PackageManagerService.java revision 78f3cf971b33aa5788f59234fbf3b93b0d0197ec
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_CPU_ABI_INCOMPATIBLE; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 32import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 36import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 37import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 38import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 39import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 41import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 43import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 44import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 46import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 47import static android.content.pm.PackageParser.isApkFile; 48import static android.os.Process.PACKAGE_INFO_GID; 49import static android.os.Process.SYSTEM_UID; 50import static android.system.OsConstants.O_CREAT; 51import static android.system.OsConstants.O_RDWR; 52import static android.system.OsConstants.S_IRGRP; 53import static android.system.OsConstants.S_IROTH; 54import static android.system.OsConstants.S_IRWXU; 55import static android.system.OsConstants.S_IXGRP; 56import static android.system.OsConstants.S_IXOTH; 57import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 58import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 59import static com.android.internal.util.ArrayUtils.appendInt; 60import static com.android.internal.util.ArrayUtils.removeInt; 61 62import android.util.ArrayMap; 63 64import com.android.internal.R; 65import com.android.internal.app.IMediaContainerService; 66import com.android.internal.app.ResolverActivity; 67import com.android.internal.content.NativeLibraryHelper; 68import com.android.internal.content.PackageHelper; 69import com.android.internal.os.IParcelFileDescriptorFactory; 70import com.android.internal.util.ArrayUtils; 71import com.android.internal.util.FastPrintWriter; 72import com.android.internal.util.FastXmlSerializer; 73import com.android.internal.util.IndentingPrintWriter; 74import com.android.internal.util.Preconditions; 75import com.android.server.EventLogTags; 76import com.android.server.IntentResolver; 77import com.android.server.LocalServices; 78import com.android.server.ServiceThread; 79import com.android.server.SystemConfig; 80import com.android.server.Watchdog; 81import com.android.server.pm.Settings.DatabaseVersion; 82import com.android.server.storage.DeviceStorageMonitorInternal; 83 84import org.xmlpull.v1.XmlSerializer; 85 86import android.app.ActivityManager; 87import android.app.ActivityManagerNative; 88import android.app.IActivityManager; 89import android.app.admin.IDevicePolicyManager; 90import android.app.backup.IBackupManager; 91import android.content.BroadcastReceiver; 92import android.content.ComponentName; 93import android.content.Context; 94import android.content.IIntentReceiver; 95import android.content.Intent; 96import android.content.IntentFilter; 97import android.content.IntentSender; 98import android.content.IntentSender.SendIntentException; 99import android.content.ServiceConnection; 100import android.content.pm.ActivityInfo; 101import android.content.pm.ApplicationInfo; 102import android.content.pm.FeatureInfo; 103import android.content.pm.IPackageDataObserver; 104import android.content.pm.IPackageDeleteObserver; 105import android.content.pm.IPackageInstallObserver2; 106import android.content.pm.IPackageInstaller; 107import android.content.pm.IPackageManager; 108import android.content.pm.IPackageMoveObserver; 109import android.content.pm.IPackageStatsObserver; 110import android.content.pm.InstallSessionParams; 111import android.content.pm.InstrumentationInfo; 112import android.content.pm.ManifestDigest; 113import android.content.pm.PackageCleanItem; 114import android.content.pm.PackageInfo; 115import android.content.pm.PackageInfoLite; 116import android.content.pm.PackageManager; 117import android.content.pm.PackageParser.ActivityIntentInfo; 118import android.content.pm.PackageParser.PackageLite; 119import android.content.pm.PackageParser.PackageParserException; 120import android.content.pm.PackageParser; 121import android.content.pm.PackageStats; 122import android.content.pm.PackageUserState; 123import android.content.pm.ParceledListSlice; 124import android.content.pm.PermissionGroupInfo; 125import android.content.pm.PermissionInfo; 126import android.content.pm.ProviderInfo; 127import android.content.pm.ResolveInfo; 128import android.content.pm.ServiceInfo; 129import android.content.pm.Signature; 130import android.content.pm.UserInfo; 131import android.content.pm.VerificationParams; 132import android.content.pm.VerifierDeviceIdentity; 133import android.content.pm.VerifierInfo; 134import android.content.res.Resources; 135import android.hardware.display.DisplayManager; 136import android.net.Uri; 137import android.os.Binder; 138import android.os.Build; 139import android.os.Bundle; 140import android.os.Environment; 141import android.os.Environment.UserEnvironment; 142import android.os.FileObserver; 143import android.os.FileUtils; 144import android.os.Handler; 145import android.os.IBinder; 146import android.os.Looper; 147import android.os.Message; 148import android.os.Parcel; 149import android.os.ParcelFileDescriptor; 150import android.os.Process; 151import android.os.RemoteException; 152import android.os.SELinux; 153import android.os.ServiceManager; 154import android.os.SystemClock; 155import android.os.SystemProperties; 156import android.os.UserHandle; 157import android.os.UserManager; 158import android.security.KeyStore; 159import android.security.SystemKeyStore; 160import android.system.ErrnoException; 161import android.system.Os; 162import android.system.StructStat; 163import android.text.TextUtils; 164import android.util.ArraySet; 165import android.util.AtomicFile; 166import android.util.DisplayMetrics; 167import android.util.EventLog; 168import android.util.ExceptionUtils; 169import android.util.Log; 170import android.util.LogPrinter; 171import android.util.PrintStreamPrinter; 172import android.util.Slog; 173import android.util.SparseArray; 174import android.util.SparseBooleanArray; 175import android.view.Display; 176 177import java.io.BufferedInputStream; 178import java.io.BufferedOutputStream; 179import java.io.File; 180import java.io.FileDescriptor; 181import java.io.FileInputStream; 182import java.io.FileNotFoundException; 183import java.io.FileOutputStream; 184import java.io.FilenameFilter; 185import java.io.IOException; 186import java.io.InputStream; 187import java.io.PrintWriter; 188import java.nio.charset.StandardCharsets; 189import java.security.NoSuchAlgorithmException; 190import java.security.PublicKey; 191import java.security.cert.CertificateEncodingException; 192import java.security.cert.CertificateException; 193import java.text.SimpleDateFormat; 194import java.util.ArrayList; 195import java.util.Arrays; 196import java.util.Collection; 197import java.util.Collections; 198import java.util.Comparator; 199import java.util.Date; 200import java.util.HashMap; 201import java.util.HashSet; 202import java.util.Iterator; 203import java.util.List; 204import java.util.Map; 205import java.util.Set; 206import java.util.concurrent.atomic.AtomicBoolean; 207import java.util.concurrent.atomic.AtomicLong; 208 209import dalvik.system.DexFile; 210import dalvik.system.StaleDexCacheError; 211import dalvik.system.VMRuntime; 212 213import libcore.io.IoUtils; 214 215/** 216 * Keep track of all those .apks everywhere. 217 * 218 * This is very central to the platform's security; please run the unit 219 * tests whenever making modifications here: 220 * 221mmm frameworks/base/tests/AndroidTests 222adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 223adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 224 * 225 * {@hide} 226 */ 227public class PackageManagerService extends IPackageManager.Stub { 228 static final String TAG = "PackageManager"; 229 static final boolean DEBUG_SETTINGS = false; 230 static final boolean DEBUG_PREFERRED = false; 231 static final boolean DEBUG_UPGRADE = false; 232 private static final boolean DEBUG_INSTALL = false; 233 private static final boolean DEBUG_REMOVE = false; 234 private static final boolean DEBUG_BROADCASTS = false; 235 private static final boolean DEBUG_SHOW_INFO = false; 236 private static final boolean DEBUG_PACKAGE_INFO = false; 237 private static final boolean DEBUG_INTENT_MATCHING = false; 238 private static final boolean DEBUG_PACKAGE_SCANNING = false; 239 private static final boolean DEBUG_APP_DIR_OBSERVER = false; 240 private static final boolean DEBUG_VERIFY = false; 241 private static final boolean DEBUG_DEXOPT = false; 242 private static final boolean DEBUG_ABI_SELECTION = false; 243 244 private static final int RADIO_UID = Process.PHONE_UID; 245 private static final int LOG_UID = Process.LOG_UID; 246 private static final int NFC_UID = Process.NFC_UID; 247 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 248 private static final int SHELL_UID = Process.SHELL_UID; 249 250 // Cap the size of permission trees that 3rd party apps can define 251 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 252 253 private static final int REMOVE_EVENTS = 254 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM; 255 private static final int ADD_EVENTS = 256 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO; 257 258 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS; 259 // Suffix used during package installation when copying/moving 260 // package apks to install directory. 261 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 262 263 static final int SCAN_MONITOR = 1<<0; 264 static final int SCAN_NO_DEX = 1<<1; 265 static final int SCAN_FORCE_DEX = 1<<2; 266 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 267 static final int SCAN_NEW_INSTALL = 1<<4; 268 static final int SCAN_NO_PATHS = 1<<5; 269 static final int SCAN_UPDATE_TIME = 1<<6; 270 static final int SCAN_DEFER_DEX = 1<<7; 271 static final int SCAN_BOOTING = 1<<8; 272 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 273 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 274 275 static final int REMOVE_CHATTY = 1<<16; 276 277 /** 278 * Timeout (in milliseconds) after which the watchdog should declare that 279 * our handler thread is wedged. The usual default for such things is one 280 * minute but we sometimes do very lengthy I/O operations on this thread, 281 * such as installing multi-gigabyte applications, so ours needs to be longer. 282 */ 283 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 284 285 /** 286 * Whether verification is enabled by default. 287 */ 288 private static final boolean DEFAULT_VERIFY_ENABLE = true; 289 290 /** 291 * The default maximum time to wait for the verification agent to return in 292 * milliseconds. 293 */ 294 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 295 296 /** 297 * The default response for package verification timeout. 298 * 299 * This can be either PackageManager.VERIFICATION_ALLOW or 300 * PackageManager.VERIFICATION_REJECT. 301 */ 302 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 303 304 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 305 306 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 307 DEFAULT_CONTAINER_PACKAGE, 308 "com.android.defcontainer.DefaultContainerService"); 309 310 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 311 312 private static final String LIB_DIR_NAME = "lib"; 313 private static final String LIB64_DIR_NAME = "lib64"; 314 315 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 316 317 static final String mTempContainerPrefix = "smdl2tmp"; 318 319 private static String sPreferredInstructionSet; 320 321 final ServiceThread mHandlerThread; 322 323 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 324 private static final String IDMAP_SUFFIX = "@idmap"; 325 326 final PackageHandler mHandler; 327 328 final int mSdkVersion = Build.VERSION.SDK_INT; 329 330 final Context mContext; 331 final boolean mFactoryTest; 332 final boolean mOnlyCore; 333 final DisplayMetrics mMetrics; 334 final int mDefParseFlags; 335 final String[] mSeparateProcesses; 336 337 // This is where all application persistent data goes. 338 final File mAppDataDir; 339 340 // This is where all application persistent data goes for secondary users. 341 final File mUserAppDataDir; 342 343 /** The location for ASEC container files on internal storage. */ 344 final String mAsecInternalPath; 345 346 // This is the object monitoring the framework dir. 347 final FileObserver mFrameworkInstallObserver; 348 349 // This is the object monitoring the system app dir. 350 final FileObserver mSystemInstallObserver; 351 352 // This is the object monitoring the privileged system app dir. 353 final FileObserver mPrivilegedInstallObserver; 354 355 // This is the object monitoring the vendor app dir. 356 final FileObserver mVendorInstallObserver; 357 358 // This is the object monitoring the vendor overlay package dir. 359 final FileObserver mVendorOverlayInstallObserver; 360 361 // This is the object monitoring the OEM app dir. 362 final FileObserver mOemInstallObserver; 363 364 // This is the object monitoring mAppInstallDir. 365 final FileObserver mAppInstallObserver; 366 367 // This is the object monitoring mDrmAppPrivateInstallDir. 368 final FileObserver mDrmAppInstallObserver; 369 370 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 371 // LOCK HELD. Can be called with mInstallLock held. 372 final Installer mInstaller; 373 374 /** Directory where installed third-party apps stored */ 375 final File mAppInstallDir; 376 377 /** 378 * Directory to which applications installed internally have their 379 * 32 bit native libraries copied. 380 */ 381 private File mAppLib32InstallDir; 382 383 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 384 // apps. 385 final File mDrmAppPrivateInstallDir; 386 387 // ---------------------------------------------------------------- 388 389 // Lock for state used when installing and doing other long running 390 // operations. Methods that must be called with this lock held have 391 // the suffix "LI". 392 final Object mInstallLock = new Object(); 393 394 // These are the directories in the 3rd party applications installed dir 395 // that we have currently loaded packages from. Keys are the application's 396 // installed zip file (absolute codePath), and values are Package. 397 final HashMap<String, PackageParser.Package> mAppDirs = 398 new HashMap<String, PackageParser.Package>(); 399 400 // ---------------------------------------------------------------- 401 402 // Keys are String (package name), values are Package. This also serves 403 // as the lock for the global state. Methods that must be called with 404 // this lock held have the prefix "LP". 405 final HashMap<String, PackageParser.Package> mPackages = 406 new HashMap<String, PackageParser.Package>(); 407 408 // Tracks available target package names -> overlay package paths. 409 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 410 new HashMap<String, HashMap<String, PackageParser.Package>>(); 411 412 final Settings mSettings; 413 boolean mRestoredSettings; 414 415 // System configuration read by SystemConfig. 416 final int[] mGlobalGids; 417 final SparseArray<HashSet<String>> mSystemPermissions; 418 final HashMap<String, FeatureInfo> mAvailableFeatures; 419 420 // If mac_permissions.xml was found for seinfo labeling. 421 boolean mFoundPolicyFile; 422 423 // If a recursive restorecon of /data/data/<pkg> is needed. 424 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 425 426 public static final class SharedLibraryEntry { 427 public final String path; 428 public final String apk; 429 430 SharedLibraryEntry(String _path, String _apk) { 431 path = _path; 432 apk = _apk; 433 } 434 } 435 436 // Currently known shared libraries. 437 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 438 new HashMap<String, SharedLibraryEntry>(); 439 440 // All available activities, for your resolving pleasure. 441 final ActivityIntentResolver mActivities = 442 new ActivityIntentResolver(); 443 444 // All available receivers, for your resolving pleasure. 445 final ActivityIntentResolver mReceivers = 446 new ActivityIntentResolver(); 447 448 // All available services, for your resolving pleasure. 449 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 450 451 // All available providers, for your resolving pleasure. 452 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 453 454 // Mapping from provider base names (first directory in content URI codePath) 455 // to the provider information. 456 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 457 new HashMap<String, PackageParser.Provider>(); 458 459 // Mapping from instrumentation class names to info about them. 460 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 461 new HashMap<ComponentName, PackageParser.Instrumentation>(); 462 463 // Mapping from permission names to info about them. 464 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 465 new HashMap<String, PackageParser.PermissionGroup>(); 466 467 // Packages whose data we have transfered into another package, thus 468 // should no longer exist. 469 final HashSet<String> mTransferedPackages = new HashSet<String>(); 470 471 // Broadcast actions that are only available to the system. 472 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 473 474 /** List of packages waiting for verification. */ 475 final SparseArray<PackageVerificationState> mPendingVerification 476 = new SparseArray<PackageVerificationState>(); 477 478 final PackageInstallerService mInstallerService; 479 480 HashSet<PackageParser.Package> mDeferredDexOpt = null; 481 482 // Cache of users who need badging. 483 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 484 485 /** Token for keys in mPendingVerification. */ 486 private int mPendingVerificationToken = 0; 487 488 boolean mSystemReady; 489 boolean mSafeMode; 490 boolean mHasSystemUidErrors; 491 492 ApplicationInfo mAndroidApplication; 493 final ActivityInfo mResolveActivity = new ActivityInfo(); 494 final ResolveInfo mResolveInfo = new ResolveInfo(); 495 ComponentName mResolveComponentName; 496 PackageParser.Package mPlatformPackage; 497 ComponentName mCustomResolverComponentName; 498 499 boolean mResolverReplaced = false; 500 501 // Set of pending broadcasts for aggregating enable/disable of components. 502 static class PendingPackageBroadcasts { 503 // for each user id, a map of <package name -> components within that package> 504 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 505 506 public PendingPackageBroadcasts() { 507 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 508 } 509 510 public ArrayList<String> get(int userId, String packageName) { 511 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 512 return packages.get(packageName); 513 } 514 515 public void put(int userId, String packageName, ArrayList<String> components) { 516 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 517 packages.put(packageName, components); 518 } 519 520 public void remove(int userId, String packageName) { 521 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 522 if (packages != null) { 523 packages.remove(packageName); 524 } 525 } 526 527 public void remove(int userId) { 528 mUidMap.remove(userId); 529 } 530 531 public int userIdCount() { 532 return mUidMap.size(); 533 } 534 535 public int userIdAt(int n) { 536 return mUidMap.keyAt(n); 537 } 538 539 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 540 return mUidMap.get(userId); 541 } 542 543 public int size() { 544 // total number of pending broadcast entries across all userIds 545 int num = 0; 546 for (int i = 0; i< mUidMap.size(); i++) { 547 num += mUidMap.valueAt(i).size(); 548 } 549 return num; 550 } 551 552 public void clear() { 553 mUidMap.clear(); 554 } 555 556 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 557 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 558 if (map == null) { 559 map = new HashMap<String, ArrayList<String>>(); 560 mUidMap.put(userId, map); 561 } 562 return map; 563 } 564 } 565 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 566 567 // Service Connection to remote media container service to copy 568 // package uri's from external media onto secure containers 569 // or internal storage. 570 private IMediaContainerService mContainerService = null; 571 572 static final int SEND_PENDING_BROADCAST = 1; 573 static final int MCS_BOUND = 3; 574 static final int END_COPY = 4; 575 static final int INIT_COPY = 5; 576 static final int MCS_UNBIND = 6; 577 static final int START_CLEANING_PACKAGE = 7; 578 static final int FIND_INSTALL_LOC = 8; 579 static final int POST_INSTALL = 9; 580 static final int MCS_RECONNECT = 10; 581 static final int MCS_GIVE_UP = 11; 582 static final int UPDATED_MEDIA_STATUS = 12; 583 static final int WRITE_SETTINGS = 13; 584 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 585 static final int PACKAGE_VERIFIED = 15; 586 static final int CHECK_PENDING_VERIFICATION = 16; 587 588 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 589 590 // Delay time in millisecs 591 static final int BROADCAST_DELAY = 10 * 1000; 592 593 static UserManagerService sUserManager; 594 595 // Stores a list of users whose package restrictions file needs to be updated 596 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 597 598 final private DefaultContainerConnection mDefContainerConn = 599 new DefaultContainerConnection(); 600 class DefaultContainerConnection implements ServiceConnection { 601 public void onServiceConnected(ComponentName name, IBinder service) { 602 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 603 IMediaContainerService imcs = 604 IMediaContainerService.Stub.asInterface(service); 605 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 606 } 607 608 public void onServiceDisconnected(ComponentName name) { 609 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 610 } 611 }; 612 613 // Recordkeeping of restore-after-install operations that are currently in flight 614 // between the Package Manager and the Backup Manager 615 class PostInstallData { 616 public InstallArgs args; 617 public PackageInstalledInfo res; 618 619 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 620 args = _a; 621 res = _r; 622 } 623 }; 624 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 625 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 626 627 private final String mRequiredVerifierPackage; 628 629 private final PackageUsage mPackageUsage = new PackageUsage(); 630 631 private class PackageUsage { 632 private static final int WRITE_INTERVAL 633 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 634 635 private final Object mFileLock = new Object(); 636 private final AtomicLong mLastWritten = new AtomicLong(0); 637 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 638 639 private boolean mIsHistoricalPackageUsageAvailable = true; 640 641 boolean isHistoricalPackageUsageAvailable() { 642 return mIsHistoricalPackageUsageAvailable; 643 } 644 645 void write(boolean force) { 646 if (force) { 647 writeInternal(); 648 return; 649 } 650 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 651 && !DEBUG_DEXOPT) { 652 return; 653 } 654 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 655 new Thread("PackageUsage_DiskWriter") { 656 @Override 657 public void run() { 658 try { 659 writeInternal(); 660 } finally { 661 mBackgroundWriteRunning.set(false); 662 } 663 } 664 }.start(); 665 } 666 } 667 668 private void writeInternal() { 669 synchronized (mPackages) { 670 synchronized (mFileLock) { 671 AtomicFile file = getFile(); 672 FileOutputStream f = null; 673 try { 674 f = file.startWrite(); 675 BufferedOutputStream out = new BufferedOutputStream(f); 676 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 677 StringBuilder sb = new StringBuilder(); 678 for (PackageParser.Package pkg : mPackages.values()) { 679 if (pkg.mLastPackageUsageTimeInMills == 0) { 680 continue; 681 } 682 sb.setLength(0); 683 sb.append(pkg.packageName); 684 sb.append(' '); 685 sb.append((long)pkg.mLastPackageUsageTimeInMills); 686 sb.append('\n'); 687 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 688 } 689 out.flush(); 690 file.finishWrite(f); 691 } catch (IOException e) { 692 if (f != null) { 693 file.failWrite(f); 694 } 695 Log.e(TAG, "Failed to write package usage times", e); 696 } 697 } 698 } 699 mLastWritten.set(SystemClock.elapsedRealtime()); 700 } 701 702 void readLP() { 703 synchronized (mFileLock) { 704 AtomicFile file = getFile(); 705 BufferedInputStream in = null; 706 try { 707 in = new BufferedInputStream(file.openRead()); 708 StringBuffer sb = new StringBuffer(); 709 while (true) { 710 String packageName = readToken(in, sb, ' '); 711 if (packageName == null) { 712 break; 713 } 714 String timeInMillisString = readToken(in, sb, '\n'); 715 if (timeInMillisString == null) { 716 throw new IOException("Failed to find last usage time for package " 717 + packageName); 718 } 719 PackageParser.Package pkg = mPackages.get(packageName); 720 if (pkg == null) { 721 continue; 722 } 723 long timeInMillis; 724 try { 725 timeInMillis = Long.parseLong(timeInMillisString.toString()); 726 } catch (NumberFormatException e) { 727 throw new IOException("Failed to parse " + timeInMillisString 728 + " as a long.", e); 729 } 730 pkg.mLastPackageUsageTimeInMills = timeInMillis; 731 } 732 } catch (FileNotFoundException expected) { 733 mIsHistoricalPackageUsageAvailable = false; 734 } catch (IOException e) { 735 Log.w(TAG, "Failed to read package usage times", e); 736 } finally { 737 IoUtils.closeQuietly(in); 738 } 739 } 740 mLastWritten.set(SystemClock.elapsedRealtime()); 741 } 742 743 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 744 throws IOException { 745 sb.setLength(0); 746 while (true) { 747 int ch = in.read(); 748 if (ch == -1) { 749 if (sb.length() == 0) { 750 return null; 751 } 752 throw new IOException("Unexpected EOF"); 753 } 754 if (ch == endOfToken) { 755 return sb.toString(); 756 } 757 sb.append((char)ch); 758 } 759 } 760 761 private AtomicFile getFile() { 762 File dataDir = Environment.getDataDirectory(); 763 File systemDir = new File(dataDir, "system"); 764 File fname = new File(systemDir, "package-usage.list"); 765 return new AtomicFile(fname); 766 } 767 } 768 769 class PackageHandler extends Handler { 770 private boolean mBound = false; 771 final ArrayList<HandlerParams> mPendingInstalls = 772 new ArrayList<HandlerParams>(); 773 774 private boolean connectToService() { 775 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 776 " DefaultContainerService"); 777 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 778 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 779 if (mContext.bindServiceAsUser(service, mDefContainerConn, 780 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 781 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 782 mBound = true; 783 return true; 784 } 785 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 786 return false; 787 } 788 789 private void disconnectService() { 790 mContainerService = null; 791 mBound = false; 792 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 793 mContext.unbindService(mDefContainerConn); 794 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 795 } 796 797 PackageHandler(Looper looper) { 798 super(looper); 799 } 800 801 public void handleMessage(Message msg) { 802 try { 803 doHandleMessage(msg); 804 } finally { 805 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 806 } 807 } 808 809 void doHandleMessage(Message msg) { 810 switch (msg.what) { 811 case INIT_COPY: { 812 HandlerParams params = (HandlerParams) msg.obj; 813 int idx = mPendingInstalls.size(); 814 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 815 // If a bind was already initiated we dont really 816 // need to do anything. The pending install 817 // will be processed later on. 818 if (!mBound) { 819 // If this is the only one pending we might 820 // have to bind to the service again. 821 if (!connectToService()) { 822 Slog.e(TAG, "Failed to bind to media container service"); 823 params.serviceError(); 824 return; 825 } else { 826 // Once we bind to the service, the first 827 // pending request will be processed. 828 mPendingInstalls.add(idx, params); 829 } 830 } else { 831 mPendingInstalls.add(idx, params); 832 // Already bound to the service. Just make 833 // sure we trigger off processing the first request. 834 if (idx == 0) { 835 mHandler.sendEmptyMessage(MCS_BOUND); 836 } 837 } 838 break; 839 } 840 case MCS_BOUND: { 841 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 842 if (msg.obj != null) { 843 mContainerService = (IMediaContainerService) msg.obj; 844 } 845 if (mContainerService == null) { 846 // Something seriously wrong. Bail out 847 Slog.e(TAG, "Cannot bind to media container service"); 848 for (HandlerParams params : mPendingInstalls) { 849 // Indicate service bind error 850 params.serviceError(); 851 } 852 mPendingInstalls.clear(); 853 } else if (mPendingInstalls.size() > 0) { 854 HandlerParams params = mPendingInstalls.get(0); 855 if (params != null) { 856 if (params.startCopy()) { 857 // We are done... look for more work or to 858 // go idle. 859 if (DEBUG_SD_INSTALL) Log.i(TAG, 860 "Checking for more work or unbind..."); 861 // Delete pending install 862 if (mPendingInstalls.size() > 0) { 863 mPendingInstalls.remove(0); 864 } 865 if (mPendingInstalls.size() == 0) { 866 if (mBound) { 867 if (DEBUG_SD_INSTALL) Log.i(TAG, 868 "Posting delayed MCS_UNBIND"); 869 removeMessages(MCS_UNBIND); 870 Message ubmsg = obtainMessage(MCS_UNBIND); 871 // Unbind after a little delay, to avoid 872 // continual thrashing. 873 sendMessageDelayed(ubmsg, 10000); 874 } 875 } else { 876 // There are more pending requests in queue. 877 // Just post MCS_BOUND message to trigger processing 878 // of next pending install. 879 if (DEBUG_SD_INSTALL) Log.i(TAG, 880 "Posting MCS_BOUND for next work"); 881 mHandler.sendEmptyMessage(MCS_BOUND); 882 } 883 } 884 } 885 } else { 886 // Should never happen ideally. 887 Slog.w(TAG, "Empty queue"); 888 } 889 break; 890 } 891 case MCS_RECONNECT: { 892 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 893 if (mPendingInstalls.size() > 0) { 894 if (mBound) { 895 disconnectService(); 896 } 897 if (!connectToService()) { 898 Slog.e(TAG, "Failed to bind to media container service"); 899 for (HandlerParams params : mPendingInstalls) { 900 // Indicate service bind error 901 params.serviceError(); 902 } 903 mPendingInstalls.clear(); 904 } 905 } 906 break; 907 } 908 case MCS_UNBIND: { 909 // If there is no actual work left, then time to unbind. 910 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 911 912 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 913 if (mBound) { 914 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 915 916 disconnectService(); 917 } 918 } else if (mPendingInstalls.size() > 0) { 919 // There are more pending requests in queue. 920 // Just post MCS_BOUND message to trigger processing 921 // of next pending install. 922 mHandler.sendEmptyMessage(MCS_BOUND); 923 } 924 925 break; 926 } 927 case MCS_GIVE_UP: { 928 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 929 mPendingInstalls.remove(0); 930 break; 931 } 932 case SEND_PENDING_BROADCAST: { 933 String packages[]; 934 ArrayList<String> components[]; 935 int size = 0; 936 int uids[]; 937 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 938 synchronized (mPackages) { 939 if (mPendingBroadcasts == null) { 940 return; 941 } 942 size = mPendingBroadcasts.size(); 943 if (size <= 0) { 944 // Nothing to be done. Just return 945 return; 946 } 947 packages = new String[size]; 948 components = new ArrayList[size]; 949 uids = new int[size]; 950 int i = 0; // filling out the above arrays 951 952 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 953 int packageUserId = mPendingBroadcasts.userIdAt(n); 954 Iterator<Map.Entry<String, ArrayList<String>>> it 955 = mPendingBroadcasts.packagesForUserId(packageUserId) 956 .entrySet().iterator(); 957 while (it.hasNext() && i < size) { 958 Map.Entry<String, ArrayList<String>> ent = it.next(); 959 packages[i] = ent.getKey(); 960 components[i] = ent.getValue(); 961 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 962 uids[i] = (ps != null) 963 ? UserHandle.getUid(packageUserId, ps.appId) 964 : -1; 965 i++; 966 } 967 } 968 size = i; 969 mPendingBroadcasts.clear(); 970 } 971 // Send broadcasts 972 for (int i = 0; i < size; i++) { 973 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 974 } 975 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 976 break; 977 } 978 case START_CLEANING_PACKAGE: { 979 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 980 final String packageName = (String)msg.obj; 981 final int userId = msg.arg1; 982 final boolean andCode = msg.arg2 != 0; 983 synchronized (mPackages) { 984 if (userId == UserHandle.USER_ALL) { 985 int[] users = sUserManager.getUserIds(); 986 for (int user : users) { 987 mSettings.addPackageToCleanLPw( 988 new PackageCleanItem(user, packageName, andCode)); 989 } 990 } else { 991 mSettings.addPackageToCleanLPw( 992 new PackageCleanItem(userId, packageName, andCode)); 993 } 994 } 995 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 996 startCleaningPackages(); 997 } break; 998 case POST_INSTALL: { 999 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1000 PostInstallData data = mRunningInstalls.get(msg.arg1); 1001 mRunningInstalls.delete(msg.arg1); 1002 boolean deleteOld = false; 1003 1004 if (data != null) { 1005 InstallArgs args = data.args; 1006 PackageInstalledInfo res = data.res; 1007 1008 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1009 res.removedInfo.sendBroadcast(false, true, false); 1010 Bundle extras = new Bundle(1); 1011 extras.putInt(Intent.EXTRA_UID, res.uid); 1012 // Determine the set of users who are adding this 1013 // package for the first time vs. those who are seeing 1014 // an update. 1015 int[] firstUsers; 1016 int[] updateUsers = new int[0]; 1017 if (res.origUsers == null || res.origUsers.length == 0) { 1018 firstUsers = res.newUsers; 1019 } else { 1020 firstUsers = new int[0]; 1021 for (int i=0; i<res.newUsers.length; i++) { 1022 int user = res.newUsers[i]; 1023 boolean isNew = true; 1024 for (int j=0; j<res.origUsers.length; j++) { 1025 if (res.origUsers[j] == user) { 1026 isNew = false; 1027 break; 1028 } 1029 } 1030 if (isNew) { 1031 int[] newFirst = new int[firstUsers.length+1]; 1032 System.arraycopy(firstUsers, 0, newFirst, 0, 1033 firstUsers.length); 1034 newFirst[firstUsers.length] = user; 1035 firstUsers = newFirst; 1036 } else { 1037 int[] newUpdate = new int[updateUsers.length+1]; 1038 System.arraycopy(updateUsers, 0, newUpdate, 0, 1039 updateUsers.length); 1040 newUpdate[updateUsers.length] = user; 1041 updateUsers = newUpdate; 1042 } 1043 } 1044 } 1045 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1046 res.pkg.applicationInfo.packageName, 1047 extras, null, null, firstUsers); 1048 final boolean update = res.removedInfo.removedPackage != null; 1049 if (update) { 1050 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1051 } 1052 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1053 res.pkg.applicationInfo.packageName, 1054 extras, null, null, updateUsers); 1055 if (update) { 1056 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1057 res.pkg.applicationInfo.packageName, 1058 extras, null, null, updateUsers); 1059 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1060 null, null, 1061 res.pkg.applicationInfo.packageName, null, updateUsers); 1062 1063 // treat asec-hosted packages like removable media on upgrade 1064 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1065 if (DEBUG_INSTALL) { 1066 Slog.i(TAG, "upgrading pkg " + res.pkg 1067 + " is ASEC-hosted -> AVAILABLE"); 1068 } 1069 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1070 ArrayList<String> pkgList = new ArrayList<String>(1); 1071 pkgList.add(res.pkg.applicationInfo.packageName); 1072 sendResourcesChangedBroadcast(true, true, 1073 pkgList,uidArray, null); 1074 } 1075 } 1076 if (res.removedInfo.args != null) { 1077 // Remove the replaced package's older resources safely now 1078 deleteOld = true; 1079 } 1080 1081 // Log current value of "unknown sources" setting 1082 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1083 getUnknownSourcesSettings()); 1084 } 1085 // Force a gc to clear up things 1086 Runtime.getRuntime().gc(); 1087 // We delete after a gc for applications on sdcard. 1088 if (deleteOld) { 1089 synchronized (mInstallLock) { 1090 res.removedInfo.args.doPostDeleteLI(true); 1091 } 1092 } 1093 if (args.observer != null) { 1094 try { 1095 Bundle extras = extrasForInstallResult(res); 1096 args.observer.packageInstalled(res.name, extras, res.returnCode, 1097 res.returnMsg); 1098 } catch (RemoteException e) { 1099 Slog.i(TAG, "Observer no longer exists."); 1100 } 1101 } 1102 } else { 1103 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1104 } 1105 } break; 1106 case UPDATED_MEDIA_STATUS: { 1107 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1108 boolean reportStatus = msg.arg1 == 1; 1109 boolean doGc = msg.arg2 == 1; 1110 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1111 if (doGc) { 1112 // Force a gc to clear up stale containers. 1113 Runtime.getRuntime().gc(); 1114 } 1115 if (msg.obj != null) { 1116 @SuppressWarnings("unchecked") 1117 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1118 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1119 // Unload containers 1120 unloadAllContainers(args); 1121 } 1122 if (reportStatus) { 1123 try { 1124 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1125 PackageHelper.getMountService().finishMediaUpdate(); 1126 } catch (RemoteException e) { 1127 Log.e(TAG, "MountService not running?"); 1128 } 1129 } 1130 } break; 1131 case WRITE_SETTINGS: { 1132 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1133 synchronized (mPackages) { 1134 removeMessages(WRITE_SETTINGS); 1135 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1136 mSettings.writeLPr(); 1137 mDirtyUsers.clear(); 1138 } 1139 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1140 } break; 1141 case WRITE_PACKAGE_RESTRICTIONS: { 1142 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1143 synchronized (mPackages) { 1144 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1145 for (int userId : mDirtyUsers) { 1146 mSettings.writePackageRestrictionsLPr(userId); 1147 } 1148 mDirtyUsers.clear(); 1149 } 1150 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1151 } break; 1152 case CHECK_PENDING_VERIFICATION: { 1153 final int verificationId = msg.arg1; 1154 final PackageVerificationState state = mPendingVerification.get(verificationId); 1155 1156 if ((state != null) && !state.timeoutExtended()) { 1157 final InstallArgs args = state.getInstallArgs(); 1158 final Uri originUri = Uri.fromFile(args.originFile); 1159 1160 Slog.i(TAG, "Verification timed out for " + originUri); 1161 mPendingVerification.remove(verificationId); 1162 1163 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1164 1165 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1166 Slog.i(TAG, "Continuing with installation of " + originUri); 1167 state.setVerifierResponse(Binder.getCallingUid(), 1168 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1169 broadcastPackageVerified(verificationId, originUri, 1170 PackageManager.VERIFICATION_ALLOW, 1171 state.getInstallArgs().getUser()); 1172 try { 1173 ret = args.copyApk(mContainerService, true); 1174 } catch (RemoteException e) { 1175 Slog.e(TAG, "Could not contact the ContainerService"); 1176 } 1177 } else { 1178 broadcastPackageVerified(verificationId, originUri, 1179 PackageManager.VERIFICATION_REJECT, 1180 state.getInstallArgs().getUser()); 1181 } 1182 1183 processPendingInstall(args, ret); 1184 mHandler.sendEmptyMessage(MCS_UNBIND); 1185 } 1186 break; 1187 } 1188 case PACKAGE_VERIFIED: { 1189 final int verificationId = msg.arg1; 1190 1191 final PackageVerificationState state = mPendingVerification.get(verificationId); 1192 if (state == null) { 1193 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1194 break; 1195 } 1196 1197 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1198 1199 state.setVerifierResponse(response.callerUid, response.code); 1200 1201 if (state.isVerificationComplete()) { 1202 mPendingVerification.remove(verificationId); 1203 1204 final InstallArgs args = state.getInstallArgs(); 1205 final Uri originUri = Uri.fromFile(args.originFile); 1206 1207 int ret; 1208 if (state.isInstallAllowed()) { 1209 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1210 broadcastPackageVerified(verificationId, originUri, 1211 response.code, state.getInstallArgs().getUser()); 1212 try { 1213 ret = args.copyApk(mContainerService, true); 1214 } catch (RemoteException e) { 1215 Slog.e(TAG, "Could not contact the ContainerService"); 1216 } 1217 } else { 1218 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1219 } 1220 1221 processPendingInstall(args, ret); 1222 1223 mHandler.sendEmptyMessage(MCS_UNBIND); 1224 } 1225 1226 break; 1227 } 1228 } 1229 } 1230 } 1231 1232 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1233 Bundle extras = null; 1234 switch (res.returnCode) { 1235 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1236 extras = new Bundle(); 1237 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1238 res.origPermission); 1239 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1240 res.origPackage); 1241 break; 1242 } 1243 } 1244 return extras; 1245 } 1246 1247 void scheduleWriteSettingsLocked() { 1248 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1249 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1250 } 1251 } 1252 1253 void scheduleWritePackageRestrictionsLocked(int userId) { 1254 if (!sUserManager.exists(userId)) return; 1255 mDirtyUsers.add(userId); 1256 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1257 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1258 } 1259 } 1260 1261 public static final PackageManagerService main(Context context, Installer installer, 1262 boolean factoryTest, boolean onlyCore) { 1263 PackageManagerService m = new PackageManagerService(context, installer, 1264 factoryTest, onlyCore); 1265 ServiceManager.addService("package", m); 1266 return m; 1267 } 1268 1269 static String[] splitString(String str, char sep) { 1270 int count = 1; 1271 int i = 0; 1272 while ((i=str.indexOf(sep, i)) >= 0) { 1273 count++; 1274 i++; 1275 } 1276 1277 String[] res = new String[count]; 1278 i=0; 1279 count = 0; 1280 int lastI=0; 1281 while ((i=str.indexOf(sep, i)) >= 0) { 1282 res[count] = str.substring(lastI, i); 1283 count++; 1284 i++; 1285 lastI = i; 1286 } 1287 res[count] = str.substring(lastI, str.length()); 1288 return res; 1289 } 1290 1291 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1292 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1293 Context.DISPLAY_SERVICE); 1294 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1295 } 1296 1297 public PackageManagerService(Context context, Installer installer, 1298 boolean factoryTest, boolean onlyCore) { 1299 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1300 SystemClock.uptimeMillis()); 1301 1302 if (mSdkVersion <= 0) { 1303 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1304 } 1305 1306 mContext = context; 1307 mFactoryTest = factoryTest; 1308 mOnlyCore = onlyCore; 1309 mMetrics = new DisplayMetrics(); 1310 mSettings = new Settings(context); 1311 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1312 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1313 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1314 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1315 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1316 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1317 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1318 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1319 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1320 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1321 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1322 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1323 1324 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1325 if (separateProcesses != null && separateProcesses.length() > 0) { 1326 if ("*".equals(separateProcesses)) { 1327 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1328 mSeparateProcesses = null; 1329 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1330 } else { 1331 mDefParseFlags = 0; 1332 mSeparateProcesses = separateProcesses.split(","); 1333 Slog.w(TAG, "Running with debug.separate_processes: " 1334 + separateProcesses); 1335 } 1336 } else { 1337 mDefParseFlags = 0; 1338 mSeparateProcesses = null; 1339 } 1340 1341 mInstaller = installer; 1342 1343 getDefaultDisplayMetrics(context, mMetrics); 1344 1345 SystemConfig systemConfig = SystemConfig.getInstance(); 1346 mGlobalGids = systemConfig.getGlobalGids(); 1347 mSystemPermissions = systemConfig.getSystemPermissions(); 1348 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1349 1350 synchronized (mInstallLock) { 1351 // writer 1352 synchronized (mPackages) { 1353 mHandlerThread = new ServiceThread(TAG, 1354 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1355 mHandlerThread.start(); 1356 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1357 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1358 1359 File dataDir = Environment.getDataDirectory(); 1360 mAppDataDir = new File(dataDir, "data"); 1361 mAppInstallDir = new File(dataDir, "app"); 1362 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1363 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1364 mUserAppDataDir = new File(dataDir, "user"); 1365 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1366 1367 sUserManager = new UserManagerService(context, this, 1368 mInstallLock, mPackages); 1369 1370 // Propagate permission configuration in to package manager. 1371 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1372 = systemConfig.getPermissions(); 1373 for (int i=0; i<permConfig.size(); i++) { 1374 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1375 BasePermission bp = mSettings.mPermissions.get(perm.name); 1376 if (bp == null) { 1377 bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN); 1378 mSettings.mPermissions.put(perm.name, bp); 1379 } 1380 if (perm.gids != null) { 1381 bp.gids = appendInts(bp.gids, perm.gids); 1382 } 1383 } 1384 1385 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1386 for (int i=0; i<libConfig.size(); i++) { 1387 mSharedLibraries.put(libConfig.keyAt(i), 1388 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1389 } 1390 1391 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1392 1393 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1394 mSdkVersion, mOnlyCore); 1395 1396 String customResolverActivity = Resources.getSystem().getString( 1397 R.string.config_customResolverActivity); 1398 if (TextUtils.isEmpty(customResolverActivity)) { 1399 customResolverActivity = null; 1400 } else { 1401 mCustomResolverComponentName = ComponentName.unflattenFromString( 1402 customResolverActivity); 1403 } 1404 1405 long startTime = SystemClock.uptimeMillis(); 1406 1407 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1408 startTime); 1409 1410 // Set flag to monitor and not change apk file paths when 1411 // scanning install directories. 1412 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1413 1414 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1415 1416 /** 1417 * Add everything in the in the boot class path to the 1418 * list of process files because dexopt will have been run 1419 * if necessary during zygote startup. 1420 */ 1421 String bootClassPath = System.getProperty("java.boot.class.path"); 1422 if (bootClassPath != null) { 1423 String[] paths = splitString(bootClassPath, ':'); 1424 for (int i=0; i<paths.length; i++) { 1425 alreadyDexOpted.add(paths[i]); 1426 } 1427 } else { 1428 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1429 } 1430 1431 boolean didDexOptLibraryOrTool = false; 1432 1433 final List<String> instructionSets = getAllInstructionSets(); 1434 1435 /** 1436 * Ensure all external libraries have had dexopt run on them. 1437 */ 1438 if (mSharedLibraries.size() > 0) { 1439 // NOTE: For now, we're compiling these system "shared libraries" 1440 // (and framework jars) into all available architectures. It's possible 1441 // to compile them only when we come across an app that uses them (there's 1442 // already logic for that in scanPackageLI) but that adds some complexity. 1443 for (String instructionSet : instructionSets) { 1444 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1445 final String lib = libEntry.path; 1446 if (lib == null) { 1447 continue; 1448 } 1449 1450 try { 1451 if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) { 1452 alreadyDexOpted.add(lib); 1453 1454 // The list of "shared libraries" we have at this point is 1455 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet); 1456 didDexOptLibraryOrTool = true; 1457 } 1458 } catch (FileNotFoundException e) { 1459 Slog.w(TAG, "Library not found: " + lib); 1460 } catch (IOException e) { 1461 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1462 + e.getMessage()); 1463 } 1464 } 1465 } 1466 } 1467 1468 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1469 1470 // Gross hack for now: we know this file doesn't contain any 1471 // code, so don't dexopt it to avoid the resulting log spew. 1472 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1473 1474 // Gross hack for now: we know this file is only part of 1475 // the boot class path for art, so don't dexopt it to 1476 // avoid the resulting log spew. 1477 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1478 1479 /** 1480 * And there are a number of commands implemented in Java, which 1481 * we currently need to do the dexopt on so that they can be 1482 * run from a non-root shell. 1483 */ 1484 String[] frameworkFiles = frameworkDir.list(); 1485 if (frameworkFiles != null) { 1486 // TODO: We could compile these only for the most preferred ABI. We should 1487 // first double check that the dex files for these commands are not referenced 1488 // by other system apps. 1489 for (String instructionSet : instructionSets) { 1490 for (int i=0; i<frameworkFiles.length; i++) { 1491 File libPath = new File(frameworkDir, frameworkFiles[i]); 1492 String path = libPath.getPath(); 1493 // Skip the file if we already did it. 1494 if (alreadyDexOpted.contains(path)) { 1495 continue; 1496 } 1497 // Skip the file if it is not a type we want to dexopt. 1498 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1499 continue; 1500 } 1501 try { 1502 if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) { 1503 mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet); 1504 didDexOptLibraryOrTool = true; 1505 } 1506 } catch (FileNotFoundException e) { 1507 Slog.w(TAG, "Jar not found: " + path); 1508 } catch (IOException e) { 1509 Slog.w(TAG, "Exception reading jar: " + path, e); 1510 } 1511 } 1512 } 1513 } 1514 1515 if (didDexOptLibraryOrTool) { 1516 // If we dexopted a library or tool, then something on the system has 1517 // changed. Consider this significant, and wipe away all other 1518 // existing dexopt files to ensure we don't leave any dangling around. 1519 // 1520 // TODO: This should be revisited because it isn't as good an indicator 1521 // as it used to be. It used to include the boot classpath but at some point 1522 // DexFile.isDexOptNeeded started returning false for the boot 1523 // class path files in all cases. It is very possible in a 1524 // small maintenance release update that the library and tool 1525 // jars may be unchanged but APK could be removed resulting in 1526 // unused dalvik-cache files. 1527 for (String instructionSet : instructionSets) { 1528 mInstaller.pruneDexCache(instructionSet); 1529 } 1530 1531 // Additionally, delete all dex files from the root directory 1532 // since there shouldn't be any there anyway, unless we're upgrading 1533 // from an older OS version or a build that contained the "old" style 1534 // flat scheme. 1535 mInstaller.pruneDexCache("."); 1536 } 1537 1538 // Collect vendor overlay packages. 1539 // (Do this before scanning any apps.) 1540 // For security and version matching reason, only consider 1541 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1542 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1543 mVendorOverlayInstallObserver = new AppDirObserver( 1544 vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false); 1545 mVendorOverlayInstallObserver.startWatching(); 1546 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1547 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1548 1549 // Find base frameworks (resource packages without code). 1550 mFrameworkInstallObserver = new AppDirObserver( 1551 frameworkDir.getPath(), OBSERVER_EVENTS, true, false); 1552 mFrameworkInstallObserver.startWatching(); 1553 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1554 | PackageParser.PARSE_IS_SYSTEM_DIR 1555 | PackageParser.PARSE_IS_PRIVILEGED, 1556 scanMode | SCAN_NO_DEX, 0); 1557 1558 // Collected privileged system packages. 1559 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1560 mPrivilegedInstallObserver = new AppDirObserver( 1561 privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true); 1562 mPrivilegedInstallObserver.startWatching(); 1563 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1564 | PackageParser.PARSE_IS_SYSTEM_DIR 1565 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1566 1567 // Collect ordinary system packages. 1568 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1569 mSystemInstallObserver = new AppDirObserver( 1570 systemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1571 mSystemInstallObserver.startWatching(); 1572 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1573 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1574 1575 // Collect all vendor packages. 1576 File vendorAppDir = new File("/vendor/app"); 1577 try { 1578 vendorAppDir = vendorAppDir.getCanonicalFile(); 1579 } catch (IOException e) { 1580 // failed to look up canonical path, continue with original one 1581 } 1582 mVendorInstallObserver = new AppDirObserver( 1583 vendorAppDir.getPath(), OBSERVER_EVENTS, true, false); 1584 mVendorInstallObserver.startWatching(); 1585 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1586 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1587 1588 // Collect all OEM packages. 1589 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1590 mOemInstallObserver = new AppDirObserver( 1591 oemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1592 mOemInstallObserver.startWatching(); 1593 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1594 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1595 1596 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1597 mInstaller.moveFiles(); 1598 1599 // Prune any system packages that no longer exist. 1600 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1601 if (!mOnlyCore) { 1602 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1603 while (psit.hasNext()) { 1604 PackageSetting ps = psit.next(); 1605 1606 /* 1607 * If this is not a system app, it can't be a 1608 * disable system app. 1609 */ 1610 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1611 continue; 1612 } 1613 1614 /* 1615 * If the package is scanned, it's not erased. 1616 */ 1617 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1618 if (scannedPkg != null) { 1619 /* 1620 * If the system app is both scanned and in the 1621 * disabled packages list, then it must have been 1622 * added via OTA. Remove it from the currently 1623 * scanned package so the previously user-installed 1624 * application can be scanned. 1625 */ 1626 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1627 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1628 + "; removing system app"); 1629 removePackageLI(ps, true); 1630 } 1631 1632 continue; 1633 } 1634 1635 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1636 psit.remove(); 1637 String msg = "System package " + ps.name 1638 + " no longer exists; wiping its data"; 1639 reportSettingsProblem(Log.WARN, msg); 1640 removeDataDirsLI(ps.name); 1641 } else { 1642 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1643 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1644 possiblyDeletedUpdatedSystemApps.add(ps.name); 1645 } 1646 } 1647 } 1648 } 1649 1650 //look for any incomplete package installations 1651 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1652 //clean up list 1653 for(int i = 0; i < deletePkgsList.size(); i++) { 1654 //clean up here 1655 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1656 } 1657 //delete tmp files 1658 deleteTempPackageFiles(); 1659 1660 // Remove any shared userIDs that have no associated packages 1661 mSettings.pruneSharedUsersLPw(); 1662 1663 if (!mOnlyCore) { 1664 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1665 SystemClock.uptimeMillis()); 1666 mAppInstallObserver = new AppDirObserver( 1667 mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1668 mAppInstallObserver.startWatching(); 1669 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1670 1671 mDrmAppInstallObserver = new AppDirObserver( 1672 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1673 mDrmAppInstallObserver.startWatching(); 1674 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1675 scanMode, 0); 1676 1677 /** 1678 * Remove disable package settings for any updated system 1679 * apps that were removed via an OTA. If they're not a 1680 * previously-updated app, remove them completely. 1681 * Otherwise, just revoke their system-level permissions. 1682 */ 1683 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1684 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1685 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1686 1687 String msg; 1688 if (deletedPkg == null) { 1689 msg = "Updated system package " + deletedAppName 1690 + " no longer exists; wiping its data"; 1691 removeDataDirsLI(deletedAppName); 1692 } else { 1693 msg = "Updated system app + " + deletedAppName 1694 + " no longer present; removing system privileges for " 1695 + deletedAppName; 1696 1697 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1698 1699 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1700 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1701 } 1702 reportSettingsProblem(Log.WARN, msg); 1703 } 1704 } else { 1705 mAppInstallObserver = null; 1706 mDrmAppInstallObserver = null; 1707 } 1708 1709 // Now that we know all of the shared libraries, update all clients to have 1710 // the correct library paths. 1711 updateAllSharedLibrariesLPw(); 1712 1713 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1714 // NOTE: We ignore potential failures here during a system scan (like 1715 // the rest of the commands above) because there's precious little we 1716 // can do about it. A settings error is reported, though. 1717 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1718 false /* force dexopt */, false /* defer dexopt */); 1719 } 1720 1721 // Now that we know all the packages we are keeping, 1722 // read and update their last usage times. 1723 mPackageUsage.readLP(); 1724 1725 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1726 SystemClock.uptimeMillis()); 1727 Slog.i(TAG, "Time to scan packages: " 1728 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1729 + " seconds"); 1730 1731 // If the platform SDK has changed since the last time we booted, 1732 // we need to re-grant app permission to catch any new ones that 1733 // appear. This is really a hack, and means that apps can in some 1734 // cases get permissions that the user didn't initially explicitly 1735 // allow... it would be nice to have some better way to handle 1736 // this situation. 1737 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1738 != mSdkVersion; 1739 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1740 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1741 + "; regranting permissions for internal storage"); 1742 mSettings.mInternalSdkPlatform = mSdkVersion; 1743 1744 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1745 | (regrantPermissions 1746 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1747 : 0)); 1748 1749 // If this is the first boot, and it is a normal boot, then 1750 // we need to initialize the default preferred apps. 1751 if (!mRestoredSettings && !onlyCore) { 1752 mSettings.readDefaultPreferredAppsLPw(this, 0); 1753 } 1754 1755 // If this is first boot after an OTA, and a normal boot, then 1756 // we need to clear code cache directories. 1757 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1758 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1759 for (String pkgName : mSettings.mPackages.keySet()) { 1760 deleteCodeCacheDirsLI(pkgName); 1761 } 1762 mSettings.mFingerprint = Build.FINGERPRINT; 1763 } 1764 1765 // All the changes are done during package scanning. 1766 mSettings.updateInternalDatabaseVersion(); 1767 1768 // can downgrade to reader 1769 mSettings.writeLPr(); 1770 1771 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1772 SystemClock.uptimeMillis()); 1773 1774 1775 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1776 } // synchronized (mPackages) 1777 } // synchronized (mInstallLock) 1778 1779 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1780 1781 // Now after opening every single application zip, make sure they 1782 // are all flushed. Not really needed, but keeps things nice and 1783 // tidy. 1784 Runtime.getRuntime().gc(); 1785 } 1786 1787 @Override 1788 public boolean isFirstBoot() { 1789 return !mRestoredSettings; 1790 } 1791 1792 @Override 1793 public boolean isOnlyCoreApps() { 1794 return mOnlyCore; 1795 } 1796 1797 private String getRequiredVerifierLPr() { 1798 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1799 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1800 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1801 1802 String requiredVerifier = null; 1803 1804 final int N = receivers.size(); 1805 for (int i = 0; i < N; i++) { 1806 final ResolveInfo info = receivers.get(i); 1807 1808 if (info.activityInfo == null) { 1809 continue; 1810 } 1811 1812 final String packageName = info.activityInfo.packageName; 1813 1814 final PackageSetting ps = mSettings.mPackages.get(packageName); 1815 if (ps == null) { 1816 continue; 1817 } 1818 1819 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1820 if (!gp.grantedPermissions 1821 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1822 continue; 1823 } 1824 1825 if (requiredVerifier != null) { 1826 throw new RuntimeException("There can be only one required verifier"); 1827 } 1828 1829 requiredVerifier = packageName; 1830 } 1831 1832 return requiredVerifier; 1833 } 1834 1835 @Override 1836 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1837 throws RemoteException { 1838 try { 1839 return super.onTransact(code, data, reply, flags); 1840 } catch (RuntimeException e) { 1841 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1842 Slog.wtf(TAG, "Package Manager Crash", e); 1843 } 1844 throw e; 1845 } 1846 } 1847 1848 void cleanupInstallFailedPackage(PackageSetting ps) { 1849 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1850 removeDataDirsLI(ps.name); 1851 1852 // TODO: try cleaning up codePath directory contents first, since it 1853 // might be a cluster 1854 1855 if (ps.codePath != null) { 1856 if (!ps.codePath.delete()) { 1857 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1858 } 1859 } 1860 if (ps.resourcePath != null) { 1861 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1862 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1863 } 1864 } 1865 mSettings.removePackageLPw(ps.name); 1866 } 1867 1868 static int[] appendInts(int[] cur, int[] add) { 1869 if (add == null) return cur; 1870 if (cur == null) return add; 1871 final int N = add.length; 1872 for (int i=0; i<N; i++) { 1873 cur = appendInt(cur, add[i]); 1874 } 1875 return cur; 1876 } 1877 1878 static int[] removeInts(int[] cur, int[] rem) { 1879 if (rem == null) return cur; 1880 if (cur == null) return cur; 1881 final int N = rem.length; 1882 for (int i=0; i<N; i++) { 1883 cur = removeInt(cur, rem[i]); 1884 } 1885 return cur; 1886 } 1887 1888 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1889 if (!sUserManager.exists(userId)) return null; 1890 final PackageSetting ps = (PackageSetting) p.mExtras; 1891 if (ps == null) { 1892 return null; 1893 } 1894 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1895 final PackageUserState state = ps.readUserState(userId); 1896 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1897 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1898 state, userId); 1899 } 1900 1901 @Override 1902 public boolean isPackageAvailable(String packageName, int userId) { 1903 if (!sUserManager.exists(userId)) return false; 1904 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1905 synchronized (mPackages) { 1906 PackageParser.Package p = mPackages.get(packageName); 1907 if (p != null) { 1908 final PackageSetting ps = (PackageSetting) p.mExtras; 1909 if (ps != null) { 1910 final PackageUserState state = ps.readUserState(userId); 1911 if (state != null) { 1912 return PackageParser.isAvailable(state); 1913 } 1914 } 1915 } 1916 } 1917 return false; 1918 } 1919 1920 @Override 1921 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1922 if (!sUserManager.exists(userId)) return null; 1923 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1924 // reader 1925 synchronized (mPackages) { 1926 PackageParser.Package p = mPackages.get(packageName); 1927 if (DEBUG_PACKAGE_INFO) 1928 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1929 if (p != null) { 1930 return generatePackageInfo(p, flags, userId); 1931 } 1932 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1933 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1934 } 1935 } 1936 return null; 1937 } 1938 1939 @Override 1940 public String[] currentToCanonicalPackageNames(String[] names) { 1941 String[] out = new String[names.length]; 1942 // reader 1943 synchronized (mPackages) { 1944 for (int i=names.length-1; i>=0; i--) { 1945 PackageSetting ps = mSettings.mPackages.get(names[i]); 1946 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1947 } 1948 } 1949 return out; 1950 } 1951 1952 @Override 1953 public String[] canonicalToCurrentPackageNames(String[] names) { 1954 String[] out = new String[names.length]; 1955 // reader 1956 synchronized (mPackages) { 1957 for (int i=names.length-1; i>=0; i--) { 1958 String cur = mSettings.mRenamedPackages.get(names[i]); 1959 out[i] = cur != null ? cur : names[i]; 1960 } 1961 } 1962 return out; 1963 } 1964 1965 @Override 1966 public int getPackageUid(String packageName, int userId) { 1967 if (!sUserManager.exists(userId)) return -1; 1968 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1969 // reader 1970 synchronized (mPackages) { 1971 PackageParser.Package p = mPackages.get(packageName); 1972 if(p != null) { 1973 return UserHandle.getUid(userId, p.applicationInfo.uid); 1974 } 1975 PackageSetting ps = mSettings.mPackages.get(packageName); 1976 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1977 return -1; 1978 } 1979 p = ps.pkg; 1980 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1981 } 1982 } 1983 1984 @Override 1985 public int[] getPackageGids(String packageName) { 1986 // reader 1987 synchronized (mPackages) { 1988 PackageParser.Package p = mPackages.get(packageName); 1989 if (DEBUG_PACKAGE_INFO) 1990 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1991 if (p != null) { 1992 final PackageSetting ps = (PackageSetting)p.mExtras; 1993 return ps.getGids(); 1994 } 1995 } 1996 // stupid thing to indicate an error. 1997 return new int[0]; 1998 } 1999 2000 static final PermissionInfo generatePermissionInfo( 2001 BasePermission bp, int flags) { 2002 if (bp.perm != null) { 2003 return PackageParser.generatePermissionInfo(bp.perm, flags); 2004 } 2005 PermissionInfo pi = new PermissionInfo(); 2006 pi.name = bp.name; 2007 pi.packageName = bp.sourcePackage; 2008 pi.nonLocalizedLabel = bp.name; 2009 pi.protectionLevel = bp.protectionLevel; 2010 return pi; 2011 } 2012 2013 @Override 2014 public PermissionInfo getPermissionInfo(String name, int flags) { 2015 // reader 2016 synchronized (mPackages) { 2017 final BasePermission p = mSettings.mPermissions.get(name); 2018 if (p != null) { 2019 return generatePermissionInfo(p, flags); 2020 } 2021 return null; 2022 } 2023 } 2024 2025 @Override 2026 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2027 // reader 2028 synchronized (mPackages) { 2029 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2030 for (BasePermission p : mSettings.mPermissions.values()) { 2031 if (group == null) { 2032 if (p.perm == null || p.perm.info.group == null) { 2033 out.add(generatePermissionInfo(p, flags)); 2034 } 2035 } else { 2036 if (p.perm != null && group.equals(p.perm.info.group)) { 2037 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2038 } 2039 } 2040 } 2041 2042 if (out.size() > 0) { 2043 return out; 2044 } 2045 return mPermissionGroups.containsKey(group) ? out : null; 2046 } 2047 } 2048 2049 @Override 2050 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2051 // reader 2052 synchronized (mPackages) { 2053 return PackageParser.generatePermissionGroupInfo( 2054 mPermissionGroups.get(name), flags); 2055 } 2056 } 2057 2058 @Override 2059 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2060 // reader 2061 synchronized (mPackages) { 2062 final int N = mPermissionGroups.size(); 2063 ArrayList<PermissionGroupInfo> out 2064 = new ArrayList<PermissionGroupInfo>(N); 2065 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2066 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2067 } 2068 return out; 2069 } 2070 } 2071 2072 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2073 int userId) { 2074 if (!sUserManager.exists(userId)) return null; 2075 PackageSetting ps = mSettings.mPackages.get(packageName); 2076 if (ps != null) { 2077 if (ps.pkg == null) { 2078 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2079 flags, userId); 2080 if (pInfo != null) { 2081 return pInfo.applicationInfo; 2082 } 2083 return null; 2084 } 2085 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2086 ps.readUserState(userId), userId); 2087 } 2088 return null; 2089 } 2090 2091 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2092 int userId) { 2093 if (!sUserManager.exists(userId)) return null; 2094 PackageSetting ps = mSettings.mPackages.get(packageName); 2095 if (ps != null) { 2096 PackageParser.Package pkg = ps.pkg; 2097 if (pkg == null) { 2098 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2099 return null; 2100 } 2101 // Only data remains, so we aren't worried about code paths 2102 pkg = new PackageParser.Package(packageName); 2103 pkg.applicationInfo.packageName = packageName; 2104 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2105 pkg.applicationInfo.dataDir = 2106 getDataPathForPackage(packageName, 0).getPath(); 2107 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2108 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2109 } 2110 return generatePackageInfo(pkg, flags, userId); 2111 } 2112 return null; 2113 } 2114 2115 @Override 2116 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2117 if (!sUserManager.exists(userId)) return null; 2118 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2119 // writer 2120 synchronized (mPackages) { 2121 PackageParser.Package p = mPackages.get(packageName); 2122 if (DEBUG_PACKAGE_INFO) Log.v( 2123 TAG, "getApplicationInfo " + packageName 2124 + ": " + p); 2125 if (p != null) { 2126 PackageSetting ps = mSettings.mPackages.get(packageName); 2127 if (ps == null) return null; 2128 // Note: isEnabledLP() does not apply here - always return info 2129 return PackageParser.generateApplicationInfo( 2130 p, flags, ps.readUserState(userId), userId); 2131 } 2132 if ("android".equals(packageName)||"system".equals(packageName)) { 2133 return mAndroidApplication; 2134 } 2135 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2136 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2137 } 2138 } 2139 return null; 2140 } 2141 2142 2143 @Override 2144 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2145 mContext.enforceCallingOrSelfPermission( 2146 android.Manifest.permission.CLEAR_APP_CACHE, null); 2147 // Queue up an async operation since clearing cache may take a little while. 2148 mHandler.post(new Runnable() { 2149 public void run() { 2150 mHandler.removeCallbacks(this); 2151 int retCode = -1; 2152 synchronized (mInstallLock) { 2153 retCode = mInstaller.freeCache(freeStorageSize); 2154 if (retCode < 0) { 2155 Slog.w(TAG, "Couldn't clear application caches"); 2156 } 2157 } 2158 if (observer != null) { 2159 try { 2160 observer.onRemoveCompleted(null, (retCode >= 0)); 2161 } catch (RemoteException e) { 2162 Slog.w(TAG, "RemoveException when invoking call back"); 2163 } 2164 } 2165 } 2166 }); 2167 } 2168 2169 @Override 2170 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2171 mContext.enforceCallingOrSelfPermission( 2172 android.Manifest.permission.CLEAR_APP_CACHE, null); 2173 // Queue up an async operation since clearing cache may take a little while. 2174 mHandler.post(new Runnable() { 2175 public void run() { 2176 mHandler.removeCallbacks(this); 2177 int retCode = -1; 2178 synchronized (mInstallLock) { 2179 retCode = mInstaller.freeCache(freeStorageSize); 2180 if (retCode < 0) { 2181 Slog.w(TAG, "Couldn't clear application caches"); 2182 } 2183 } 2184 if(pi != null) { 2185 try { 2186 // Callback via pending intent 2187 int code = (retCode >= 0) ? 1 : 0; 2188 pi.sendIntent(null, code, null, 2189 null, null); 2190 } catch (SendIntentException e1) { 2191 Slog.i(TAG, "Failed to send pending intent"); 2192 } 2193 } 2194 } 2195 }); 2196 } 2197 2198 void freeStorage(long freeStorageSize) throws IOException { 2199 synchronized (mInstallLock) { 2200 if (mInstaller.freeCache(freeStorageSize) < 0) { 2201 throw new IOException("Failed to free enough space"); 2202 } 2203 } 2204 } 2205 2206 @Override 2207 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2208 if (!sUserManager.exists(userId)) return null; 2209 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2210 synchronized (mPackages) { 2211 PackageParser.Activity a = mActivities.mActivities.get(component); 2212 2213 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2214 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2215 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2216 if (ps == null) return null; 2217 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2218 userId); 2219 } 2220 if (mResolveComponentName.equals(component)) { 2221 return mResolveActivity; 2222 } 2223 } 2224 return null; 2225 } 2226 2227 @Override 2228 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2229 String resolvedType) { 2230 synchronized (mPackages) { 2231 PackageParser.Activity a = mActivities.mActivities.get(component); 2232 if (a == null) { 2233 return false; 2234 } 2235 for (int i=0; i<a.intents.size(); i++) { 2236 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2237 intent.getData(), intent.getCategories(), TAG) >= 0) { 2238 return true; 2239 } 2240 } 2241 return false; 2242 } 2243 } 2244 2245 @Override 2246 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2247 if (!sUserManager.exists(userId)) return null; 2248 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2249 synchronized (mPackages) { 2250 PackageParser.Activity a = mReceivers.mActivities.get(component); 2251 if (DEBUG_PACKAGE_INFO) Log.v( 2252 TAG, "getReceiverInfo " + component + ": " + a); 2253 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2254 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2255 if (ps == null) return null; 2256 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2257 userId); 2258 } 2259 } 2260 return null; 2261 } 2262 2263 @Override 2264 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2265 if (!sUserManager.exists(userId)) return null; 2266 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2267 synchronized (mPackages) { 2268 PackageParser.Service s = mServices.mServices.get(component); 2269 if (DEBUG_PACKAGE_INFO) Log.v( 2270 TAG, "getServiceInfo " + component + ": " + s); 2271 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2272 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2273 if (ps == null) return null; 2274 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2275 userId); 2276 } 2277 } 2278 return null; 2279 } 2280 2281 @Override 2282 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2283 if (!sUserManager.exists(userId)) return null; 2284 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2285 synchronized (mPackages) { 2286 PackageParser.Provider p = mProviders.mProviders.get(component); 2287 if (DEBUG_PACKAGE_INFO) Log.v( 2288 TAG, "getProviderInfo " + component + ": " + p); 2289 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2290 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2291 if (ps == null) return null; 2292 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2293 userId); 2294 } 2295 } 2296 return null; 2297 } 2298 2299 @Override 2300 public String[] getSystemSharedLibraryNames() { 2301 Set<String> libSet; 2302 synchronized (mPackages) { 2303 libSet = mSharedLibraries.keySet(); 2304 int size = libSet.size(); 2305 if (size > 0) { 2306 String[] libs = new String[size]; 2307 libSet.toArray(libs); 2308 return libs; 2309 } 2310 } 2311 return null; 2312 } 2313 2314 @Override 2315 public FeatureInfo[] getSystemAvailableFeatures() { 2316 Collection<FeatureInfo> featSet; 2317 synchronized (mPackages) { 2318 featSet = mAvailableFeatures.values(); 2319 int size = featSet.size(); 2320 if (size > 0) { 2321 FeatureInfo[] features = new FeatureInfo[size+1]; 2322 featSet.toArray(features); 2323 FeatureInfo fi = new FeatureInfo(); 2324 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2325 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2326 features[size] = fi; 2327 return features; 2328 } 2329 } 2330 return null; 2331 } 2332 2333 @Override 2334 public boolean hasSystemFeature(String name) { 2335 synchronized (mPackages) { 2336 return mAvailableFeatures.containsKey(name); 2337 } 2338 } 2339 2340 private void checkValidCaller(int uid, int userId) { 2341 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2342 return; 2343 2344 throw new SecurityException("Caller uid=" + uid 2345 + " is not privileged to communicate with user=" + userId); 2346 } 2347 2348 @Override 2349 public int checkPermission(String permName, String pkgName) { 2350 synchronized (mPackages) { 2351 PackageParser.Package p = mPackages.get(pkgName); 2352 if (p != null && p.mExtras != null) { 2353 PackageSetting ps = (PackageSetting)p.mExtras; 2354 if (ps.sharedUser != null) { 2355 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2356 return PackageManager.PERMISSION_GRANTED; 2357 } 2358 } else if (ps.grantedPermissions.contains(permName)) { 2359 return PackageManager.PERMISSION_GRANTED; 2360 } 2361 } 2362 } 2363 return PackageManager.PERMISSION_DENIED; 2364 } 2365 2366 @Override 2367 public int checkUidPermission(String permName, int uid) { 2368 synchronized (mPackages) { 2369 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2370 if (obj != null) { 2371 GrantedPermissions gp = (GrantedPermissions)obj; 2372 if (gp.grantedPermissions.contains(permName)) { 2373 return PackageManager.PERMISSION_GRANTED; 2374 } 2375 } else { 2376 HashSet<String> perms = mSystemPermissions.get(uid); 2377 if (perms != null && perms.contains(permName)) { 2378 return PackageManager.PERMISSION_GRANTED; 2379 } 2380 } 2381 } 2382 return PackageManager.PERMISSION_DENIED; 2383 } 2384 2385 /** 2386 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2387 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2388 * @param message the message to log on security exception 2389 */ 2390 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2391 String message) { 2392 if (userId < 0) { 2393 throw new IllegalArgumentException("Invalid userId " + userId); 2394 } 2395 if (userId == UserHandle.getUserId(callingUid)) return; 2396 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2397 if (requireFullPermission) { 2398 mContext.enforceCallingOrSelfPermission( 2399 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2400 } else { 2401 try { 2402 mContext.enforceCallingOrSelfPermission( 2403 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2404 } catch (SecurityException se) { 2405 mContext.enforceCallingOrSelfPermission( 2406 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2407 } 2408 } 2409 } 2410 } 2411 2412 private BasePermission findPermissionTreeLP(String permName) { 2413 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2414 if (permName.startsWith(bp.name) && 2415 permName.length() > bp.name.length() && 2416 permName.charAt(bp.name.length()) == '.') { 2417 return bp; 2418 } 2419 } 2420 return null; 2421 } 2422 2423 private BasePermission checkPermissionTreeLP(String permName) { 2424 if (permName != null) { 2425 BasePermission bp = findPermissionTreeLP(permName); 2426 if (bp != null) { 2427 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2428 return bp; 2429 } 2430 throw new SecurityException("Calling uid " 2431 + Binder.getCallingUid() 2432 + " is not allowed to add to permission tree " 2433 + bp.name + " owned by uid " + bp.uid); 2434 } 2435 } 2436 throw new SecurityException("No permission tree found for " + permName); 2437 } 2438 2439 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2440 if (s1 == null) { 2441 return s2 == null; 2442 } 2443 if (s2 == null) { 2444 return false; 2445 } 2446 if (s1.getClass() != s2.getClass()) { 2447 return false; 2448 } 2449 return s1.equals(s2); 2450 } 2451 2452 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2453 if (pi1.icon != pi2.icon) return false; 2454 if (pi1.logo != pi2.logo) return false; 2455 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2456 if (!compareStrings(pi1.name, pi2.name)) return false; 2457 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2458 // We'll take care of setting this one. 2459 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2460 // These are not currently stored in settings. 2461 //if (!compareStrings(pi1.group, pi2.group)) return false; 2462 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2463 //if (pi1.labelRes != pi2.labelRes) return false; 2464 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2465 return true; 2466 } 2467 2468 int permissionInfoFootprint(PermissionInfo info) { 2469 int size = info.name.length(); 2470 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2471 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2472 return size; 2473 } 2474 2475 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2476 int size = 0; 2477 for (BasePermission perm : mSettings.mPermissions.values()) { 2478 if (perm.uid == tree.uid) { 2479 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2480 } 2481 } 2482 return size; 2483 } 2484 2485 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2486 // We calculate the max size of permissions defined by this uid and throw 2487 // if that plus the size of 'info' would exceed our stated maximum. 2488 if (tree.uid != Process.SYSTEM_UID) { 2489 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2490 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2491 throw new SecurityException("Permission tree size cap exceeded"); 2492 } 2493 } 2494 } 2495 2496 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2497 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2498 throw new SecurityException("Label must be specified in permission"); 2499 } 2500 BasePermission tree = checkPermissionTreeLP(info.name); 2501 BasePermission bp = mSettings.mPermissions.get(info.name); 2502 boolean added = bp == null; 2503 boolean changed = true; 2504 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2505 if (added) { 2506 enforcePermissionCapLocked(info, tree); 2507 bp = new BasePermission(info.name, tree.sourcePackage, 2508 BasePermission.TYPE_DYNAMIC); 2509 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2510 throw new SecurityException( 2511 "Not allowed to modify non-dynamic permission " 2512 + info.name); 2513 } else { 2514 if (bp.protectionLevel == fixedLevel 2515 && bp.perm.owner.equals(tree.perm.owner) 2516 && bp.uid == tree.uid 2517 && comparePermissionInfos(bp.perm.info, info)) { 2518 changed = false; 2519 } 2520 } 2521 bp.protectionLevel = fixedLevel; 2522 info = new PermissionInfo(info); 2523 info.protectionLevel = fixedLevel; 2524 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2525 bp.perm.info.packageName = tree.perm.info.packageName; 2526 bp.uid = tree.uid; 2527 if (added) { 2528 mSettings.mPermissions.put(info.name, bp); 2529 } 2530 if (changed) { 2531 if (!async) { 2532 mSettings.writeLPr(); 2533 } else { 2534 scheduleWriteSettingsLocked(); 2535 } 2536 } 2537 return added; 2538 } 2539 2540 @Override 2541 public boolean addPermission(PermissionInfo info) { 2542 synchronized (mPackages) { 2543 return addPermissionLocked(info, false); 2544 } 2545 } 2546 2547 @Override 2548 public boolean addPermissionAsync(PermissionInfo info) { 2549 synchronized (mPackages) { 2550 return addPermissionLocked(info, true); 2551 } 2552 } 2553 2554 @Override 2555 public void removePermission(String name) { 2556 synchronized (mPackages) { 2557 checkPermissionTreeLP(name); 2558 BasePermission bp = mSettings.mPermissions.get(name); 2559 if (bp != null) { 2560 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2561 throw new SecurityException( 2562 "Not allowed to modify non-dynamic permission " 2563 + name); 2564 } 2565 mSettings.mPermissions.remove(name); 2566 mSettings.writeLPr(); 2567 } 2568 } 2569 } 2570 2571 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2572 int index = pkg.requestedPermissions.indexOf(bp.name); 2573 if (index == -1) { 2574 throw new SecurityException("Package " + pkg.packageName 2575 + " has not requested permission " + bp.name); 2576 } 2577 boolean isNormal = 2578 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2579 == PermissionInfo.PROTECTION_NORMAL); 2580 boolean isDangerous = 2581 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2582 == PermissionInfo.PROTECTION_DANGEROUS); 2583 boolean isDevelopment = 2584 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2585 2586 if (!isNormal && !isDangerous && !isDevelopment) { 2587 throw new SecurityException("Permission " + bp.name 2588 + " is not a changeable permission type"); 2589 } 2590 2591 if (isNormal || isDangerous) { 2592 if (pkg.requestedPermissionsRequired.get(index)) { 2593 throw new SecurityException("Can't change " + bp.name 2594 + ". It is required by the application"); 2595 } 2596 } 2597 } 2598 2599 @Override 2600 public void grantPermission(String packageName, String permissionName) { 2601 mContext.enforceCallingOrSelfPermission( 2602 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2603 synchronized (mPackages) { 2604 final PackageParser.Package pkg = mPackages.get(packageName); 2605 if (pkg == null) { 2606 throw new IllegalArgumentException("Unknown package: " + packageName); 2607 } 2608 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2609 if (bp == null) { 2610 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2611 } 2612 2613 checkGrantRevokePermissions(pkg, bp); 2614 2615 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2616 if (ps == null) { 2617 return; 2618 } 2619 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2620 if (gp.grantedPermissions.add(permissionName)) { 2621 if (ps.haveGids) { 2622 gp.gids = appendInts(gp.gids, bp.gids); 2623 } 2624 mSettings.writeLPr(); 2625 } 2626 } 2627 } 2628 2629 @Override 2630 public void revokePermission(String packageName, String permissionName) { 2631 int changedAppId = -1; 2632 2633 synchronized (mPackages) { 2634 final PackageParser.Package pkg = mPackages.get(packageName); 2635 if (pkg == null) { 2636 throw new IllegalArgumentException("Unknown package: " + packageName); 2637 } 2638 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2639 mContext.enforceCallingOrSelfPermission( 2640 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2641 } 2642 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2643 if (bp == null) { 2644 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2645 } 2646 2647 checkGrantRevokePermissions(pkg, bp); 2648 2649 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2650 if (ps == null) { 2651 return; 2652 } 2653 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2654 if (gp.grantedPermissions.remove(permissionName)) { 2655 gp.grantedPermissions.remove(permissionName); 2656 if (ps.haveGids) { 2657 gp.gids = removeInts(gp.gids, bp.gids); 2658 } 2659 mSettings.writeLPr(); 2660 changedAppId = ps.appId; 2661 } 2662 } 2663 2664 if (changedAppId >= 0) { 2665 // We changed the perm on someone, kill its processes. 2666 IActivityManager am = ActivityManagerNative.getDefault(); 2667 if (am != null) { 2668 final int callingUserId = UserHandle.getCallingUserId(); 2669 final long ident = Binder.clearCallingIdentity(); 2670 try { 2671 //XXX we should only revoke for the calling user's app permissions, 2672 // but for now we impact all users. 2673 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2674 // "revoke " + permissionName); 2675 int[] users = sUserManager.getUserIds(); 2676 for (int user : users) { 2677 am.killUid(UserHandle.getUid(user, changedAppId), 2678 "revoke " + permissionName); 2679 } 2680 } catch (RemoteException e) { 2681 } finally { 2682 Binder.restoreCallingIdentity(ident); 2683 } 2684 } 2685 } 2686 } 2687 2688 @Override 2689 public boolean isProtectedBroadcast(String actionName) { 2690 synchronized (mPackages) { 2691 return mProtectedBroadcasts.contains(actionName); 2692 } 2693 } 2694 2695 @Override 2696 public int checkSignatures(String pkg1, String pkg2) { 2697 synchronized (mPackages) { 2698 final PackageParser.Package p1 = mPackages.get(pkg1); 2699 final PackageParser.Package p2 = mPackages.get(pkg2); 2700 if (p1 == null || p1.mExtras == null 2701 || p2 == null || p2.mExtras == null) { 2702 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2703 } 2704 return compareSignatures(p1.mSignatures, p2.mSignatures); 2705 } 2706 } 2707 2708 @Override 2709 public int checkUidSignatures(int uid1, int uid2) { 2710 // Map to base uids. 2711 uid1 = UserHandle.getAppId(uid1); 2712 uid2 = UserHandle.getAppId(uid2); 2713 // reader 2714 synchronized (mPackages) { 2715 Signature[] s1; 2716 Signature[] s2; 2717 Object obj = mSettings.getUserIdLPr(uid1); 2718 if (obj != null) { 2719 if (obj instanceof SharedUserSetting) { 2720 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2721 } else if (obj instanceof PackageSetting) { 2722 s1 = ((PackageSetting)obj).signatures.mSignatures; 2723 } else { 2724 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2725 } 2726 } else { 2727 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2728 } 2729 obj = mSettings.getUserIdLPr(uid2); 2730 if (obj != null) { 2731 if (obj instanceof SharedUserSetting) { 2732 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2733 } else if (obj instanceof PackageSetting) { 2734 s2 = ((PackageSetting)obj).signatures.mSignatures; 2735 } else { 2736 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2737 } 2738 } else { 2739 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2740 } 2741 return compareSignatures(s1, s2); 2742 } 2743 } 2744 2745 /** 2746 * Compares two sets of signatures. Returns: 2747 * <br /> 2748 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2749 * <br /> 2750 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2751 * <br /> 2752 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2753 * <br /> 2754 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2755 * <br /> 2756 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2757 */ 2758 static int compareSignatures(Signature[] s1, Signature[] s2) { 2759 if (s1 == null) { 2760 return s2 == null 2761 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2762 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2763 } 2764 2765 if (s2 == null) { 2766 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2767 } 2768 2769 if (s1.length != s2.length) { 2770 return PackageManager.SIGNATURE_NO_MATCH; 2771 } 2772 2773 // Since both signature sets are of size 1, we can compare without HashSets. 2774 if (s1.length == 1) { 2775 return s1[0].equals(s2[0]) ? 2776 PackageManager.SIGNATURE_MATCH : 2777 PackageManager.SIGNATURE_NO_MATCH; 2778 } 2779 2780 HashSet<Signature> set1 = new HashSet<Signature>(); 2781 for (Signature sig : s1) { 2782 set1.add(sig); 2783 } 2784 HashSet<Signature> set2 = new HashSet<Signature>(); 2785 for (Signature sig : s2) { 2786 set2.add(sig); 2787 } 2788 // Make sure s2 contains all signatures in s1. 2789 if (set1.equals(set2)) { 2790 return PackageManager.SIGNATURE_MATCH; 2791 } 2792 return PackageManager.SIGNATURE_NO_MATCH; 2793 } 2794 2795 /** 2796 * If the database version for this type of package (internal storage or 2797 * external storage) is less than the version where package signatures 2798 * were updated, return true. 2799 */ 2800 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2801 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2802 DatabaseVersion.SIGNATURE_END_ENTITY)) 2803 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2804 DatabaseVersion.SIGNATURE_END_ENTITY)); 2805 } 2806 2807 /** 2808 * Used for backward compatibility to make sure any packages with 2809 * certificate chains get upgraded to the new style. {@code existingSigs} 2810 * will be in the old format (since they were stored on disk from before the 2811 * system upgrade) and {@code scannedSigs} will be in the newer format. 2812 */ 2813 private int compareSignaturesCompat(PackageSignatures existingSigs, 2814 PackageParser.Package scannedPkg) { 2815 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2816 return PackageManager.SIGNATURE_NO_MATCH; 2817 } 2818 2819 HashSet<Signature> existingSet = new HashSet<Signature>(); 2820 for (Signature sig : existingSigs.mSignatures) { 2821 existingSet.add(sig); 2822 } 2823 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2824 for (Signature sig : scannedPkg.mSignatures) { 2825 try { 2826 Signature[] chainSignatures = sig.getChainSignatures(); 2827 for (Signature chainSig : chainSignatures) { 2828 scannedCompatSet.add(chainSig); 2829 } 2830 } catch (CertificateEncodingException e) { 2831 scannedCompatSet.add(sig); 2832 } 2833 } 2834 /* 2835 * Make sure the expanded scanned set contains all signatures in the 2836 * existing one. 2837 */ 2838 if (scannedCompatSet.equals(existingSet)) { 2839 // Migrate the old signatures to the new scheme. 2840 existingSigs.assignSignatures(scannedPkg.mSignatures); 2841 // The new KeySets will be re-added later in the scanning process. 2842 synchronized (mPackages) { 2843 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2844 } 2845 return PackageManager.SIGNATURE_MATCH; 2846 } 2847 return PackageManager.SIGNATURE_NO_MATCH; 2848 } 2849 2850 @Override 2851 public String[] getPackagesForUid(int uid) { 2852 uid = UserHandle.getAppId(uid); 2853 // reader 2854 synchronized (mPackages) { 2855 Object obj = mSettings.getUserIdLPr(uid); 2856 if (obj instanceof SharedUserSetting) { 2857 final SharedUserSetting sus = (SharedUserSetting) obj; 2858 final int N = sus.packages.size(); 2859 final String[] res = new String[N]; 2860 final Iterator<PackageSetting> it = sus.packages.iterator(); 2861 int i = 0; 2862 while (it.hasNext()) { 2863 res[i++] = it.next().name; 2864 } 2865 return res; 2866 } else if (obj instanceof PackageSetting) { 2867 final PackageSetting ps = (PackageSetting) obj; 2868 return new String[] { ps.name }; 2869 } 2870 } 2871 return null; 2872 } 2873 2874 @Override 2875 public String getNameForUid(int uid) { 2876 // reader 2877 synchronized (mPackages) { 2878 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2879 if (obj instanceof SharedUserSetting) { 2880 final SharedUserSetting sus = (SharedUserSetting) obj; 2881 return sus.name + ":" + sus.userId; 2882 } else if (obj instanceof PackageSetting) { 2883 final PackageSetting ps = (PackageSetting) obj; 2884 return ps.name; 2885 } 2886 } 2887 return null; 2888 } 2889 2890 @Override 2891 public int getUidForSharedUser(String sharedUserName) { 2892 if(sharedUserName == null) { 2893 return -1; 2894 } 2895 // reader 2896 synchronized (mPackages) { 2897 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2898 if (suid == null) { 2899 return -1; 2900 } 2901 return suid.userId; 2902 } 2903 } 2904 2905 @Override 2906 public int getFlagsForUid(int uid) { 2907 synchronized (mPackages) { 2908 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2909 if (obj instanceof SharedUserSetting) { 2910 final SharedUserSetting sus = (SharedUserSetting) obj; 2911 return sus.pkgFlags; 2912 } else if (obj instanceof PackageSetting) { 2913 final PackageSetting ps = (PackageSetting) obj; 2914 return ps.pkgFlags; 2915 } 2916 } 2917 return 0; 2918 } 2919 2920 @Override 2921 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2922 int flags, int userId) { 2923 if (!sUserManager.exists(userId)) return null; 2924 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2925 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2926 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2927 } 2928 2929 @Override 2930 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2931 IntentFilter filter, int match, ComponentName activity) { 2932 final int userId = UserHandle.getCallingUserId(); 2933 if (DEBUG_PREFERRED) { 2934 Log.v(TAG, "setLastChosenActivity intent=" + intent 2935 + " resolvedType=" + resolvedType 2936 + " flags=" + flags 2937 + " filter=" + filter 2938 + " match=" + match 2939 + " activity=" + activity); 2940 filter.dump(new PrintStreamPrinter(System.out), " "); 2941 } 2942 intent.setComponent(null); 2943 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2944 // Find any earlier preferred or last chosen entries and nuke them 2945 findPreferredActivity(intent, resolvedType, 2946 flags, query, 0, false, true, false, userId); 2947 // Add the new activity as the last chosen for this filter 2948 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2949 } 2950 2951 @Override 2952 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2953 final int userId = UserHandle.getCallingUserId(); 2954 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2955 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2956 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2957 false, false, false, userId); 2958 } 2959 2960 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2961 int flags, List<ResolveInfo> query, int userId) { 2962 if (query != null) { 2963 final int N = query.size(); 2964 if (N == 1) { 2965 return query.get(0); 2966 } else if (N > 1) { 2967 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2968 // If there is more than one activity with the same priority, 2969 // then let the user decide between them. 2970 ResolveInfo r0 = query.get(0); 2971 ResolveInfo r1 = query.get(1); 2972 if (DEBUG_INTENT_MATCHING || debug) { 2973 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2974 + r1.activityInfo.name + "=" + r1.priority); 2975 } 2976 // If the first activity has a higher priority, or a different 2977 // default, then it is always desireable to pick it. 2978 if (r0.priority != r1.priority 2979 || r0.preferredOrder != r1.preferredOrder 2980 || r0.isDefault != r1.isDefault) { 2981 return query.get(0); 2982 } 2983 // If we have saved a preference for a preferred activity for 2984 // this Intent, use that. 2985 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2986 flags, query, r0.priority, true, false, debug, userId); 2987 if (ri != null) { 2988 return ri; 2989 } 2990 if (userId != 0) { 2991 ri = new ResolveInfo(mResolveInfo); 2992 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2993 ri.activityInfo.applicationInfo = new ApplicationInfo( 2994 ri.activityInfo.applicationInfo); 2995 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2996 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2997 return ri; 2998 } 2999 return mResolveInfo; 3000 } 3001 } 3002 return null; 3003 } 3004 3005 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3006 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3007 final int N = query.size(); 3008 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3009 .get(userId); 3010 // Get the list of persistent preferred activities that handle the intent 3011 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3012 List<PersistentPreferredActivity> pprefs = ppir != null 3013 ? ppir.queryIntent(intent, resolvedType, 3014 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3015 : null; 3016 if (pprefs != null && pprefs.size() > 0) { 3017 final int M = pprefs.size(); 3018 for (int i=0; i<M; i++) { 3019 final PersistentPreferredActivity ppa = pprefs.get(i); 3020 if (DEBUG_PREFERRED || debug) { 3021 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3022 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3023 + "\n component=" + ppa.mComponent); 3024 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3025 } 3026 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3027 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3028 if (DEBUG_PREFERRED || debug) { 3029 Slog.v(TAG, "Found persistent preferred activity:"); 3030 if (ai != null) { 3031 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3032 } else { 3033 Slog.v(TAG, " null"); 3034 } 3035 } 3036 if (ai == null) { 3037 // This previously registered persistent preferred activity 3038 // component is no longer known. Ignore it and do NOT remove it. 3039 continue; 3040 } 3041 for (int j=0; j<N; j++) { 3042 final ResolveInfo ri = query.get(j); 3043 if (!ri.activityInfo.applicationInfo.packageName 3044 .equals(ai.applicationInfo.packageName)) { 3045 continue; 3046 } 3047 if (!ri.activityInfo.name.equals(ai.name)) { 3048 continue; 3049 } 3050 // Found a persistent preference that can handle the intent. 3051 if (DEBUG_PREFERRED || debug) { 3052 Slog.v(TAG, "Returning persistent preferred activity: " + 3053 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3054 } 3055 return ri; 3056 } 3057 } 3058 } 3059 return null; 3060 } 3061 3062 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3063 List<ResolveInfo> query, int priority, boolean always, 3064 boolean removeMatches, boolean debug, int userId) { 3065 if (!sUserManager.exists(userId)) return null; 3066 // writer 3067 synchronized (mPackages) { 3068 if (intent.getSelector() != null) { 3069 intent = intent.getSelector(); 3070 } 3071 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3072 3073 // Try to find a matching persistent preferred activity. 3074 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3075 debug, userId); 3076 3077 // If a persistent preferred activity matched, use it. 3078 if (pri != null) { 3079 return pri; 3080 } 3081 3082 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3083 // Get the list of preferred activities that handle the intent 3084 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3085 List<PreferredActivity> prefs = pir != null 3086 ? pir.queryIntent(intent, resolvedType, 3087 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3088 : null; 3089 if (prefs != null && prefs.size() > 0) { 3090 // First figure out how good the original match set is. 3091 // We will only allow preferred activities that came 3092 // from the same match quality. 3093 int match = 0; 3094 3095 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3096 3097 final int N = query.size(); 3098 for (int j=0; j<N; j++) { 3099 final ResolveInfo ri = query.get(j); 3100 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3101 + ": 0x" + Integer.toHexString(match)); 3102 if (ri.match > match) { 3103 match = ri.match; 3104 } 3105 } 3106 3107 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3108 + Integer.toHexString(match)); 3109 3110 match &= IntentFilter.MATCH_CATEGORY_MASK; 3111 final int M = prefs.size(); 3112 for (int i=0; i<M; i++) { 3113 final PreferredActivity pa = prefs.get(i); 3114 if (DEBUG_PREFERRED || debug) { 3115 Slog.v(TAG, "Checking PreferredActivity ds=" 3116 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3117 + "\n component=" + pa.mPref.mComponent); 3118 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3119 } 3120 if (pa.mPref.mMatch != match) { 3121 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3122 + Integer.toHexString(pa.mPref.mMatch)); 3123 continue; 3124 } 3125 // If it's not an "always" type preferred activity and that's what we're 3126 // looking for, skip it. 3127 if (always && !pa.mPref.mAlways) { 3128 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3129 continue; 3130 } 3131 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3132 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3133 if (DEBUG_PREFERRED || debug) { 3134 Slog.v(TAG, "Found preferred activity:"); 3135 if (ai != null) { 3136 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3137 } else { 3138 Slog.v(TAG, " null"); 3139 } 3140 } 3141 if (ai == null) { 3142 // This previously registered preferred activity 3143 // component is no longer known. Most likely an update 3144 // to the app was installed and in the new version this 3145 // component no longer exists. Clean it up by removing 3146 // it from the preferred activities list, and skip it. 3147 Slog.w(TAG, "Removing dangling preferred activity: " 3148 + pa.mPref.mComponent); 3149 pir.removeFilter(pa); 3150 continue; 3151 } 3152 for (int j=0; j<N; j++) { 3153 final ResolveInfo ri = query.get(j); 3154 if (!ri.activityInfo.applicationInfo.packageName 3155 .equals(ai.applicationInfo.packageName)) { 3156 continue; 3157 } 3158 if (!ri.activityInfo.name.equals(ai.name)) { 3159 continue; 3160 } 3161 3162 if (removeMatches) { 3163 pir.removeFilter(pa); 3164 if (DEBUG_PREFERRED) { 3165 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3166 } 3167 break; 3168 } 3169 3170 // Okay we found a previously set preferred or last chosen app. 3171 // If the result set is different from when this 3172 // was created, we need to clear it and re-ask the 3173 // user their preference, if we're looking for an "always" type entry. 3174 if (always && !pa.mPref.sameSet(query, priority)) { 3175 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3176 + intent + " type " + resolvedType); 3177 if (DEBUG_PREFERRED) { 3178 Slog.v(TAG, "Removing preferred activity since set changed " 3179 + pa.mPref.mComponent); 3180 } 3181 pir.removeFilter(pa); 3182 // Re-add the filter as a "last chosen" entry (!always) 3183 PreferredActivity lastChosen = new PreferredActivity( 3184 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3185 pir.addFilter(lastChosen); 3186 mSettings.writePackageRestrictionsLPr(userId); 3187 return null; 3188 } 3189 3190 // Yay! Either the set matched or we're looking for the last chosen 3191 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3192 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3193 mSettings.writePackageRestrictionsLPr(userId); 3194 return ri; 3195 } 3196 } 3197 } 3198 mSettings.writePackageRestrictionsLPr(userId); 3199 } 3200 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3201 return null; 3202 } 3203 3204 /* 3205 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3206 */ 3207 @Override 3208 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3209 int targetUserId) { 3210 mContext.enforceCallingOrSelfPermission( 3211 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3212 List<CrossProfileIntentFilter> matches = 3213 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3214 if (matches != null) { 3215 int size = matches.size(); 3216 for (int i = 0; i < size; i++) { 3217 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3218 } 3219 } 3220 3221 ArrayList<String> packageNames = null; 3222 SparseArray<ArrayList<String>> fromSource = 3223 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3224 if (fromSource != null) { 3225 packageNames = fromSource.get(targetUserId); 3226 } 3227 if (packageNames.contains(intent.getPackage())) { 3228 return true; 3229 } 3230 // We need the package name, so we try to resolve with the loosest flags possible 3231 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3232 intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3233 int count = resolveInfos.size(); 3234 for (int i = 0; i < count; i++) { 3235 ResolveInfo resolveInfo = resolveInfos.get(i); 3236 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3237 return true; 3238 } 3239 } 3240 return false; 3241 } 3242 3243 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3244 String resolvedType, int userId) { 3245 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3246 if (resolver != null) { 3247 return resolver.queryIntent(intent, resolvedType, false, userId); 3248 } 3249 return null; 3250 } 3251 3252 @Override 3253 public List<ResolveInfo> queryIntentActivities(Intent intent, 3254 String resolvedType, int flags, int userId) { 3255 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3256 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3257 ComponentName comp = intent.getComponent(); 3258 if (comp == null) { 3259 if (intent.getSelector() != null) { 3260 intent = intent.getSelector(); 3261 comp = intent.getComponent(); 3262 } 3263 } 3264 3265 if (comp != null) { 3266 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3267 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3268 if (ai != null) { 3269 final ResolveInfo ri = new ResolveInfo(); 3270 ri.activityInfo = ai; 3271 list.add(ri); 3272 } 3273 return list; 3274 } 3275 3276 // reader 3277 synchronized (mPackages) { 3278 final String pkgName = intent.getPackage(); 3279 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3280 if (pkgName == null) { 3281 ResolveInfo resolveInfo = null; 3282 if (queryCrossProfile) { 3283 // Check if the intent needs to be forwarded to another user for this package 3284 ArrayList<ResolveInfo> crossProfileResult = 3285 queryIntentActivitiesCrossProfilePackage( 3286 intent, resolvedType, flags, userId); 3287 if (!crossProfileResult.isEmpty()) { 3288 // Skip the current profile 3289 return crossProfileResult; 3290 } 3291 List<CrossProfileIntentFilter> matchingFilters = 3292 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3293 // Check for results that need to skip the current profile. 3294 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3295 resolvedType, flags, userId); 3296 if (resolveInfo != null) { 3297 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3298 result.add(resolveInfo); 3299 return result; 3300 } 3301 // Check for cross profile results. 3302 resolveInfo = queryCrossProfileIntents( 3303 matchingFilters, intent, resolvedType, flags, userId); 3304 } 3305 // Check for results in the current profile. 3306 List<ResolveInfo> result = mActivities.queryIntent( 3307 intent, resolvedType, flags, userId); 3308 if (resolveInfo != null) { 3309 result.add(resolveInfo); 3310 } 3311 return result; 3312 } 3313 final PackageParser.Package pkg = mPackages.get(pkgName); 3314 if (pkg != null) { 3315 if (queryCrossProfile) { 3316 ArrayList<ResolveInfo> crossProfileResult = 3317 queryIntentActivitiesCrossProfilePackage( 3318 intent, resolvedType, flags, userId, pkg, pkgName); 3319 if (!crossProfileResult.isEmpty()) { 3320 // Skip the current profile 3321 return crossProfileResult; 3322 } 3323 } 3324 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3325 pkg.activities, userId); 3326 } 3327 return new ArrayList<ResolveInfo>(); 3328 } 3329 } 3330 3331 private ResolveInfo querySkipCurrentProfileIntents( 3332 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3333 int flags, int sourceUserId) { 3334 if (matchingFilters != null) { 3335 int size = matchingFilters.size(); 3336 for (int i = 0; i < size; i ++) { 3337 CrossProfileIntentFilter filter = matchingFilters.get(i); 3338 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3339 // Checking if there are activities in the target user that can handle the 3340 // intent. 3341 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3342 flags, sourceUserId); 3343 if (resolveInfo != null) { 3344 return resolveInfo; 3345 } 3346 } 3347 } 3348 } 3349 return null; 3350 } 3351 3352 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3353 Intent intent, String resolvedType, int flags, int userId) { 3354 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3355 SparseArray<ArrayList<String>> sourceForwardingInfo = 3356 mSettings.mCrossProfilePackageInfo.get(userId); 3357 if (sourceForwardingInfo != null) { 3358 int NI = sourceForwardingInfo.size(); 3359 for (int i = 0; i < NI; i++) { 3360 int targetUserId = sourceForwardingInfo.keyAt(i); 3361 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3362 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3363 intent, resolvedType, flags, targetUserId); 3364 int NJ = resolveInfos.size(); 3365 for (int j = 0; j < NJ; j++) { 3366 ResolveInfo resolveInfo = resolveInfos.get(j); 3367 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3368 matchingResolveInfos.add(createForwardingResolveInfo( 3369 resolveInfo.filter, userId, targetUserId)); 3370 } 3371 } 3372 } 3373 } 3374 return matchingResolveInfos; 3375 } 3376 3377 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3378 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3379 String packageName) { 3380 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3381 SparseArray<ArrayList<String>> sourceForwardingInfo = 3382 mSettings.mCrossProfilePackageInfo.get(userId); 3383 if (sourceForwardingInfo != null) { 3384 int NI = sourceForwardingInfo.size(); 3385 for (int i = 0; i < NI; i++) { 3386 int targetUserId = sourceForwardingInfo.keyAt(i); 3387 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3388 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3389 intent, resolvedType, flags, pkg.activities, targetUserId); 3390 int NJ = resolveInfos.size(); 3391 for (int j = 0; j < NJ; j++) { 3392 ResolveInfo resolveInfo = resolveInfos.get(j); 3393 matchingResolveInfos.add(createForwardingResolveInfo( 3394 resolveInfo.filter, userId, targetUserId)); 3395 } 3396 } 3397 } 3398 } 3399 return matchingResolveInfos; 3400 } 3401 3402 // Return matching ResolveInfo if any for skip current profile intent filters. 3403 private ResolveInfo queryCrossProfileIntents( 3404 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3405 int flags, int sourceUserId) { 3406 if (matchingFilters != null) { 3407 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3408 // match the same intent. For performance reasons, it is better not to 3409 // run queryIntent twice for the same userId 3410 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3411 int size = matchingFilters.size(); 3412 for (int i = 0; i < size; i++) { 3413 CrossProfileIntentFilter filter = matchingFilters.get(i); 3414 int targetUserId = filter.getTargetUserId(); 3415 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3416 && !alreadyTriedUserIds.get(targetUserId)) { 3417 // Checking if there are activities in the target user that can handle the 3418 // intent. 3419 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3420 flags, sourceUserId); 3421 if (resolveInfo != null) return resolveInfo; 3422 alreadyTriedUserIds.put(targetUserId, true); 3423 } 3424 } 3425 } 3426 return null; 3427 } 3428 3429 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3430 String resolvedType, int flags, int sourceUserId) { 3431 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3432 resolvedType, flags, filter.getTargetUserId()); 3433 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3434 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3435 } 3436 return null; 3437 } 3438 3439 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3440 int sourceUserId, int targetUserId) { 3441 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3442 String className; 3443 if (targetUserId == UserHandle.USER_OWNER) { 3444 className = FORWARD_INTENT_TO_USER_OWNER; 3445 } else { 3446 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3447 } 3448 ComponentName forwardingActivityComponentName = new ComponentName( 3449 mAndroidApplication.packageName, className); 3450 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3451 sourceUserId); 3452 if (targetUserId == UserHandle.USER_OWNER) { 3453 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3454 forwardingResolveInfo.noResourceId = true; 3455 } 3456 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3457 forwardingResolveInfo.priority = 0; 3458 forwardingResolveInfo.preferredOrder = 0; 3459 forwardingResolveInfo.match = 0; 3460 forwardingResolveInfo.isDefault = true; 3461 forwardingResolveInfo.filter = filter; 3462 forwardingResolveInfo.targetUserId = targetUserId; 3463 return forwardingResolveInfo; 3464 } 3465 3466 @Override 3467 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3468 Intent[] specifics, String[] specificTypes, Intent intent, 3469 String resolvedType, int flags, int userId) { 3470 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3471 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3472 "query intent activity options"); 3473 final String resultsAction = intent.getAction(); 3474 3475 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3476 | PackageManager.GET_RESOLVED_FILTER, userId); 3477 3478 if (DEBUG_INTENT_MATCHING) { 3479 Log.v(TAG, "Query " + intent + ": " + results); 3480 } 3481 3482 int specificsPos = 0; 3483 int N; 3484 3485 // todo: note that the algorithm used here is O(N^2). This 3486 // isn't a problem in our current environment, but if we start running 3487 // into situations where we have more than 5 or 10 matches then this 3488 // should probably be changed to something smarter... 3489 3490 // First we go through and resolve each of the specific items 3491 // that were supplied, taking care of removing any corresponding 3492 // duplicate items in the generic resolve list. 3493 if (specifics != null) { 3494 for (int i=0; i<specifics.length; i++) { 3495 final Intent sintent = specifics[i]; 3496 if (sintent == null) { 3497 continue; 3498 } 3499 3500 if (DEBUG_INTENT_MATCHING) { 3501 Log.v(TAG, "Specific #" + i + ": " + sintent); 3502 } 3503 3504 String action = sintent.getAction(); 3505 if (resultsAction != null && resultsAction.equals(action)) { 3506 // If this action was explicitly requested, then don't 3507 // remove things that have it. 3508 action = null; 3509 } 3510 3511 ResolveInfo ri = null; 3512 ActivityInfo ai = null; 3513 3514 ComponentName comp = sintent.getComponent(); 3515 if (comp == null) { 3516 ri = resolveIntent( 3517 sintent, 3518 specificTypes != null ? specificTypes[i] : null, 3519 flags, userId); 3520 if (ri == null) { 3521 continue; 3522 } 3523 if (ri == mResolveInfo) { 3524 // ACK! Must do something better with this. 3525 } 3526 ai = ri.activityInfo; 3527 comp = new ComponentName(ai.applicationInfo.packageName, 3528 ai.name); 3529 } else { 3530 ai = getActivityInfo(comp, flags, userId); 3531 if (ai == null) { 3532 continue; 3533 } 3534 } 3535 3536 // Look for any generic query activities that are duplicates 3537 // of this specific one, and remove them from the results. 3538 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3539 N = results.size(); 3540 int j; 3541 for (j=specificsPos; j<N; j++) { 3542 ResolveInfo sri = results.get(j); 3543 if ((sri.activityInfo.name.equals(comp.getClassName()) 3544 && sri.activityInfo.applicationInfo.packageName.equals( 3545 comp.getPackageName())) 3546 || (action != null && sri.filter.matchAction(action))) { 3547 results.remove(j); 3548 if (DEBUG_INTENT_MATCHING) Log.v( 3549 TAG, "Removing duplicate item from " + j 3550 + " due to specific " + specificsPos); 3551 if (ri == null) { 3552 ri = sri; 3553 } 3554 j--; 3555 N--; 3556 } 3557 } 3558 3559 // Add this specific item to its proper place. 3560 if (ri == null) { 3561 ri = new ResolveInfo(); 3562 ri.activityInfo = ai; 3563 } 3564 results.add(specificsPos, ri); 3565 ri.specificIndex = i; 3566 specificsPos++; 3567 } 3568 } 3569 3570 // Now we go through the remaining generic results and remove any 3571 // duplicate actions that are found here. 3572 N = results.size(); 3573 for (int i=specificsPos; i<N-1; i++) { 3574 final ResolveInfo rii = results.get(i); 3575 if (rii.filter == null) { 3576 continue; 3577 } 3578 3579 // Iterate over all of the actions of this result's intent 3580 // filter... typically this should be just one. 3581 final Iterator<String> it = rii.filter.actionsIterator(); 3582 if (it == null) { 3583 continue; 3584 } 3585 while (it.hasNext()) { 3586 final String action = it.next(); 3587 if (resultsAction != null && resultsAction.equals(action)) { 3588 // If this action was explicitly requested, then don't 3589 // remove things that have it. 3590 continue; 3591 } 3592 for (int j=i+1; j<N; j++) { 3593 final ResolveInfo rij = results.get(j); 3594 if (rij.filter != null && rij.filter.hasAction(action)) { 3595 results.remove(j); 3596 if (DEBUG_INTENT_MATCHING) Log.v( 3597 TAG, "Removing duplicate item from " + j 3598 + " due to action " + action + " at " + i); 3599 j--; 3600 N--; 3601 } 3602 } 3603 } 3604 3605 // If the caller didn't request filter information, drop it now 3606 // so we don't have to marshall/unmarshall it. 3607 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3608 rii.filter = null; 3609 } 3610 } 3611 3612 // Filter out the caller activity if so requested. 3613 if (caller != null) { 3614 N = results.size(); 3615 for (int i=0; i<N; i++) { 3616 ActivityInfo ainfo = results.get(i).activityInfo; 3617 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3618 && caller.getClassName().equals(ainfo.name)) { 3619 results.remove(i); 3620 break; 3621 } 3622 } 3623 } 3624 3625 // If the caller didn't request filter information, 3626 // drop them now so we don't have to 3627 // marshall/unmarshall it. 3628 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3629 N = results.size(); 3630 for (int i=0; i<N; i++) { 3631 results.get(i).filter = null; 3632 } 3633 } 3634 3635 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3636 return results; 3637 } 3638 3639 @Override 3640 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3641 int userId) { 3642 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3643 ComponentName comp = intent.getComponent(); 3644 if (comp == null) { 3645 if (intent.getSelector() != null) { 3646 intent = intent.getSelector(); 3647 comp = intent.getComponent(); 3648 } 3649 } 3650 if (comp != null) { 3651 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3652 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3653 if (ai != null) { 3654 ResolveInfo ri = new ResolveInfo(); 3655 ri.activityInfo = ai; 3656 list.add(ri); 3657 } 3658 return list; 3659 } 3660 3661 // reader 3662 synchronized (mPackages) { 3663 String pkgName = intent.getPackage(); 3664 if (pkgName == null) { 3665 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3666 } 3667 final PackageParser.Package pkg = mPackages.get(pkgName); 3668 if (pkg != null) { 3669 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3670 userId); 3671 } 3672 return null; 3673 } 3674 } 3675 3676 @Override 3677 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3678 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3679 if (!sUserManager.exists(userId)) return null; 3680 if (query != null) { 3681 if (query.size() >= 1) { 3682 // If there is more than one service with the same priority, 3683 // just arbitrarily pick the first one. 3684 return query.get(0); 3685 } 3686 } 3687 return null; 3688 } 3689 3690 @Override 3691 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3692 int userId) { 3693 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3694 ComponentName comp = intent.getComponent(); 3695 if (comp == null) { 3696 if (intent.getSelector() != null) { 3697 intent = intent.getSelector(); 3698 comp = intent.getComponent(); 3699 } 3700 } 3701 if (comp != null) { 3702 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3703 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3704 if (si != null) { 3705 final ResolveInfo ri = new ResolveInfo(); 3706 ri.serviceInfo = si; 3707 list.add(ri); 3708 } 3709 return list; 3710 } 3711 3712 // reader 3713 synchronized (mPackages) { 3714 String pkgName = intent.getPackage(); 3715 if (pkgName == null) { 3716 return mServices.queryIntent(intent, resolvedType, flags, userId); 3717 } 3718 final PackageParser.Package pkg = mPackages.get(pkgName); 3719 if (pkg != null) { 3720 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3721 userId); 3722 } 3723 return null; 3724 } 3725 } 3726 3727 @Override 3728 public List<ResolveInfo> queryIntentContentProviders( 3729 Intent intent, String resolvedType, int flags, int userId) { 3730 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3731 ComponentName comp = intent.getComponent(); 3732 if (comp == null) { 3733 if (intent.getSelector() != null) { 3734 intent = intent.getSelector(); 3735 comp = intent.getComponent(); 3736 } 3737 } 3738 if (comp != null) { 3739 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3740 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3741 if (pi != null) { 3742 final ResolveInfo ri = new ResolveInfo(); 3743 ri.providerInfo = pi; 3744 list.add(ri); 3745 } 3746 return list; 3747 } 3748 3749 // reader 3750 synchronized (mPackages) { 3751 String pkgName = intent.getPackage(); 3752 if (pkgName == null) { 3753 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3754 } 3755 final PackageParser.Package pkg = mPackages.get(pkgName); 3756 if (pkg != null) { 3757 return mProviders.queryIntentForPackage( 3758 intent, resolvedType, flags, pkg.providers, userId); 3759 } 3760 return null; 3761 } 3762 } 3763 3764 @Override 3765 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3766 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3767 3768 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3769 3770 // writer 3771 synchronized (mPackages) { 3772 ArrayList<PackageInfo> list; 3773 if (listUninstalled) { 3774 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3775 for (PackageSetting ps : mSettings.mPackages.values()) { 3776 PackageInfo pi; 3777 if (ps.pkg != null) { 3778 pi = generatePackageInfo(ps.pkg, flags, userId); 3779 } else { 3780 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3781 } 3782 if (pi != null) { 3783 list.add(pi); 3784 } 3785 } 3786 } else { 3787 list = new ArrayList<PackageInfo>(mPackages.size()); 3788 for (PackageParser.Package p : mPackages.values()) { 3789 PackageInfo pi = generatePackageInfo(p, flags, userId); 3790 if (pi != null) { 3791 list.add(pi); 3792 } 3793 } 3794 } 3795 3796 return new ParceledListSlice<PackageInfo>(list); 3797 } 3798 } 3799 3800 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3801 String[] permissions, boolean[] tmp, int flags, int userId) { 3802 int numMatch = 0; 3803 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3804 for (int i=0; i<permissions.length; i++) { 3805 if (gp.grantedPermissions.contains(permissions[i])) { 3806 tmp[i] = true; 3807 numMatch++; 3808 } else { 3809 tmp[i] = false; 3810 } 3811 } 3812 if (numMatch == 0) { 3813 return; 3814 } 3815 PackageInfo pi; 3816 if (ps.pkg != null) { 3817 pi = generatePackageInfo(ps.pkg, flags, userId); 3818 } else { 3819 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3820 } 3821 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3822 if (numMatch == permissions.length) { 3823 pi.requestedPermissions = permissions; 3824 } else { 3825 pi.requestedPermissions = new String[numMatch]; 3826 numMatch = 0; 3827 for (int i=0; i<permissions.length; i++) { 3828 if (tmp[i]) { 3829 pi.requestedPermissions[numMatch] = permissions[i]; 3830 numMatch++; 3831 } 3832 } 3833 } 3834 } 3835 list.add(pi); 3836 } 3837 3838 @Override 3839 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3840 String[] permissions, int flags, int userId) { 3841 if (!sUserManager.exists(userId)) return null; 3842 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3843 3844 // writer 3845 synchronized (mPackages) { 3846 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3847 boolean[] tmpBools = new boolean[permissions.length]; 3848 if (listUninstalled) { 3849 for (PackageSetting ps : mSettings.mPackages.values()) { 3850 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3851 } 3852 } else { 3853 for (PackageParser.Package pkg : mPackages.values()) { 3854 PackageSetting ps = (PackageSetting)pkg.mExtras; 3855 if (ps != null) { 3856 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3857 userId); 3858 } 3859 } 3860 } 3861 3862 return new ParceledListSlice<PackageInfo>(list); 3863 } 3864 } 3865 3866 @Override 3867 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3868 if (!sUserManager.exists(userId)) return null; 3869 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3870 3871 // writer 3872 synchronized (mPackages) { 3873 ArrayList<ApplicationInfo> list; 3874 if (listUninstalled) { 3875 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3876 for (PackageSetting ps : mSettings.mPackages.values()) { 3877 ApplicationInfo ai; 3878 if (ps.pkg != null) { 3879 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3880 ps.readUserState(userId), userId); 3881 } else { 3882 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3883 } 3884 if (ai != null) { 3885 list.add(ai); 3886 } 3887 } 3888 } else { 3889 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3890 for (PackageParser.Package p : mPackages.values()) { 3891 if (p.mExtras != null) { 3892 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3893 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3894 if (ai != null) { 3895 list.add(ai); 3896 } 3897 } 3898 } 3899 } 3900 3901 return new ParceledListSlice<ApplicationInfo>(list); 3902 } 3903 } 3904 3905 public List<ApplicationInfo> getPersistentApplications(int flags) { 3906 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3907 3908 // reader 3909 synchronized (mPackages) { 3910 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3911 final int userId = UserHandle.getCallingUserId(); 3912 while (i.hasNext()) { 3913 final PackageParser.Package p = i.next(); 3914 if (p.applicationInfo != null 3915 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3916 && (!mSafeMode || isSystemApp(p))) { 3917 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3918 if (ps != null) { 3919 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3920 ps.readUserState(userId), userId); 3921 if (ai != null) { 3922 finalList.add(ai); 3923 } 3924 } 3925 } 3926 } 3927 } 3928 3929 return finalList; 3930 } 3931 3932 @Override 3933 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3934 if (!sUserManager.exists(userId)) return null; 3935 // reader 3936 synchronized (mPackages) { 3937 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3938 PackageSetting ps = provider != null 3939 ? mSettings.mPackages.get(provider.owner.packageName) 3940 : null; 3941 return ps != null 3942 && mSettings.isEnabledLPr(provider.info, flags, userId) 3943 && (!mSafeMode || (provider.info.applicationInfo.flags 3944 &ApplicationInfo.FLAG_SYSTEM) != 0) 3945 ? PackageParser.generateProviderInfo(provider, flags, 3946 ps.readUserState(userId), userId) 3947 : null; 3948 } 3949 } 3950 3951 /** 3952 * @deprecated 3953 */ 3954 @Deprecated 3955 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3956 // reader 3957 synchronized (mPackages) { 3958 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3959 .entrySet().iterator(); 3960 final int userId = UserHandle.getCallingUserId(); 3961 while (i.hasNext()) { 3962 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3963 PackageParser.Provider p = entry.getValue(); 3964 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3965 3966 if (ps != null && p.syncable 3967 && (!mSafeMode || (p.info.applicationInfo.flags 3968 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3969 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3970 ps.readUserState(userId), userId); 3971 if (info != null) { 3972 outNames.add(entry.getKey()); 3973 outInfo.add(info); 3974 } 3975 } 3976 } 3977 } 3978 } 3979 3980 @Override 3981 public List<ProviderInfo> queryContentProviders(String processName, 3982 int uid, int flags) { 3983 ArrayList<ProviderInfo> finalList = null; 3984 // reader 3985 synchronized (mPackages) { 3986 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3987 final int userId = processName != null ? 3988 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3989 while (i.hasNext()) { 3990 final PackageParser.Provider p = i.next(); 3991 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3992 if (ps != null && p.info.authority != null 3993 && (processName == null 3994 || (p.info.processName.equals(processName) 3995 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3996 && mSettings.isEnabledLPr(p.info, flags, userId) 3997 && (!mSafeMode 3998 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3999 if (finalList == null) { 4000 finalList = new ArrayList<ProviderInfo>(3); 4001 } 4002 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4003 ps.readUserState(userId), userId); 4004 if (info != null) { 4005 finalList.add(info); 4006 } 4007 } 4008 } 4009 } 4010 4011 if (finalList != null) { 4012 Collections.sort(finalList, mProviderInitOrderSorter); 4013 } 4014 4015 return finalList; 4016 } 4017 4018 @Override 4019 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4020 int flags) { 4021 // reader 4022 synchronized (mPackages) { 4023 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4024 return PackageParser.generateInstrumentationInfo(i, flags); 4025 } 4026 } 4027 4028 @Override 4029 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4030 int flags) { 4031 ArrayList<InstrumentationInfo> finalList = 4032 new ArrayList<InstrumentationInfo>(); 4033 4034 // reader 4035 synchronized (mPackages) { 4036 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4037 while (i.hasNext()) { 4038 final PackageParser.Instrumentation p = i.next(); 4039 if (targetPackage == null 4040 || targetPackage.equals(p.info.targetPackage)) { 4041 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4042 flags); 4043 if (ii != null) { 4044 finalList.add(ii); 4045 } 4046 } 4047 } 4048 } 4049 4050 return finalList; 4051 } 4052 4053 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4054 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4055 if (overlays == null) { 4056 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4057 return; 4058 } 4059 for (PackageParser.Package opkg : overlays.values()) { 4060 // Not much to do if idmap fails: we already logged the error 4061 // and we certainly don't want to abort installation of pkg simply 4062 // because an overlay didn't fit properly. For these reasons, 4063 // ignore the return value of createIdmapForPackagePairLI. 4064 createIdmapForPackagePairLI(pkg, opkg); 4065 } 4066 } 4067 4068 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4069 PackageParser.Package opkg) { 4070 if (!opkg.mTrustedOverlay) { 4071 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4072 opkg.baseCodePath + ": overlay not trusted"); 4073 return false; 4074 } 4075 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4076 if (overlaySet == null) { 4077 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4078 opkg.baseCodePath + " but target package has no known overlays"); 4079 return false; 4080 } 4081 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4082 // TODO: generate idmap for split APKs 4083 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4084 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4085 + opkg.baseCodePath); 4086 return false; 4087 } 4088 PackageParser.Package[] overlayArray = 4089 overlaySet.values().toArray(new PackageParser.Package[0]); 4090 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4091 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4092 return p1.mOverlayPriority - p2.mOverlayPriority; 4093 } 4094 }; 4095 Arrays.sort(overlayArray, cmp); 4096 4097 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4098 int i = 0; 4099 for (PackageParser.Package p : overlayArray) { 4100 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4101 } 4102 return true; 4103 } 4104 4105 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4106 final File[] files = dir.listFiles(); 4107 if (ArrayUtils.isEmpty(files)) { 4108 Log.d(TAG, "No files in app dir " + dir); 4109 return; 4110 } 4111 4112 if (DEBUG_PACKAGE_SCANNING) { 4113 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4114 + " flags=0x" + Integer.toHexString(flags)); 4115 } 4116 4117 for (File file : files) { 4118 final boolean isPackage = isApkFile(file) || file.isDirectory(); 4119 if (!isPackage) { 4120 // Ignore entries which are not apk's 4121 continue; 4122 } 4123 try { 4124 scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, 4125 null, null); 4126 } catch (PackageManagerException e) { 4127 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4128 4129 // Don't mess around with apps in system partition. 4130 if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4131 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4132 // Delete the apk 4133 Slog.w(TAG, "Cleaning up failed install of " + file); 4134 file.delete(); 4135 } 4136 } 4137 } 4138 } 4139 4140 private static File getSettingsProblemFile() { 4141 File dataDir = Environment.getDataDirectory(); 4142 File systemDir = new File(dataDir, "system"); 4143 File fname = new File(systemDir, "uiderrors.txt"); 4144 return fname; 4145 } 4146 4147 static void reportSettingsProblem(int priority, String msg) { 4148 try { 4149 File fname = getSettingsProblemFile(); 4150 FileOutputStream out = new FileOutputStream(fname, true); 4151 PrintWriter pw = new FastPrintWriter(out); 4152 SimpleDateFormat formatter = new SimpleDateFormat(); 4153 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4154 pw.println(dateString + ": " + msg); 4155 pw.close(); 4156 FileUtils.setPermissions( 4157 fname.toString(), 4158 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4159 -1, -1); 4160 } catch (java.io.IOException e) { 4161 } 4162 Slog.println(priority, TAG, msg); 4163 } 4164 4165 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4166 PackageParser.Package pkg, File srcFile, int parseFlags) 4167 throws PackageManagerException { 4168 if (ps != null 4169 && ps.codePath.equals(srcFile) 4170 && ps.timeStamp == srcFile.lastModified() 4171 && !isCompatSignatureUpdateNeeded(pkg)) { 4172 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4173 if (ps.signatures.mSignatures != null 4174 && ps.signatures.mSignatures.length != 0 4175 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4176 // Optimization: reuse the existing cached certificates 4177 // if the package appears to be unchanged. 4178 pkg.mSignatures = ps.signatures.mSignatures; 4179 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4180 synchronized (mPackages) { 4181 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4182 } 4183 return; 4184 } 4185 4186 Slog.w(TAG, "PackageSetting for " + ps.name 4187 + " is missing signatures. Collecting certs again to recover them."); 4188 } else { 4189 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4190 } 4191 4192 try { 4193 pp.collectCertificates(pkg, parseFlags); 4194 pp.collectManifestDigest(pkg); 4195 } catch (PackageParserException e) { 4196 throw new PackageManagerException(e.error, "Failed to collect certificates for " 4197 + pkg.packageName + ": " + e.getMessage()); 4198 } 4199 } 4200 4201 /* 4202 * Scan a package and return the newly parsed package. 4203 * Returns null in case of errors and the error code is stored in mLastScanError 4204 */ 4205 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode, 4206 long currentTime, UserHandle user, String abiOverride) throws PackageManagerException { 4207 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4208 parseFlags |= mDefParseFlags; 4209 PackageParser pp = new PackageParser(); 4210 pp.setSeparateProcesses(mSeparateProcesses); 4211 pp.setOnlyCoreApps(mOnlyCore); 4212 pp.setDisplayMetrics(mMetrics); 4213 4214 if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) { 4215 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4216 } 4217 4218 final PackageParser.Package pkg; 4219 try { 4220 pkg = pp.parsePackage(scanFile, parseFlags); 4221 } catch (PackageParserException e) { 4222 throw new PackageManagerException(e.error, 4223 "Failed to scan " + scanFile + ": " + e.getMessage()); 4224 } 4225 4226 PackageSetting ps = null; 4227 PackageSetting updatedPkg; 4228 // reader 4229 synchronized (mPackages) { 4230 // Look to see if we already know about this package. 4231 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4232 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4233 // This package has been renamed to its original name. Let's 4234 // use that. 4235 ps = mSettings.peekPackageLPr(oldName); 4236 } 4237 // If there was no original package, see one for the real package name. 4238 if (ps == null) { 4239 ps = mSettings.peekPackageLPr(pkg.packageName); 4240 } 4241 // Check to see if this package could be hiding/updating a system 4242 // package. Must look for it either under the original or real 4243 // package name depending on our state. 4244 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4245 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4246 } 4247 boolean updatedPkgBetter = false; 4248 // First check if this is a system package that may involve an update 4249 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4250 if (ps != null && !ps.codePath.equals(scanFile)) { 4251 // The path has changed from what was last scanned... check the 4252 // version of the new path against what we have stored to determine 4253 // what to do. 4254 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4255 if (pkg.mVersionCode < ps.versionCode) { 4256 // The system package has been updated and the code path does not match 4257 // Ignore entry. Skip it. 4258 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4259 + " ignored: updated version " + ps.versionCode 4260 + " better than this " + pkg.mVersionCode); 4261 if (!updatedPkg.codePath.equals(scanFile)) { 4262 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4263 + ps.name + " changing from " + updatedPkg.codePathString 4264 + " to " + scanFile); 4265 updatedPkg.codePath = scanFile; 4266 updatedPkg.codePathString = scanFile.toString(); 4267 // This is the point at which we know that the system-disk APK 4268 // for this package has moved during a reboot (e.g. due to an OTA), 4269 // so we need to reevaluate it for privilege policy. 4270 if (locationIsPrivileged(scanFile)) { 4271 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4272 } 4273 } 4274 updatedPkg.pkg = pkg; 4275 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4276 } else { 4277 // The current app on the system partition is better than 4278 // what we have updated to on the data partition; switch 4279 // back to the system partition version. 4280 // At this point, its safely assumed that package installation for 4281 // apps in system partition will go through. If not there won't be a working 4282 // version of the app 4283 // writer 4284 synchronized (mPackages) { 4285 // Just remove the loaded entries from package lists. 4286 mPackages.remove(ps.name); 4287 } 4288 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4289 + "reverting from " + ps.codePathString 4290 + ": new version " + pkg.mVersionCode 4291 + " better than installed " + ps.versionCode); 4292 4293 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4294 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4295 getAppDexInstructionSets(ps), isMultiArch(ps)); 4296 synchronized (mInstallLock) { 4297 args.cleanUpResourcesLI(); 4298 } 4299 synchronized (mPackages) { 4300 mSettings.enableSystemPackageLPw(ps.name); 4301 } 4302 updatedPkgBetter = true; 4303 } 4304 } 4305 } 4306 4307 if (updatedPkg != null) { 4308 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4309 // initially 4310 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4311 4312 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4313 // flag set initially 4314 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4315 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4316 } 4317 } 4318 4319 // Verify certificates against what was last scanned 4320 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4321 4322 /* 4323 * A new system app appeared, but we already had a non-system one of the 4324 * same name installed earlier. 4325 */ 4326 boolean shouldHideSystemApp = false; 4327 if (updatedPkg == null && ps != null 4328 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4329 /* 4330 * Check to make sure the signatures match first. If they don't, 4331 * wipe the installed application and its data. 4332 */ 4333 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4334 != PackageManager.SIGNATURE_MATCH) { 4335 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4336 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4337 ps = null; 4338 } else { 4339 /* 4340 * If the newly-added system app is an older version than the 4341 * already installed version, hide it. It will be scanned later 4342 * and re-added like an update. 4343 */ 4344 if (pkg.mVersionCode < ps.versionCode) { 4345 shouldHideSystemApp = true; 4346 } else { 4347 /* 4348 * The newly found system app is a newer version that the 4349 * one previously installed. Simply remove the 4350 * already-installed application and replace it with our own 4351 * while keeping the application data. 4352 */ 4353 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4354 + ps.codePathString + ": new version " + pkg.mVersionCode 4355 + " better than installed " + ps.versionCode); 4356 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4357 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4358 getAppDexInstructionSets(ps), isMultiArch(ps)); 4359 synchronized (mInstallLock) { 4360 args.cleanUpResourcesLI(); 4361 } 4362 } 4363 } 4364 } 4365 4366 // The apk is forward locked (not public) if its code and resources 4367 // are kept in different files. (except for app in either system or 4368 // vendor path). 4369 // TODO grab this value from PackageSettings 4370 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4371 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4372 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4373 } 4374 } 4375 4376 // TODO: extend to support forward-locked splits 4377 String resourcePath = null; 4378 String baseResourcePath = null; 4379 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4380 if (ps != null && ps.resourcePathString != null) { 4381 resourcePath = ps.resourcePathString; 4382 baseResourcePath = ps.resourcePathString; 4383 } else { 4384 // Should not happen at all. Just log an error. 4385 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4386 } 4387 } else { 4388 resourcePath = pkg.codePath; 4389 baseResourcePath = pkg.baseCodePath; 4390 } 4391 4392 // Set application objects path explicitly. 4393 pkg.applicationInfo.setCodePath(pkg.codePath); 4394 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4395 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4396 pkg.applicationInfo.setResourcePath(resourcePath); 4397 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4398 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4399 4400 // Note that we invoke the following method only if we are about to unpack an application 4401 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4402 | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride); 4403 4404 /* 4405 * If the system app should be overridden by a previously installed 4406 * data, hide the system app now and let the /data/app scan pick it up 4407 * again. 4408 */ 4409 if (shouldHideSystemApp) { 4410 synchronized (mPackages) { 4411 /* 4412 * We have to grant systems permissions before we hide, because 4413 * grantPermissions will assume the package update is trying to 4414 * expand its permissions. 4415 */ 4416 grantPermissionsLPw(pkg, true); 4417 mSettings.disableSystemPackageLPw(pkg.packageName); 4418 } 4419 } 4420 4421 return scannedPkg; 4422 } 4423 4424 private static String fixProcessName(String defProcessName, 4425 String processName, int uid) { 4426 if (processName == null) { 4427 return defProcessName; 4428 } 4429 return processName; 4430 } 4431 4432 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4433 throws PackageManagerException { 4434 if (pkgSetting.signatures.mSignatures != null) { 4435 // Already existing package. Make sure signatures match 4436 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4437 == PackageManager.SIGNATURE_MATCH; 4438 if (!match) { 4439 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4440 == PackageManager.SIGNATURE_MATCH; 4441 } 4442 if (!match) { 4443 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4444 + pkg.packageName + " signatures do not match the " 4445 + "previously installed version; ignoring!"); 4446 } 4447 } 4448 4449 // Check for shared user signatures 4450 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4451 // Already existing package. Make sure signatures match 4452 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4453 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4454 if (!match) { 4455 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4456 == PackageManager.SIGNATURE_MATCH; 4457 } 4458 if (!match) { 4459 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4460 "Package " + pkg.packageName 4461 + " has no signatures that match those in shared user " 4462 + pkgSetting.sharedUser.name + "; ignoring!"); 4463 } 4464 } 4465 } 4466 4467 /** 4468 * Enforces that only the system UID or root's UID can call a method exposed 4469 * via Binder. 4470 * 4471 * @param message used as message if SecurityException is thrown 4472 * @throws SecurityException if the caller is not system or root 4473 */ 4474 private static final void enforceSystemOrRoot(String message) { 4475 final int uid = Binder.getCallingUid(); 4476 if (uid != Process.SYSTEM_UID && uid != 0) { 4477 throw new SecurityException(message); 4478 } 4479 } 4480 4481 @Override 4482 public void performBootDexOpt() { 4483 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4484 4485 final HashSet<PackageParser.Package> pkgs; 4486 synchronized (mPackages) { 4487 pkgs = mDeferredDexOpt; 4488 mDeferredDexOpt = null; 4489 } 4490 4491 if (pkgs != null) { 4492 // Filter out packages that aren't recently used. 4493 // 4494 // The exception is first boot of a non-eng device, which 4495 // should do a full dexopt. 4496 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4497 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4498 // TODO: add a property to control this? 4499 long dexOptLRUThresholdInMinutes; 4500 if (eng) { 4501 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4502 } else { 4503 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4504 } 4505 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4506 4507 int total = pkgs.size(); 4508 int skipped = 0; 4509 long now = System.currentTimeMillis(); 4510 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4511 PackageParser.Package pkg = i.next(); 4512 long then = pkg.mLastPackageUsageTimeInMills; 4513 if (then + dexOptLRUThresholdInMills < now) { 4514 if (DEBUG_DEXOPT) { 4515 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4516 ((then == 0) ? "never" : new Date(then))); 4517 } 4518 i.remove(); 4519 skipped++; 4520 } 4521 } 4522 if (DEBUG_DEXOPT) { 4523 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4524 } 4525 } 4526 4527 int i = 0; 4528 for (PackageParser.Package pkg : pkgs) { 4529 i++; 4530 if (DEBUG_DEXOPT) { 4531 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4532 + ": " + pkg.packageName); 4533 } 4534 if (!isFirstBoot()) { 4535 try { 4536 ActivityManagerNative.getDefault().showBootMessage( 4537 mContext.getResources().getString( 4538 R.string.android_upgrading_apk, 4539 i, pkgs.size()), true); 4540 } catch (RemoteException e) { 4541 } 4542 } 4543 PackageParser.Package p = pkg; 4544 synchronized (mInstallLock) { 4545 if (p.mDexOptNeeded) { 4546 performDexOptLI(p, false /* force dex */, false /* defer */, 4547 true /* include dependencies */); 4548 } 4549 } 4550 } 4551 } 4552 } 4553 4554 @Override 4555 public boolean performDexOpt(String packageName) { 4556 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4557 return performDexOpt(packageName, true); 4558 } 4559 4560 public boolean performDexOpt(String packageName, boolean updateUsage) { 4561 4562 PackageParser.Package p; 4563 synchronized (mPackages) { 4564 p = mPackages.get(packageName); 4565 if (p == null) { 4566 return false; 4567 } 4568 if (updateUsage) { 4569 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4570 } 4571 mPackageUsage.write(false); 4572 if (!p.mDexOptNeeded) { 4573 return false; 4574 } 4575 } 4576 4577 synchronized (mInstallLock) { 4578 return performDexOptLI(p, false /* force dex */, false /* defer */, 4579 true /* include dependencies */) == DEX_OPT_PERFORMED; 4580 } 4581 } 4582 4583 public HashSet<String> getPackagesThatNeedDexOpt() { 4584 HashSet<String> pkgs = null; 4585 synchronized (mPackages) { 4586 for (PackageParser.Package p : mPackages.values()) { 4587 if (DEBUG_DEXOPT) { 4588 Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded); 4589 } 4590 if (!p.mDexOptNeeded) { 4591 continue; 4592 } 4593 if (pkgs == null) { 4594 pkgs = new HashSet<String>(); 4595 } 4596 pkgs.add(p.packageName); 4597 } 4598 } 4599 return pkgs; 4600 } 4601 4602 public void shutdown() { 4603 mPackageUsage.write(true); 4604 } 4605 4606 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4607 boolean forceDex, boolean defer, HashSet<String> done) { 4608 for (int i=0; i<libs.size(); i++) { 4609 PackageParser.Package libPkg; 4610 String libName; 4611 synchronized (mPackages) { 4612 libName = libs.get(i); 4613 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4614 if (lib != null && lib.apk != null) { 4615 libPkg = mPackages.get(lib.apk); 4616 } else { 4617 libPkg = null; 4618 } 4619 } 4620 if (libPkg != null && !done.contains(libName)) { 4621 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4622 } 4623 } 4624 } 4625 4626 static final int DEX_OPT_SKIPPED = 0; 4627 static final int DEX_OPT_PERFORMED = 1; 4628 static final int DEX_OPT_DEFERRED = 2; 4629 static final int DEX_OPT_FAILED = -1; 4630 4631 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4632 boolean forceDex, boolean defer, HashSet<String> done) { 4633 final String[] instructionSets = targetInstructionSets != null ? 4634 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4635 4636 if (done != null) { 4637 done.add(pkg.packageName); 4638 if (pkg.usesLibraries != null) { 4639 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4640 } 4641 if (pkg.usesOptionalLibraries != null) { 4642 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4643 } 4644 } 4645 4646 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4647 return DEX_OPT_SKIPPED; 4648 } 4649 4650 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4651 boolean performedDexOpt = false; 4652 // There are three basic cases here: 4653 // 1.) we need to dexopt, either because we are forced or it is needed 4654 // 2.) we are defering a needed dexopt 4655 // 3.) we are skipping an unneeded dexopt 4656 for (String path : paths) { 4657 for (String instructionSet : instructionSets) { 4658 try { 4659 final boolean isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4660 pkg.packageName, instructionSet, defer); 4661 if (forceDex || (!defer && isDexOptNeeded)) { 4662 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4663 + pkg.applicationInfo.packageName + " isa=" + instructionSet); 4664 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4665 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4666 pkg.packageName, instructionSet); 4667 4668 if (ret < 0) { 4669 // Don't bother running dexopt again if we failed, it will probably 4670 // just result in an error again. Also, don't bother dexopting for other 4671 // paths & ISAs. 4672 pkg.mDexOptNeeded = false; 4673 return DEX_OPT_FAILED; 4674 } else { 4675 performedDexOpt = true; 4676 } 4677 } 4678 4679 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4680 // paths and instruction sets. We'll deal with them all together when we process 4681 // our list of deferred dexopts. 4682 if (defer && isDexOptNeeded) { 4683 if (mDeferredDexOpt == null) { 4684 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4685 } 4686 mDeferredDexOpt.add(pkg); 4687 return DEX_OPT_DEFERRED; 4688 } 4689 } catch (FileNotFoundException e) { 4690 Slog.w(TAG, "Apk not found for dexopt: " + path); 4691 return DEX_OPT_FAILED; 4692 } catch (IOException e) { 4693 Slog.w(TAG, "IOException reading apk: " + path, e); 4694 return DEX_OPT_FAILED; 4695 } catch (StaleDexCacheError e) { 4696 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4697 return DEX_OPT_FAILED; 4698 } catch (Exception e) { 4699 Slog.w(TAG, "Exception when doing dexopt : ", e); 4700 return DEX_OPT_FAILED; 4701 } 4702 } 4703 } 4704 4705 // If we've gotten here, we're sure that no error occurred and that we haven't 4706 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4707 // we've skipped all of them because they are up to date. In both cases this 4708 // package doesn't need dexopt any longer. 4709 pkg.mDexOptNeeded = false; 4710 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4711 } 4712 4713 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4714 if (info.primaryCpuAbi != null) { 4715 if (info.secondaryCpuAbi != null) { 4716 return new String[] { 4717 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4718 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4719 } else { 4720 return new String[] { 4721 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4722 } 4723 } 4724 4725 return new String[] { getPreferredInstructionSet() }; 4726 } 4727 4728 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4729 if (ps.primaryCpuAbiString != null) { 4730 if (ps.secondaryCpuAbiString != null) { 4731 return new String[] { 4732 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4733 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4734 } else { 4735 return new String[] { 4736 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4737 } 4738 } 4739 4740 return new String[] { getPreferredInstructionSet() }; 4741 } 4742 4743 private static String getPreferredInstructionSet() { 4744 if (sPreferredInstructionSet == null) { 4745 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4746 } 4747 4748 return sPreferredInstructionSet; 4749 } 4750 4751 private static List<String> getAllInstructionSets() { 4752 final String[] allAbis = Build.SUPPORTED_ABIS; 4753 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4754 4755 for (String abi : allAbis) { 4756 final String instructionSet = VMRuntime.getInstructionSet(abi); 4757 if (!allInstructionSets.contains(instructionSet)) { 4758 allInstructionSets.add(instructionSet); 4759 } 4760 } 4761 4762 return allInstructionSets; 4763 } 4764 4765 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer, 4766 boolean inclDependencies) { 4767 HashSet<String> done; 4768 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4769 done = new HashSet<String>(); 4770 done.add(pkg.packageName); 4771 } else { 4772 done = null; 4773 } 4774 return performDexOptLI(pkg, null /* target instruction sets */, forceDex, defer, done); 4775 } 4776 4777 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4778 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4779 Slog.w(TAG, "Unable to update from " + oldPkg.name 4780 + " to " + newPkg.packageName 4781 + ": old package not in system partition"); 4782 return false; 4783 } else if (mPackages.get(oldPkg.name) != null) { 4784 Slog.w(TAG, "Unable to update from " + oldPkg.name 4785 + " to " + newPkg.packageName 4786 + ": old package still exists"); 4787 return false; 4788 } 4789 return true; 4790 } 4791 4792 File getDataPathForUser(int userId) { 4793 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4794 } 4795 4796 private File getDataPathForPackage(String packageName, int userId) { 4797 /* 4798 * Until we fully support multiple users, return the directory we 4799 * previously would have. The PackageManagerTests will need to be 4800 * revised when this is changed back.. 4801 */ 4802 if (userId == 0) { 4803 return new File(mAppDataDir, packageName); 4804 } else { 4805 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4806 + File.separator + packageName); 4807 } 4808 } 4809 4810 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4811 int[] users = sUserManager.getUserIds(); 4812 int res = mInstaller.install(packageName, uid, uid, seinfo); 4813 if (res < 0) { 4814 return res; 4815 } 4816 for (int user : users) { 4817 if (user != 0) { 4818 res = mInstaller.createUserData(packageName, 4819 UserHandle.getUid(user, uid), user, seinfo); 4820 if (res < 0) { 4821 return res; 4822 } 4823 } 4824 } 4825 return res; 4826 } 4827 4828 private int removeDataDirsLI(String packageName) { 4829 int[] users = sUserManager.getUserIds(); 4830 int res = 0; 4831 for (int user : users) { 4832 int resInner = mInstaller.remove(packageName, user); 4833 if (resInner < 0) { 4834 res = resInner; 4835 } 4836 } 4837 4838 return res; 4839 } 4840 4841 private int deleteCodeCacheDirsLI(String packageName) { 4842 int[] users = sUserManager.getUserIds(); 4843 int res = 0; 4844 for (int user : users) { 4845 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4846 if (resInner < 0) { 4847 res = resInner; 4848 } 4849 } 4850 return res; 4851 } 4852 4853 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4854 PackageParser.Package changingLib) { 4855 if (file.path != null) { 4856 usesLibraryFiles.add(file.path); 4857 return; 4858 } 4859 PackageParser.Package p = mPackages.get(file.apk); 4860 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4861 // If we are doing this while in the middle of updating a library apk, 4862 // then we need to make sure to use that new apk for determining the 4863 // dependencies here. (We haven't yet finished committing the new apk 4864 // to the package manager state.) 4865 if (p == null || p.packageName.equals(changingLib.packageName)) { 4866 p = changingLib; 4867 } 4868 } 4869 if (p != null) { 4870 usesLibraryFiles.addAll(p.getAllCodePaths()); 4871 } 4872 } 4873 4874 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4875 PackageParser.Package changingLib) throws PackageManagerException { 4876 // We might be upgrading from a version of the platform that did not 4877 // provide per-package native library directories for system apps. 4878 // Fix that up here. 4879 if (isSystemApp(pkg)) { 4880 PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName); 4881 if (!isUpdatedSystemApp(pkg)) { 4882 setBundledAppAbisAndRoots(pkg, ps); 4883 } 4884 } 4885 4886 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4887 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4888 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4889 for (int i=0; i<N; i++) { 4890 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4891 if (file == null) { 4892 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4893 "Package " + pkg.packageName + " requires unavailable shared library " 4894 + pkg.usesLibraries.get(i) + "; failing!"); 4895 } 4896 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4897 } 4898 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4899 for (int i=0; i<N; i++) { 4900 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4901 if (file == null) { 4902 Slog.w(TAG, "Package " + pkg.packageName 4903 + " desires unavailable shared library " 4904 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4905 } else { 4906 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4907 } 4908 } 4909 N = usesLibraryFiles.size(); 4910 if (N > 0) { 4911 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4912 } else { 4913 pkg.usesLibraryFiles = null; 4914 } 4915 } 4916 } 4917 4918 private static boolean hasString(List<String> list, List<String> which) { 4919 if (list == null) { 4920 return false; 4921 } 4922 for (int i=list.size()-1; i>=0; i--) { 4923 for (int j=which.size()-1; j>=0; j--) { 4924 if (which.get(j).equals(list.get(i))) { 4925 return true; 4926 } 4927 } 4928 } 4929 return false; 4930 } 4931 4932 private void updateAllSharedLibrariesLPw() { 4933 for (PackageParser.Package pkg : mPackages.values()) { 4934 try { 4935 updateSharedLibrariesLPw(pkg, null); 4936 } catch (PackageManagerException e) { 4937 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4938 } 4939 } 4940 } 4941 4942 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4943 PackageParser.Package changingPkg) { 4944 ArrayList<PackageParser.Package> res = null; 4945 for (PackageParser.Package pkg : mPackages.values()) { 4946 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4947 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4948 if (res == null) { 4949 res = new ArrayList<PackageParser.Package>(); 4950 } 4951 res.add(pkg); 4952 try { 4953 updateSharedLibrariesLPw(pkg, changingPkg); 4954 } catch (PackageManagerException e) { 4955 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4956 } 4957 } 4958 } 4959 return res; 4960 } 4961 4962 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 4963 int scanMode, long currentTime, UserHandle user, String abiOverride) 4964 throws PackageManagerException { 4965 final File scanFile = new File(pkg.codePath); 4966 if (pkg.applicationInfo.getCodePath() == null || 4967 pkg.applicationInfo.getResourcePath() == null) { 4968 // Bail out. The resource and code paths haven't been set. 4969 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 4970 "Code and resource paths haven't been set correctly"); 4971 } 4972 4973 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4974 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4975 } 4976 4977 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4978 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4979 } 4980 4981 if (mCustomResolverComponentName != null && 4982 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4983 setUpCustomResolverActivity(pkg); 4984 } 4985 4986 if (pkg.packageName.equals("android")) { 4987 synchronized (mPackages) { 4988 if (mAndroidApplication != null) { 4989 Slog.w(TAG, "*************************************************"); 4990 Slog.w(TAG, "Core android package being redefined. Skipping."); 4991 Slog.w(TAG, " file=" + scanFile); 4992 Slog.w(TAG, "*************************************************"); 4993 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 4994 "Core android package being redefined. Skipping."); 4995 } 4996 4997 // Set up information for our fall-back user intent resolution activity. 4998 mPlatformPackage = pkg; 4999 pkg.mVersionCode = mSdkVersion; 5000 mAndroidApplication = pkg.applicationInfo; 5001 5002 if (!mResolverReplaced) { 5003 mResolveActivity.applicationInfo = mAndroidApplication; 5004 mResolveActivity.name = ResolverActivity.class.getName(); 5005 mResolveActivity.packageName = mAndroidApplication.packageName; 5006 mResolveActivity.processName = "system:ui"; 5007 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5008 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5009 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5010 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5011 mResolveActivity.exported = true; 5012 mResolveActivity.enabled = true; 5013 mResolveInfo.activityInfo = mResolveActivity; 5014 mResolveInfo.priority = 0; 5015 mResolveInfo.preferredOrder = 0; 5016 mResolveInfo.match = 0; 5017 mResolveComponentName = new ComponentName( 5018 mAndroidApplication.packageName, mResolveActivity.name); 5019 } 5020 } 5021 } 5022 5023 if (DEBUG_PACKAGE_SCANNING) { 5024 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5025 Log.d(TAG, "Scanning package " + pkg.packageName); 5026 } 5027 5028 if (mPackages.containsKey(pkg.packageName) 5029 || mSharedLibraries.containsKey(pkg.packageName)) { 5030 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5031 "Application package " + pkg.packageName 5032 + " already installed. Skipping duplicate."); 5033 } 5034 5035 // Initialize package source and resource directories 5036 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5037 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5038 5039 SharedUserSetting suid = null; 5040 PackageSetting pkgSetting = null; 5041 5042 if (!isSystemApp(pkg)) { 5043 // Only system apps can use these features. 5044 pkg.mOriginalPackages = null; 5045 pkg.mRealPackage = null; 5046 pkg.mAdoptPermissions = null; 5047 } 5048 5049 // writer 5050 synchronized (mPackages) { 5051 if (pkg.mSharedUserId != null) { 5052 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5053 if (suid == null) { 5054 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5055 "Creating application package " + pkg.packageName 5056 + " for shared user failed"); 5057 } 5058 if (DEBUG_PACKAGE_SCANNING) { 5059 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5060 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5061 + "): packages=" + suid.packages); 5062 } 5063 } 5064 5065 // Check if we are renaming from an original package name. 5066 PackageSetting origPackage = null; 5067 String realName = null; 5068 if (pkg.mOriginalPackages != null) { 5069 // This package may need to be renamed to a previously 5070 // installed name. Let's check on that... 5071 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5072 if (pkg.mOriginalPackages.contains(renamed)) { 5073 // This package had originally been installed as the 5074 // original name, and we have already taken care of 5075 // transitioning to the new one. Just update the new 5076 // one to continue using the old name. 5077 realName = pkg.mRealPackage; 5078 if (!pkg.packageName.equals(renamed)) { 5079 // Callers into this function may have already taken 5080 // care of renaming the package; only do it here if 5081 // it is not already done. 5082 pkg.setPackageName(renamed); 5083 } 5084 5085 } else { 5086 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5087 if ((origPackage = mSettings.peekPackageLPr( 5088 pkg.mOriginalPackages.get(i))) != null) { 5089 // We do have the package already installed under its 5090 // original name... should we use it? 5091 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5092 // New package is not compatible with original. 5093 origPackage = null; 5094 continue; 5095 } else if (origPackage.sharedUser != null) { 5096 // Make sure uid is compatible between packages. 5097 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5098 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5099 + " to " + pkg.packageName + ": old uid " 5100 + origPackage.sharedUser.name 5101 + " differs from " + pkg.mSharedUserId); 5102 origPackage = null; 5103 continue; 5104 } 5105 } else { 5106 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5107 + pkg.packageName + " to old name " + origPackage.name); 5108 } 5109 break; 5110 } 5111 } 5112 } 5113 } 5114 5115 if (mTransferedPackages.contains(pkg.packageName)) { 5116 Slog.w(TAG, "Package " + pkg.packageName 5117 + " was transferred to another, but its .apk remains"); 5118 } 5119 5120 // Just create the setting, don't add it yet. For already existing packages 5121 // the PkgSetting exists already and doesn't have to be created. 5122 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5123 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5124 pkg.applicationInfo.primaryCpuAbi, 5125 pkg.applicationInfo.secondaryCpuAbi, 5126 pkg.applicationInfo.flags, user, false); 5127 if (pkgSetting == null) { 5128 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5129 "Creating application package " + pkg.packageName + " failed"); 5130 } 5131 5132 if (pkgSetting.origPackage != null) { 5133 // If we are first transitioning from an original package, 5134 // fix up the new package's name now. We need to do this after 5135 // looking up the package under its new name, so getPackageLP 5136 // can take care of fiddling things correctly. 5137 pkg.setPackageName(origPackage.name); 5138 5139 // File a report about this. 5140 String msg = "New package " + pkgSetting.realName 5141 + " renamed to replace old package " + pkgSetting.name; 5142 reportSettingsProblem(Log.WARN, msg); 5143 5144 // Make a note of it. 5145 mTransferedPackages.add(origPackage.name); 5146 5147 // No longer need to retain this. 5148 pkgSetting.origPackage = null; 5149 } 5150 5151 if (realName != null) { 5152 // Make a note of it. 5153 mTransferedPackages.add(pkg.packageName); 5154 } 5155 5156 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5157 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5158 } 5159 5160 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5161 // Check all shared libraries and map to their actual file path. 5162 // We only do this here for apps not on a system dir, because those 5163 // are the only ones that can fail an install due to this. We 5164 // will take care of the system apps by updating all of their 5165 // library paths after the scan is done. 5166 updateSharedLibrariesLPw(pkg, null); 5167 } 5168 5169 if (mFoundPolicyFile) { 5170 SELinuxMMAC.assignSeinfoValue(pkg); 5171 } 5172 5173 pkg.applicationInfo.uid = pkgSetting.appId; 5174 pkg.mExtras = pkgSetting; 5175 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5176 try { 5177 verifySignaturesLP(pkgSetting, pkg); 5178 } catch (PackageManagerException e) { 5179 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5180 throw e; 5181 } 5182 // The signature has changed, but this package is in the system 5183 // image... let's recover! 5184 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5185 // However... if this package is part of a shared user, but it 5186 // doesn't match the signature of the shared user, let's fail. 5187 // What this means is that you can't change the signatures 5188 // associated with an overall shared user, which doesn't seem all 5189 // that unreasonable. 5190 if (pkgSetting.sharedUser != null) { 5191 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5192 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5193 throw new PackageManagerException( 5194 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5195 "Signature mismatch for shared user : " 5196 + pkgSetting.sharedUser); 5197 } 5198 } 5199 // File a report about this. 5200 String msg = "System package " + pkg.packageName 5201 + " signature changed; retaining data."; 5202 reportSettingsProblem(Log.WARN, msg); 5203 } 5204 } else { 5205 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5206 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5207 + pkg.packageName + " upgrade keys do not match the " 5208 + "previously installed version"); 5209 } else { 5210 // signatures may have changed as result of upgrade 5211 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5212 } 5213 } 5214 // Verify that this new package doesn't have any content providers 5215 // that conflict with existing packages. Only do this if the 5216 // package isn't already installed, since we don't want to break 5217 // things that are installed. 5218 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5219 final int N = pkg.providers.size(); 5220 int i; 5221 for (i=0; i<N; i++) { 5222 PackageParser.Provider p = pkg.providers.get(i); 5223 if (p.info.authority != null) { 5224 String names[] = p.info.authority.split(";"); 5225 for (int j = 0; j < names.length; j++) { 5226 if (mProvidersByAuthority.containsKey(names[j])) { 5227 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5228 final String otherPackageName = 5229 ((other != null && other.getComponentName() != null) ? 5230 other.getComponentName().getPackageName() : "?"); 5231 throw new PackageManagerException( 5232 INSTALL_FAILED_CONFLICTING_PROVIDER, 5233 "Can't install because provider name " + names[j] 5234 + " (in package " + pkg.applicationInfo.packageName 5235 + ") is already used by " + otherPackageName); 5236 } 5237 } 5238 } 5239 } 5240 } 5241 5242 if (pkg.mAdoptPermissions != null) { 5243 // This package wants to adopt ownership of permissions from 5244 // another package. 5245 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5246 final String origName = pkg.mAdoptPermissions.get(i); 5247 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5248 if (orig != null) { 5249 if (verifyPackageUpdateLPr(orig, pkg)) { 5250 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5251 + pkg.packageName); 5252 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5253 } 5254 } 5255 } 5256 } 5257 } 5258 5259 final String pkgName = pkg.packageName; 5260 5261 final long scanFileTime = scanFile.lastModified(); 5262 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5263 pkg.applicationInfo.processName = fixProcessName( 5264 pkg.applicationInfo.packageName, 5265 pkg.applicationInfo.processName, 5266 pkg.applicationInfo.uid); 5267 5268 File dataPath; 5269 if (mPlatformPackage == pkg) { 5270 // The system package is special. 5271 dataPath = new File (Environment.getDataDirectory(), "system"); 5272 pkg.applicationInfo.dataDir = dataPath.getPath(); 5273 } else { 5274 // This is a normal package, need to make its data directory. 5275 dataPath = getDataPathForPackage(pkg.packageName, 0); 5276 5277 boolean uidError = false; 5278 5279 if (dataPath.exists()) { 5280 int currentUid = 0; 5281 try { 5282 StructStat stat = Os.stat(dataPath.getPath()); 5283 currentUid = stat.st_uid; 5284 } catch (ErrnoException e) { 5285 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5286 } 5287 5288 // If we have mismatched owners for the data path, we have a problem. 5289 if (currentUid != pkg.applicationInfo.uid) { 5290 boolean recovered = false; 5291 if (currentUid == 0) { 5292 // The directory somehow became owned by root. Wow. 5293 // This is probably because the system was stopped while 5294 // installd was in the middle of messing with its libs 5295 // directory. Ask installd to fix that. 5296 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5297 pkg.applicationInfo.uid); 5298 if (ret >= 0) { 5299 recovered = true; 5300 String msg = "Package " + pkg.packageName 5301 + " unexpectedly changed to uid 0; recovered to " + 5302 + pkg.applicationInfo.uid; 5303 reportSettingsProblem(Log.WARN, msg); 5304 } 5305 } 5306 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5307 || (scanMode&SCAN_BOOTING) != 0)) { 5308 // If this is a system app, we can at least delete its 5309 // current data so the application will still work. 5310 int ret = removeDataDirsLI(pkgName); 5311 if (ret >= 0) { 5312 // TODO: Kill the processes first 5313 // Old data gone! 5314 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5315 ? "System package " : "Third party package "; 5316 String msg = prefix + pkg.packageName 5317 + " has changed from uid: " 5318 + currentUid + " to " 5319 + pkg.applicationInfo.uid + "; old data erased"; 5320 reportSettingsProblem(Log.WARN, msg); 5321 recovered = true; 5322 5323 // And now re-install the app. 5324 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5325 pkg.applicationInfo.seinfo); 5326 if (ret == -1) { 5327 // Ack should not happen! 5328 msg = prefix + pkg.packageName 5329 + " could not have data directory re-created after delete."; 5330 reportSettingsProblem(Log.WARN, msg); 5331 throw new PackageManagerException( 5332 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5333 } 5334 } 5335 if (!recovered) { 5336 mHasSystemUidErrors = true; 5337 } 5338 } else if (!recovered) { 5339 // If we allow this install to proceed, we will be broken. 5340 // Abort, abort! 5341 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5342 "scanPackageLI"); 5343 } 5344 if (!recovered) { 5345 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5346 + pkg.applicationInfo.uid + "/fs_" 5347 + currentUid; 5348 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5349 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5350 String msg = "Package " + pkg.packageName 5351 + " has mismatched uid: " 5352 + currentUid + " on disk, " 5353 + pkg.applicationInfo.uid + " in settings"; 5354 // writer 5355 synchronized (mPackages) { 5356 mSettings.mReadMessages.append(msg); 5357 mSettings.mReadMessages.append('\n'); 5358 uidError = true; 5359 if (!pkgSetting.uidError) { 5360 reportSettingsProblem(Log.ERROR, msg); 5361 } 5362 } 5363 } 5364 } 5365 pkg.applicationInfo.dataDir = dataPath.getPath(); 5366 if (mShouldRestoreconData) { 5367 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5368 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5369 pkg.applicationInfo.uid); 5370 } 5371 } else { 5372 if (DEBUG_PACKAGE_SCANNING) { 5373 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5374 Log.v(TAG, "Want this data dir: " + dataPath); 5375 } 5376 //invoke installer to do the actual installation 5377 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5378 pkg.applicationInfo.seinfo); 5379 if (ret < 0) { 5380 // Error from installer 5381 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5382 "Unable to create data dirs [errorCode=" + ret + "]"); 5383 } 5384 5385 if (dataPath.exists()) { 5386 pkg.applicationInfo.dataDir = dataPath.getPath(); 5387 } else { 5388 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5389 pkg.applicationInfo.dataDir = null; 5390 } 5391 } 5392 5393 pkgSetting.uidError = uidError; 5394 } 5395 5396 final String path = scanFile.getPath(); 5397 final String codePath = pkg.applicationInfo.getCodePath(); 5398 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5399 // For the case where we had previously uninstalled an update, get rid 5400 // of any native binaries we might have unpackaged. Note that this assumes 5401 // that system app updates were not installed via ASEC. 5402 // 5403 // TODO(multiArch): Is this cleanup really necessary ? 5404 NativeLibraryHelper.removeNativeBinariesFromDirLI( 5405 new File(codePath, LIB_DIR_NAME), false /* delete dirs */); 5406 setBundledAppAbisAndRoots(pkg, pkgSetting); 5407 setNativeLibraryPaths(pkg); 5408 } else { 5409 // TODO: We can probably be smarter about this stuff. For installed apps, 5410 // we can calculate this information at install time once and for all. For 5411 // system apps, we can probably assume that this information doesn't change 5412 // after the first boot scan. As things stand, we do lots of unnecessary work. 5413 5414 // Give ourselves some initial paths; we'll come back for another 5415 // pass once we've determined ABI below. 5416 setNativeLibraryPaths(pkg); 5417 5418 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5419 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5420 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5421 5422 NativeLibraryHelper.Handle handle = null; 5423 try { 5424 handle = NativeLibraryHelper.Handle.create(scanFile); 5425 // TODO(multiArch): This can be null for apps that didn't go through the 5426 // usual installation process. We can calculate it again, like we 5427 // do during install time. 5428 // 5429 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5430 // unnecessary. 5431 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5432 5433 // Null out the abis so that they can be recalculated. 5434 pkg.applicationInfo.primaryCpuAbi = null; 5435 pkg.applicationInfo.secondaryCpuAbi = null; 5436 if (isMultiArch(pkg.applicationInfo)) { 5437 // Warn if we've set an abiOverride for multi-lib packages.. 5438 // By definition, we need to copy both 32 and 64 bit libraries for 5439 // such packages. 5440 if (abiOverride != null) { 5441 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5442 } 5443 5444 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5445 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5446 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5447 if (isAsec) { 5448 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5449 } else { 5450 abi32 = copyNativeLibrariesForInternalApp(handle, 5451 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs); 5452 } 5453 } 5454 5455 maybeThrowExceptionForMultiArchCopy( 5456 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5457 5458 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5459 if (isAsec) { 5460 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5461 } else { 5462 abi64 = copyNativeLibrariesForInternalApp(handle, 5463 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs); 5464 } 5465 } 5466 5467 maybeThrowExceptionForMultiArchCopy( 5468 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5469 5470 if (abi64 >= 0) { 5471 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5472 } 5473 5474 if (abi32 >= 0) { 5475 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5476 if (abi64 >= 0) { 5477 pkg.applicationInfo.secondaryCpuAbi = abi; 5478 } else { 5479 pkg.applicationInfo.primaryCpuAbi = abi; 5480 } 5481 } 5482 } else { 5483 String[] abiList = (abiOverride != null) ? 5484 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 5485 5486 // Enable gross and lame hacks for apps that are built with old 5487 // SDK tools. We must scan their APKs for renderscript bitcode and 5488 // not launch them if it's present. Don't bother checking on devices 5489 // that don't have 64 bit support. 5490 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null && 5491 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5492 abiList = Build.SUPPORTED_32_BIT_ABIS; 5493 } 5494 5495 final int copyRet; 5496 if (isAsec) { 5497 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5498 } else { 5499 copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryRoot, abiList, 5500 useIsaSpecificSubdirs); 5501 } 5502 5503 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5504 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5505 "Error unpackaging native libs for app, errorCode=" + copyRet); 5506 } 5507 5508 if (copyRet >= 0) { 5509 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5510 } 5511 } 5512 } catch (IOException ioe) { 5513 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5514 } finally { 5515 IoUtils.closeQuietly(handle); 5516 } 5517 5518 // Now that we've calculated the ABIs and determined if it's an internal app, 5519 // we will go ahead and populate the nativeLibraryPath. 5520 setNativeLibraryPaths(pkg); 5521 5522 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5523 final int[] userIds = sUserManager.getUserIds(); 5524 synchronized (mInstallLock) { 5525 // Create a native library symlink only if we have native libraries 5526 // and if the native libraries are 32 bit libraries. We do not provide 5527 // this symlink for 64 bit libraries. 5528 if (pkg.applicationInfo.primaryCpuAbi != null && 5529 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5530 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5531 for (int userId : userIds) { 5532 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5533 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5534 "Failed linking native library dir (user=" + userId + ")"); 5535 } 5536 } 5537 } 5538 } 5539 5540 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5541 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5542 } 5543 5544 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5545 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5546 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5547 5548 // Push the derived path down into PackageSettings so we know what to 5549 // clean up at uninstall time. 5550 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5551 5552 if (DEBUG_ABI_SELECTION) { 5553 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5554 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5555 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5556 } 5557 5558 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5559 // We don't do this here during boot because we can do it all 5560 // at once after scanning all existing packages. 5561 // 5562 // We also do this *before* we perform dexopt on this package, so that 5563 // we can avoid redundant dexopts, and also to make sure we've got the 5564 // code and package path correct. 5565 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5566 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0); 5567 } 5568 5569 if ((scanMode&SCAN_NO_DEX) == 0) { 5570 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5571 == DEX_OPT_FAILED) { 5572 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5573 removeDataDirsLI(pkg.packageName); 5574 } 5575 5576 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5577 } 5578 } 5579 5580 if (mFactoryTest && pkg.requestedPermissions.contains( 5581 android.Manifest.permission.FACTORY_TEST)) { 5582 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5583 } 5584 5585 ArrayList<PackageParser.Package> clientLibPkgs = null; 5586 5587 // writer 5588 synchronized (mPackages) { 5589 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5590 // Only system apps can add new shared libraries. 5591 if (pkg.libraryNames != null) { 5592 for (int i=0; i<pkg.libraryNames.size(); i++) { 5593 String name = pkg.libraryNames.get(i); 5594 boolean allowed = false; 5595 if (isUpdatedSystemApp(pkg)) { 5596 // New library entries can only be added through the 5597 // system image. This is important to get rid of a lot 5598 // of nasty edge cases: for example if we allowed a non- 5599 // system update of the app to add a library, then uninstalling 5600 // the update would make the library go away, and assumptions 5601 // we made such as through app install filtering would now 5602 // have allowed apps on the device which aren't compatible 5603 // with it. Better to just have the restriction here, be 5604 // conservative, and create many fewer cases that can negatively 5605 // impact the user experience. 5606 final PackageSetting sysPs = mSettings 5607 .getDisabledSystemPkgLPr(pkg.packageName); 5608 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5609 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5610 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5611 allowed = true; 5612 allowed = true; 5613 break; 5614 } 5615 } 5616 } 5617 } else { 5618 allowed = true; 5619 } 5620 if (allowed) { 5621 if (!mSharedLibraries.containsKey(name)) { 5622 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5623 } else if (!name.equals(pkg.packageName)) { 5624 Slog.w(TAG, "Package " + pkg.packageName + " library " 5625 + name + " already exists; skipping"); 5626 } 5627 } else { 5628 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5629 + name + " that is not declared on system image; skipping"); 5630 } 5631 } 5632 if ((scanMode&SCAN_BOOTING) == 0) { 5633 // If we are not booting, we need to update any applications 5634 // that are clients of our shared library. If we are booting, 5635 // this will all be done once the scan is complete. 5636 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5637 } 5638 } 5639 } 5640 } 5641 5642 // We also need to dexopt any apps that are dependent on this library. Note that 5643 // if these fail, we should abort the install since installing the library will 5644 // result in some apps being broken. 5645 if (clientLibPkgs != null) { 5646 if ((scanMode&SCAN_NO_DEX) == 0) { 5647 for (int i=0; i<clientLibPkgs.size(); i++) { 5648 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5649 if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5650 == DEX_OPT_FAILED) { 5651 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5652 removeDataDirsLI(pkg.packageName); 5653 } 5654 5655 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5656 "scanPackageLI failed to dexopt clientLibPkgs"); 5657 } 5658 } 5659 } 5660 } 5661 5662 // Request the ActivityManager to kill the process(only for existing packages) 5663 // so that we do not end up in a confused state while the user is still using the older 5664 // version of the application while the new one gets installed. 5665 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5666 // If the package lives in an asec, tell everyone that the container is going 5667 // away so they can clean up any references to its resources (which would prevent 5668 // vold from being able to unmount the asec) 5669 if (isForwardLocked(pkg) || isExternal(pkg)) { 5670 if (DEBUG_INSTALL) { 5671 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5672 } 5673 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5674 final ArrayList<String> pkgList = new ArrayList<String>(1); 5675 pkgList.add(pkg.applicationInfo.packageName); 5676 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5677 } 5678 5679 // Post the request that it be killed now that the going-away broadcast is en route 5680 killApplication(pkg.applicationInfo.packageName, 5681 pkg.applicationInfo.uid, "update pkg"); 5682 } 5683 5684 // Also need to kill any apps that are dependent on the library. 5685 if (clientLibPkgs != null) { 5686 for (int i=0; i<clientLibPkgs.size(); i++) { 5687 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5688 killApplication(clientPkg.applicationInfo.packageName, 5689 clientPkg.applicationInfo.uid, "update lib"); 5690 } 5691 } 5692 5693 // writer 5694 synchronized (mPackages) { 5695 // We don't expect installation to fail beyond this point, 5696 if ((scanMode&SCAN_MONITOR) != 0) { 5697 mAppDirs.put(pkg.codePath, pkg); 5698 } 5699 // Add the new setting to mSettings 5700 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5701 // Add the new setting to mPackages 5702 mPackages.put(pkg.applicationInfo.packageName, pkg); 5703 // Make sure we don't accidentally delete its data. 5704 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5705 while (iter.hasNext()) { 5706 PackageCleanItem item = iter.next(); 5707 if (pkgName.equals(item.packageName)) { 5708 iter.remove(); 5709 } 5710 } 5711 5712 // Take care of first install / last update times. 5713 if (currentTime != 0) { 5714 if (pkgSetting.firstInstallTime == 0) { 5715 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5716 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5717 pkgSetting.lastUpdateTime = currentTime; 5718 } 5719 } else if (pkgSetting.firstInstallTime == 0) { 5720 // We need *something*. Take time time stamp of the file. 5721 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5722 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5723 if (scanFileTime != pkgSetting.timeStamp) { 5724 // A package on the system image has changed; consider this 5725 // to be an update. 5726 pkgSetting.lastUpdateTime = scanFileTime; 5727 } 5728 } 5729 5730 // Add the package's KeySets to the global KeySetManagerService 5731 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5732 try { 5733 // Old KeySetData no longer valid. 5734 ksms.removeAppKeySetDataLPw(pkg.packageName); 5735 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5736 if (pkg.mKeySetMapping != null) { 5737 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5738 pkg.mKeySetMapping.entrySet()) { 5739 if (entry.getValue() != null) { 5740 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5741 entry.getValue(), entry.getKey()); 5742 } 5743 } 5744 if (pkg.mUpgradeKeySets != null) { 5745 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5746 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5747 } 5748 } 5749 } 5750 } catch (NullPointerException e) { 5751 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5752 } catch (IllegalArgumentException e) { 5753 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5754 } 5755 5756 int N = pkg.providers.size(); 5757 StringBuilder r = null; 5758 int i; 5759 for (i=0; i<N; i++) { 5760 PackageParser.Provider p = pkg.providers.get(i); 5761 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5762 p.info.processName, pkg.applicationInfo.uid); 5763 mProviders.addProvider(p); 5764 p.syncable = p.info.isSyncable; 5765 if (p.info.authority != null) { 5766 String names[] = p.info.authority.split(";"); 5767 p.info.authority = null; 5768 for (int j = 0; j < names.length; j++) { 5769 if (j == 1 && p.syncable) { 5770 // We only want the first authority for a provider to possibly be 5771 // syncable, so if we already added this provider using a different 5772 // authority clear the syncable flag. We copy the provider before 5773 // changing it because the mProviders object contains a reference 5774 // to a provider that we don't want to change. 5775 // Only do this for the second authority since the resulting provider 5776 // object can be the same for all future authorities for this provider. 5777 p = new PackageParser.Provider(p); 5778 p.syncable = false; 5779 } 5780 if (!mProvidersByAuthority.containsKey(names[j])) { 5781 mProvidersByAuthority.put(names[j], p); 5782 if (p.info.authority == null) { 5783 p.info.authority = names[j]; 5784 } else { 5785 p.info.authority = p.info.authority + ";" + names[j]; 5786 } 5787 if (DEBUG_PACKAGE_SCANNING) { 5788 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5789 Log.d(TAG, "Registered content provider: " + names[j] 5790 + ", className = " + p.info.name + ", isSyncable = " 5791 + p.info.isSyncable); 5792 } 5793 } else { 5794 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5795 Slog.w(TAG, "Skipping provider name " + names[j] + 5796 " (in package " + pkg.applicationInfo.packageName + 5797 "): name already used by " 5798 + ((other != null && other.getComponentName() != null) 5799 ? other.getComponentName().getPackageName() : "?")); 5800 } 5801 } 5802 } 5803 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5804 if (r == null) { 5805 r = new StringBuilder(256); 5806 } else { 5807 r.append(' '); 5808 } 5809 r.append(p.info.name); 5810 } 5811 } 5812 if (r != null) { 5813 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5814 } 5815 5816 N = pkg.services.size(); 5817 r = null; 5818 for (i=0; i<N; i++) { 5819 PackageParser.Service s = pkg.services.get(i); 5820 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5821 s.info.processName, pkg.applicationInfo.uid); 5822 mServices.addService(s); 5823 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5824 if (r == null) { 5825 r = new StringBuilder(256); 5826 } else { 5827 r.append(' '); 5828 } 5829 r.append(s.info.name); 5830 } 5831 } 5832 if (r != null) { 5833 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5834 } 5835 5836 N = pkg.receivers.size(); 5837 r = null; 5838 for (i=0; i<N; i++) { 5839 PackageParser.Activity a = pkg.receivers.get(i); 5840 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5841 a.info.processName, pkg.applicationInfo.uid); 5842 mReceivers.addActivity(a, "receiver"); 5843 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5844 if (r == null) { 5845 r = new StringBuilder(256); 5846 } else { 5847 r.append(' '); 5848 } 5849 r.append(a.info.name); 5850 } 5851 } 5852 if (r != null) { 5853 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5854 } 5855 5856 N = pkg.activities.size(); 5857 r = null; 5858 for (i=0; i<N; i++) { 5859 PackageParser.Activity a = pkg.activities.get(i); 5860 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5861 a.info.processName, pkg.applicationInfo.uid); 5862 mActivities.addActivity(a, "activity"); 5863 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5864 if (r == null) { 5865 r = new StringBuilder(256); 5866 } else { 5867 r.append(' '); 5868 } 5869 r.append(a.info.name); 5870 } 5871 } 5872 if (r != null) { 5873 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5874 } 5875 5876 N = pkg.permissionGroups.size(); 5877 r = null; 5878 for (i=0; i<N; i++) { 5879 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5880 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5881 if (cur == null) { 5882 mPermissionGroups.put(pg.info.name, pg); 5883 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5884 if (r == null) { 5885 r = new StringBuilder(256); 5886 } else { 5887 r.append(' '); 5888 } 5889 r.append(pg.info.name); 5890 } 5891 } else { 5892 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5893 + pg.info.packageName + " ignored: original from " 5894 + cur.info.packageName); 5895 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5896 if (r == null) { 5897 r = new StringBuilder(256); 5898 } else { 5899 r.append(' '); 5900 } 5901 r.append("DUP:"); 5902 r.append(pg.info.name); 5903 } 5904 } 5905 } 5906 if (r != null) { 5907 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5908 } 5909 5910 N = pkg.permissions.size(); 5911 r = null; 5912 for (i=0; i<N; i++) { 5913 PackageParser.Permission p = pkg.permissions.get(i); 5914 HashMap<String, BasePermission> permissionMap = 5915 p.tree ? mSettings.mPermissionTrees 5916 : mSettings.mPermissions; 5917 p.group = mPermissionGroups.get(p.info.group); 5918 if (p.info.group == null || p.group != null) { 5919 BasePermission bp = permissionMap.get(p.info.name); 5920 if (bp == null) { 5921 bp = new BasePermission(p.info.name, p.info.packageName, 5922 BasePermission.TYPE_NORMAL); 5923 permissionMap.put(p.info.name, bp); 5924 } 5925 if (bp.perm == null) { 5926 if (bp.sourcePackage != null 5927 && !bp.sourcePackage.equals(p.info.packageName)) { 5928 // If this is a permission that was formerly defined by a non-system 5929 // app, but is now defined by a system app (following an upgrade), 5930 // discard the previous declaration and consider the system's to be 5931 // canonical. 5932 if (isSystemApp(p.owner)) { 5933 String msg = "New decl " + p.owner + " of permission " 5934 + p.info.name + " is system"; 5935 reportSettingsProblem(Log.WARN, msg); 5936 bp.sourcePackage = null; 5937 } 5938 } 5939 if (bp.sourcePackage == null 5940 || bp.sourcePackage.equals(p.info.packageName)) { 5941 BasePermission tree = findPermissionTreeLP(p.info.name); 5942 if (tree == null 5943 || tree.sourcePackage.equals(p.info.packageName)) { 5944 bp.packageSetting = pkgSetting; 5945 bp.perm = p; 5946 bp.uid = pkg.applicationInfo.uid; 5947 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5948 if (r == null) { 5949 r = new StringBuilder(256); 5950 } else { 5951 r.append(' '); 5952 } 5953 r.append(p.info.name); 5954 } 5955 } else { 5956 Slog.w(TAG, "Permission " + p.info.name + " from package " 5957 + p.info.packageName + " ignored: base tree " 5958 + tree.name + " is from package " 5959 + tree.sourcePackage); 5960 } 5961 } else { 5962 Slog.w(TAG, "Permission " + p.info.name + " from package " 5963 + p.info.packageName + " ignored: original from " 5964 + bp.sourcePackage); 5965 } 5966 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5967 if (r == null) { 5968 r = new StringBuilder(256); 5969 } else { 5970 r.append(' '); 5971 } 5972 r.append("DUP:"); 5973 r.append(p.info.name); 5974 } 5975 if (bp.perm == p) { 5976 bp.protectionLevel = p.info.protectionLevel; 5977 } 5978 } else { 5979 Slog.w(TAG, "Permission " + p.info.name + " from package " 5980 + p.info.packageName + " ignored: no group " 5981 + p.group); 5982 } 5983 } 5984 if (r != null) { 5985 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 5986 } 5987 5988 N = pkg.instrumentation.size(); 5989 r = null; 5990 for (i=0; i<N; i++) { 5991 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5992 a.info.packageName = pkg.applicationInfo.packageName; 5993 a.info.sourceDir = pkg.applicationInfo.sourceDir; 5994 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 5995 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 5996 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 5997 a.info.dataDir = pkg.applicationInfo.dataDir; 5998 5999 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6000 // need other information about the application, like the ABI and what not ? 6001 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6002 mInstrumentation.put(a.getComponentName(), a); 6003 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6004 if (r == null) { 6005 r = new StringBuilder(256); 6006 } else { 6007 r.append(' '); 6008 } 6009 r.append(a.info.name); 6010 } 6011 } 6012 if (r != null) { 6013 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6014 } 6015 6016 if (pkg.protectedBroadcasts != null) { 6017 N = pkg.protectedBroadcasts.size(); 6018 for (i=0; i<N; i++) { 6019 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6020 } 6021 } 6022 6023 pkgSetting.setTimeStamp(scanFileTime); 6024 6025 // Create idmap files for pairs of (packages, overlay packages). 6026 // Note: "android", ie framework-res.apk, is handled by native layers. 6027 if (pkg.mOverlayTarget != null) { 6028 // This is an overlay package. 6029 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6030 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6031 mOverlays.put(pkg.mOverlayTarget, 6032 new HashMap<String, PackageParser.Package>()); 6033 } 6034 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6035 map.put(pkg.packageName, pkg); 6036 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6037 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6038 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6039 "scanPackageLI failed to createIdmap"); 6040 } 6041 } 6042 } else if (mOverlays.containsKey(pkg.packageName) && 6043 !pkg.packageName.equals("android")) { 6044 // This is a regular package, with one or more known overlay packages. 6045 createIdmapsForPackageLI(pkg); 6046 } 6047 } 6048 6049 return pkg; 6050 } 6051 6052 /** 6053 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6054 * i.e, so that all packages can be run inside a single process if required. 6055 * 6056 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6057 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6058 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6059 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6060 * updating a package that belongs to a shared user. 6061 * 6062 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6063 * adds unnecessary complexity. 6064 */ 6065 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6066 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6067 String requiredInstructionSet = null; 6068 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6069 requiredInstructionSet = VMRuntime.getInstructionSet( 6070 scannedPackage.applicationInfo.primaryCpuAbi); 6071 } 6072 6073 PackageSetting requirer = null; 6074 for (PackageSetting ps : packagesForUser) { 6075 // If packagesForUser contains scannedPackage, we skip it. This will happen 6076 // when scannedPackage is an update of an existing package. Without this check, 6077 // we will never be able to change the ABI of any package belonging to a shared 6078 // user, even if it's compatible with other packages. 6079 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6080 if (ps.primaryCpuAbiString == null) { 6081 continue; 6082 } 6083 6084 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6085 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6086 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6087 // this but there's not much we can do. 6088 String errorMessage = "Instruction set mismatch, " 6089 + ((requirer == null) ? "[caller]" : requirer) 6090 + " requires " + requiredInstructionSet + " whereas " + ps 6091 + " requires " + instructionSet; 6092 Slog.w(TAG, errorMessage); 6093 } 6094 6095 if (requiredInstructionSet == null) { 6096 requiredInstructionSet = instructionSet; 6097 requirer = ps; 6098 } 6099 } 6100 } 6101 6102 if (requiredInstructionSet != null) { 6103 String adjustedAbi; 6104 if (requirer != null) { 6105 // requirer != null implies that either scannedPackage was null or that scannedPackage 6106 // did not require an ABI, in which case we have to adjust scannedPackage to match 6107 // the ABI of the set (which is the same as requirer's ABI) 6108 adjustedAbi = requirer.primaryCpuAbiString; 6109 if (scannedPackage != null) { 6110 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6111 } 6112 } else { 6113 // requirer == null implies that we're updating all ABIs in the set to 6114 // match scannedPackage. 6115 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6116 } 6117 6118 for (PackageSetting ps : packagesForUser) { 6119 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6120 if (ps.primaryCpuAbiString != null) { 6121 continue; 6122 } 6123 6124 ps.primaryCpuAbiString = adjustedAbi; 6125 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6126 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6127 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6128 6129 if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) { 6130 ps.primaryCpuAbiString = null; 6131 ps.pkg.applicationInfo.primaryCpuAbi = null; 6132 return; 6133 } else { 6134 mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet()); 6135 } 6136 } 6137 } 6138 } 6139 } 6140 } 6141 6142 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6143 synchronized (mPackages) { 6144 mResolverReplaced = true; 6145 // Set up information for custom user intent resolution activity. 6146 mResolveActivity.applicationInfo = pkg.applicationInfo; 6147 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6148 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6149 mResolveActivity.processName = null; 6150 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6151 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6152 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6153 mResolveActivity.theme = 0; 6154 mResolveActivity.exported = true; 6155 mResolveActivity.enabled = true; 6156 mResolveInfo.activityInfo = mResolveActivity; 6157 mResolveInfo.priority = 0; 6158 mResolveInfo.preferredOrder = 0; 6159 mResolveInfo.match = 0; 6160 mResolveComponentName = mCustomResolverComponentName; 6161 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6162 mResolveComponentName); 6163 } 6164 } 6165 6166 private static String calculateApkRoot(final String codePathString) { 6167 final File codePath = new File(codePathString); 6168 final File codeRoot; 6169 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6170 codeRoot = Environment.getRootDirectory(); 6171 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6172 codeRoot = Environment.getOemDirectory(); 6173 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6174 codeRoot = Environment.getVendorDirectory(); 6175 } else { 6176 // Unrecognized code path; take its top real segment as the apk root: 6177 // e.g. /something/app/blah.apk => /something 6178 try { 6179 File f = codePath.getCanonicalFile(); 6180 File parent = f.getParentFile(); // non-null because codePath is a file 6181 File tmp; 6182 while ((tmp = parent.getParentFile()) != null) { 6183 f = parent; 6184 parent = tmp; 6185 } 6186 codeRoot = f; 6187 Slog.w(TAG, "Unrecognized code path " 6188 + codePath + " - using " + codeRoot); 6189 } catch (IOException e) { 6190 // Can't canonicalize the code path -- shenanigans? 6191 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6192 return Environment.getRootDirectory().getPath(); 6193 } 6194 } 6195 return codeRoot.getPath(); 6196 } 6197 6198 /** 6199 * Derive and set the location of native libraries for the given package, 6200 * which varies depending on where and how the package was installed. 6201 */ 6202 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6203 final ApplicationInfo info = pkg.applicationInfo; 6204 final String codePath = pkg.codePath; 6205 final File codeFile = new File(codePath); 6206 6207 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6208 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6209 6210 info.nativeLibraryRootDir = null; 6211 info.nativeLibraryRootRequiresIsa = false; 6212 info.nativeLibraryDir = null; 6213 6214 if (bundledApp) { 6215 // Monolithic bundled install 6216 // TODO: support cluster bundled installs? 6217 6218 final boolean is64Bit = (info.primaryCpuAbi != null) 6219 && VMRuntime.is64BitAbi(info.primaryCpuAbi); 6220 6221 // This is a bundled system app so choose the path based on the ABI. 6222 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6223 // is just the default path. 6224 final String apkName = deriveCodePathName(codePath); 6225 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6226 info.nativeLibraryRootDir = Environment.buildPath(new File(info.apkRoot), libDir, 6227 apkName).getAbsolutePath(); 6228 info.nativeLibraryRootRequiresIsa = false; 6229 6230 } else if (isApkFile(codeFile)) { 6231 // Monolithic install 6232 if (asecApp) { 6233 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6234 .getAbsolutePath(); 6235 info.nativeLibraryRootRequiresIsa = false; 6236 } else { 6237 final String apkName = deriveCodePathName(codePath); 6238 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6239 .getAbsolutePath(); 6240 info.nativeLibraryRootRequiresIsa = false; 6241 } 6242 } else { 6243 // Cluster install 6244 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6245 info.nativeLibraryRootRequiresIsa = true; 6246 } 6247 6248 if (info.nativeLibraryRootRequiresIsa) { 6249 if (info.primaryCpuAbi != null) { 6250 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6251 VMRuntime.getInstructionSet(info.primaryCpuAbi)).getAbsolutePath(); 6252 } 6253 } else { 6254 info.nativeLibraryDir = info.nativeLibraryRootDir; 6255 } 6256 } 6257 6258 /** 6259 * Calculate the abis and roots for a bundled app. These can uniquely 6260 * be determined from the contents of the system partition, i.e whether 6261 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6262 * of this information, and instead assume that the system was built 6263 * sensibly. 6264 */ 6265 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6266 PackageSetting pkgSetting) { 6267 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6268 6269 // If "/system/lib64/apkname" exists, assume that is the per-package 6270 // native library directory to use; otherwise use "/system/lib/apkname". 6271 final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6272 pkg.applicationInfo.apkRoot = apkRoot; 6273 setBundledAppAbi(pkg, apkRoot, apkName); 6274 // pkgSetting might be null during rescan following uninstall of updates 6275 // to a bundled app, so accommodate that possibility. The settings in 6276 // that case will be established later from the parsed package. 6277 // 6278 // If the settings aren't null, sync them up with what we've just derived. 6279 // note that apkRoot isn't stored in the package settings. 6280 if (pkgSetting != null) { 6281 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6282 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6283 } 6284 } 6285 6286 /** 6287 * Deduces the ABI of a bundled app and sets the relevant fields on the 6288 * parsed pkg object. 6289 * 6290 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6291 * under which system libraries are installed. 6292 * @param apkName the name of the installed package. 6293 */ 6294 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6295 // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>" 6296 // or similar. 6297 final boolean has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6298 final boolean has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6299 6300 if (has64BitLibs && !has32BitLibs) { 6301 // The package has 64 bit libs, but not 32 bit libs. Its primary 6302 // ABI should be 64 bit. We can safely assume here that the bundled 6303 // native libraries correspond to the most preferred ABI in the list. 6304 6305 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6306 pkg.applicationInfo.secondaryCpuAbi = null; 6307 } else if (has32BitLibs && !has64BitLibs) { 6308 // The package has 32 bit libs but not 64 bit libs. Its primary 6309 // ABI should be 32 bit. 6310 6311 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6312 pkg.applicationInfo.secondaryCpuAbi = null; 6313 } else if (has32BitLibs && has64BitLibs) { 6314 // The application has both 64 and 32 bit bundled libraries. We check 6315 // here that the app declares multiArch support, and warn if it doesn't. 6316 // 6317 // We will be lenient here and record both ABIs. The primary will be the 6318 // ABI that's higher on the list, i.e, a device that's configured to prefer 6319 // 64 bit apps will see a 64 bit primary ABI, 6320 6321 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6322 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6323 } 6324 6325 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6326 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6327 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6328 } else { 6329 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6330 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6331 } 6332 } else { 6333 pkg.applicationInfo.primaryCpuAbi = null; 6334 pkg.applicationInfo.secondaryCpuAbi = null; 6335 } 6336 } 6337 6338 private static void createNativeLibrarySubdir(File path) throws IOException { 6339 if (!path.isDirectory()) { 6340 path.delete(); 6341 6342 if (!path.mkdir()) { 6343 throw new IOException("Cannot create " + path.getPath()); 6344 } 6345 6346 try { 6347 Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6348 } catch (ErrnoException e) { 6349 throw new IOException("Cannot chmod native library directory " 6350 + path.getPath(), e); 6351 } 6352 } else if (!SELinux.restorecon(path)) { 6353 throw new IOException("Cannot set SELinux context for " + path.getPath()); 6354 } 6355 } 6356 6357 private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle, 6358 final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException { 6359 createNativeLibrarySubdir(nativeLibraryRoot); 6360 6361 /* 6362 * If this is an internal application or our nativeLibraryPath points to 6363 * the app-lib directory, unpack the libraries if necessary. 6364 */ 6365 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6366 if (abi >= 0) { 6367 /* 6368 * If we have a matching instruction set, construct a subdir under the native 6369 * library root that corresponds to this instruction set. 6370 */ 6371 final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]); 6372 final File subDir; 6373 if (useIsaSubdir) { 6374 final File isaSubdir = new File(nativeLibraryRoot, instructionSet); 6375 createNativeLibrarySubdir(isaSubdir); 6376 subDir = isaSubdir; 6377 } else { 6378 subDir = nativeLibraryRoot; 6379 } 6380 6381 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, subDir, abiList[abi]); 6382 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6383 return copyRet; 6384 } 6385 } 6386 6387 return abi; 6388 } 6389 6390 private void killApplication(String pkgName, int appId, String reason) { 6391 // Request the ActivityManager to kill the process(only for existing packages) 6392 // so that we do not end up in a confused state while the user is still using the older 6393 // version of the application while the new one gets installed. 6394 IActivityManager am = ActivityManagerNative.getDefault(); 6395 if (am != null) { 6396 try { 6397 am.killApplicationWithAppId(pkgName, appId, reason); 6398 } catch (RemoteException e) { 6399 } 6400 } 6401 } 6402 6403 void removePackageLI(PackageSetting ps, boolean chatty) { 6404 if (DEBUG_INSTALL) { 6405 if (chatty) 6406 Log.d(TAG, "Removing package " + ps.name); 6407 } 6408 6409 // writer 6410 synchronized (mPackages) { 6411 mPackages.remove(ps.name); 6412 if (ps.codePathString != null) { 6413 mAppDirs.remove(ps.codePathString); 6414 } 6415 6416 final PackageParser.Package pkg = ps.pkg; 6417 if (pkg != null) { 6418 cleanPackageDataStructuresLILPw(pkg, chatty); 6419 } 6420 } 6421 } 6422 6423 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6424 if (DEBUG_INSTALL) { 6425 if (chatty) 6426 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6427 } 6428 6429 // writer 6430 synchronized (mPackages) { 6431 mPackages.remove(pkg.applicationInfo.packageName); 6432 if (pkg.codePath != null) { 6433 mAppDirs.remove(pkg.codePath); 6434 } 6435 cleanPackageDataStructuresLILPw(pkg, chatty); 6436 } 6437 } 6438 6439 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6440 int N = pkg.providers.size(); 6441 StringBuilder r = null; 6442 int i; 6443 for (i=0; i<N; i++) { 6444 PackageParser.Provider p = pkg.providers.get(i); 6445 mProviders.removeProvider(p); 6446 if (p.info.authority == null) { 6447 6448 /* There was another ContentProvider with this authority when 6449 * this app was installed so this authority is null, 6450 * Ignore it as we don't have to unregister the provider. 6451 */ 6452 continue; 6453 } 6454 String names[] = p.info.authority.split(";"); 6455 for (int j = 0; j < names.length; j++) { 6456 if (mProvidersByAuthority.get(names[j]) == p) { 6457 mProvidersByAuthority.remove(names[j]); 6458 if (DEBUG_REMOVE) { 6459 if (chatty) 6460 Log.d(TAG, "Unregistered content provider: " + names[j] 6461 + ", className = " + p.info.name + ", isSyncable = " 6462 + p.info.isSyncable); 6463 } 6464 } 6465 } 6466 if (DEBUG_REMOVE && chatty) { 6467 if (r == null) { 6468 r = new StringBuilder(256); 6469 } else { 6470 r.append(' '); 6471 } 6472 r.append(p.info.name); 6473 } 6474 } 6475 if (r != null) { 6476 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6477 } 6478 6479 N = pkg.services.size(); 6480 r = null; 6481 for (i=0; i<N; i++) { 6482 PackageParser.Service s = pkg.services.get(i); 6483 mServices.removeService(s); 6484 if (chatty) { 6485 if (r == null) { 6486 r = new StringBuilder(256); 6487 } else { 6488 r.append(' '); 6489 } 6490 r.append(s.info.name); 6491 } 6492 } 6493 if (r != null) { 6494 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6495 } 6496 6497 N = pkg.receivers.size(); 6498 r = null; 6499 for (i=0; i<N; i++) { 6500 PackageParser.Activity a = pkg.receivers.get(i); 6501 mReceivers.removeActivity(a, "receiver"); 6502 if (DEBUG_REMOVE && chatty) { 6503 if (r == null) { 6504 r = new StringBuilder(256); 6505 } else { 6506 r.append(' '); 6507 } 6508 r.append(a.info.name); 6509 } 6510 } 6511 if (r != null) { 6512 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6513 } 6514 6515 N = pkg.activities.size(); 6516 r = null; 6517 for (i=0; i<N; i++) { 6518 PackageParser.Activity a = pkg.activities.get(i); 6519 mActivities.removeActivity(a, "activity"); 6520 if (DEBUG_REMOVE && chatty) { 6521 if (r == null) { 6522 r = new StringBuilder(256); 6523 } else { 6524 r.append(' '); 6525 } 6526 r.append(a.info.name); 6527 } 6528 } 6529 if (r != null) { 6530 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6531 } 6532 6533 N = pkg.permissions.size(); 6534 r = null; 6535 for (i=0; i<N; i++) { 6536 PackageParser.Permission p = pkg.permissions.get(i); 6537 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6538 if (bp == null) { 6539 bp = mSettings.mPermissionTrees.get(p.info.name); 6540 } 6541 if (bp != null && bp.perm == p) { 6542 bp.perm = null; 6543 if (DEBUG_REMOVE && chatty) { 6544 if (r == null) { 6545 r = new StringBuilder(256); 6546 } else { 6547 r.append(' '); 6548 } 6549 r.append(p.info.name); 6550 } 6551 } 6552 } 6553 if (r != null) { 6554 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6555 } 6556 6557 N = pkg.instrumentation.size(); 6558 r = null; 6559 for (i=0; i<N; i++) { 6560 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6561 mInstrumentation.remove(a.getComponentName()); 6562 if (DEBUG_REMOVE && chatty) { 6563 if (r == null) { 6564 r = new StringBuilder(256); 6565 } else { 6566 r.append(' '); 6567 } 6568 r.append(a.info.name); 6569 } 6570 } 6571 if (r != null) { 6572 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6573 } 6574 6575 r = null; 6576 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6577 // Only system apps can hold shared libraries. 6578 if (pkg.libraryNames != null) { 6579 for (i=0; i<pkg.libraryNames.size(); i++) { 6580 String name = pkg.libraryNames.get(i); 6581 SharedLibraryEntry cur = mSharedLibraries.get(name); 6582 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6583 mSharedLibraries.remove(name); 6584 if (DEBUG_REMOVE && chatty) { 6585 if (r == null) { 6586 r = new StringBuilder(256); 6587 } else { 6588 r.append(' '); 6589 } 6590 r.append(name); 6591 } 6592 } 6593 } 6594 } 6595 } 6596 if (r != null) { 6597 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6598 } 6599 } 6600 6601 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6602 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6603 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6604 return true; 6605 } 6606 } 6607 return false; 6608 } 6609 6610 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6611 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6612 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6613 6614 private void updatePermissionsLPw(String changingPkg, 6615 PackageParser.Package pkgInfo, int flags) { 6616 // Make sure there are no dangling permission trees. 6617 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6618 while (it.hasNext()) { 6619 final BasePermission bp = it.next(); 6620 if (bp.packageSetting == null) { 6621 // We may not yet have parsed the package, so just see if 6622 // we still know about its settings. 6623 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6624 } 6625 if (bp.packageSetting == null) { 6626 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6627 + " from package " + bp.sourcePackage); 6628 it.remove(); 6629 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6630 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6631 Slog.i(TAG, "Removing old permission tree: " + bp.name 6632 + " from package " + bp.sourcePackage); 6633 flags |= UPDATE_PERMISSIONS_ALL; 6634 it.remove(); 6635 } 6636 } 6637 } 6638 6639 // Make sure all dynamic permissions have been assigned to a package, 6640 // and make sure there are no dangling permissions. 6641 it = mSettings.mPermissions.values().iterator(); 6642 while (it.hasNext()) { 6643 final BasePermission bp = it.next(); 6644 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6645 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6646 + bp.name + " pkg=" + bp.sourcePackage 6647 + " info=" + bp.pendingInfo); 6648 if (bp.packageSetting == null && bp.pendingInfo != null) { 6649 final BasePermission tree = findPermissionTreeLP(bp.name); 6650 if (tree != null && tree.perm != null) { 6651 bp.packageSetting = tree.packageSetting; 6652 bp.perm = new PackageParser.Permission(tree.perm.owner, 6653 new PermissionInfo(bp.pendingInfo)); 6654 bp.perm.info.packageName = tree.perm.info.packageName; 6655 bp.perm.info.name = bp.name; 6656 bp.uid = tree.uid; 6657 } 6658 } 6659 } 6660 if (bp.packageSetting == null) { 6661 // We may not yet have parsed the package, so just see if 6662 // we still know about its settings. 6663 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6664 } 6665 if (bp.packageSetting == null) { 6666 Slog.w(TAG, "Removing dangling permission: " + bp.name 6667 + " from package " + bp.sourcePackage); 6668 it.remove(); 6669 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6670 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6671 Slog.i(TAG, "Removing old permission: " + bp.name 6672 + " from package " + bp.sourcePackage); 6673 flags |= UPDATE_PERMISSIONS_ALL; 6674 it.remove(); 6675 } 6676 } 6677 } 6678 6679 // Now update the permissions for all packages, in particular 6680 // replace the granted permissions of the system packages. 6681 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6682 for (PackageParser.Package pkg : mPackages.values()) { 6683 if (pkg != pkgInfo) { 6684 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6685 } 6686 } 6687 } 6688 6689 if (pkgInfo != null) { 6690 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6691 } 6692 } 6693 6694 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6695 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6696 if (ps == null) { 6697 return; 6698 } 6699 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6700 HashSet<String> origPermissions = gp.grantedPermissions; 6701 boolean changedPermission = false; 6702 6703 if (replace) { 6704 ps.permissionsFixed = false; 6705 if (gp == ps) { 6706 origPermissions = new HashSet<String>(gp.grantedPermissions); 6707 gp.grantedPermissions.clear(); 6708 gp.gids = mGlobalGids; 6709 } 6710 } 6711 6712 if (gp.gids == null) { 6713 gp.gids = mGlobalGids; 6714 } 6715 6716 final int N = pkg.requestedPermissions.size(); 6717 for (int i=0; i<N; i++) { 6718 final String name = pkg.requestedPermissions.get(i); 6719 final boolean required = pkg.requestedPermissionsRequired.get(i); 6720 final BasePermission bp = mSettings.mPermissions.get(name); 6721 if (DEBUG_INSTALL) { 6722 if (gp != ps) { 6723 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6724 } 6725 } 6726 6727 if (bp == null || bp.packageSetting == null) { 6728 Slog.w(TAG, "Unknown permission " + name 6729 + " in package " + pkg.packageName); 6730 continue; 6731 } 6732 6733 final String perm = bp.name; 6734 boolean allowed; 6735 boolean allowedSig = false; 6736 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6737 if (level == PermissionInfo.PROTECTION_NORMAL 6738 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6739 // We grant a normal or dangerous permission if any of the following 6740 // are true: 6741 // 1) The permission is required 6742 // 2) The permission is optional, but was granted in the past 6743 // 3) The permission is optional, but was requested by an 6744 // app in /system (not /data) 6745 // 6746 // Otherwise, reject the permission. 6747 allowed = (required || origPermissions.contains(perm) 6748 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6749 } else if (bp.packageSetting == null) { 6750 // This permission is invalid; skip it. 6751 allowed = false; 6752 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6753 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6754 if (allowed) { 6755 allowedSig = true; 6756 } 6757 } else { 6758 allowed = false; 6759 } 6760 if (DEBUG_INSTALL) { 6761 if (gp != ps) { 6762 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6763 } 6764 } 6765 if (allowed) { 6766 if (!isSystemApp(ps) && ps.permissionsFixed) { 6767 // If this is an existing, non-system package, then 6768 // we can't add any new permissions to it. 6769 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6770 // Except... if this is a permission that was added 6771 // to the platform (note: need to only do this when 6772 // updating the platform). 6773 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6774 } 6775 } 6776 if (allowed) { 6777 if (!gp.grantedPermissions.contains(perm)) { 6778 changedPermission = true; 6779 gp.grantedPermissions.add(perm); 6780 gp.gids = appendInts(gp.gids, bp.gids); 6781 } else if (!ps.haveGids) { 6782 gp.gids = appendInts(gp.gids, bp.gids); 6783 } 6784 } else { 6785 Slog.w(TAG, "Not granting permission " + perm 6786 + " to package " + pkg.packageName 6787 + " because it was previously installed without"); 6788 } 6789 } else { 6790 if (gp.grantedPermissions.remove(perm)) { 6791 changedPermission = true; 6792 gp.gids = removeInts(gp.gids, bp.gids); 6793 Slog.i(TAG, "Un-granting permission " + perm 6794 + " from package " + pkg.packageName 6795 + " (protectionLevel=" + bp.protectionLevel 6796 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6797 + ")"); 6798 } else { 6799 Slog.w(TAG, "Not granting permission " + perm 6800 + " to package " + pkg.packageName 6801 + " (protectionLevel=" + bp.protectionLevel 6802 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6803 + ")"); 6804 } 6805 } 6806 } 6807 6808 if ((changedPermission || replace) && !ps.permissionsFixed && 6809 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6810 // This is the first that we have heard about this package, so the 6811 // permissions we have now selected are fixed until explicitly 6812 // changed. 6813 ps.permissionsFixed = true; 6814 } 6815 ps.haveGids = true; 6816 } 6817 6818 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6819 boolean allowed = false; 6820 final int NP = PackageParser.NEW_PERMISSIONS.length; 6821 for (int ip=0; ip<NP; ip++) { 6822 final PackageParser.NewPermissionInfo npi 6823 = PackageParser.NEW_PERMISSIONS[ip]; 6824 if (npi.name.equals(perm) 6825 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6826 allowed = true; 6827 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6828 + pkg.packageName); 6829 break; 6830 } 6831 } 6832 return allowed; 6833 } 6834 6835 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6836 BasePermission bp, HashSet<String> origPermissions) { 6837 boolean allowed; 6838 allowed = (compareSignatures( 6839 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6840 == PackageManager.SIGNATURE_MATCH) 6841 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6842 == PackageManager.SIGNATURE_MATCH); 6843 if (!allowed && (bp.protectionLevel 6844 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6845 if (isSystemApp(pkg)) { 6846 // For updated system applications, a system permission 6847 // is granted only if it had been defined by the original application. 6848 if (isUpdatedSystemApp(pkg)) { 6849 final PackageSetting sysPs = mSettings 6850 .getDisabledSystemPkgLPr(pkg.packageName); 6851 final GrantedPermissions origGp = sysPs.sharedUser != null 6852 ? sysPs.sharedUser : sysPs; 6853 6854 if (origGp.grantedPermissions.contains(perm)) { 6855 // If the original was granted this permission, we take 6856 // that grant decision as read and propagate it to the 6857 // update. 6858 allowed = true; 6859 } else { 6860 // The system apk may have been updated with an older 6861 // version of the one on the data partition, but which 6862 // granted a new system permission that it didn't have 6863 // before. In this case we do want to allow the app to 6864 // now get the new permission if the ancestral apk is 6865 // privileged to get it. 6866 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6867 for (int j=0; 6868 j<sysPs.pkg.requestedPermissions.size(); j++) { 6869 if (perm.equals( 6870 sysPs.pkg.requestedPermissions.get(j))) { 6871 allowed = true; 6872 break; 6873 } 6874 } 6875 } 6876 } 6877 } else { 6878 allowed = isPrivilegedApp(pkg); 6879 } 6880 } 6881 } 6882 if (!allowed && (bp.protectionLevel 6883 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6884 // For development permissions, a development permission 6885 // is granted only if it was already granted. 6886 allowed = origPermissions.contains(perm); 6887 } 6888 return allowed; 6889 } 6890 6891 final class ActivityIntentResolver 6892 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6893 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6894 boolean defaultOnly, int userId) { 6895 if (!sUserManager.exists(userId)) return null; 6896 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6897 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6898 } 6899 6900 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6901 int userId) { 6902 if (!sUserManager.exists(userId)) return null; 6903 mFlags = flags; 6904 return super.queryIntent(intent, resolvedType, 6905 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6906 } 6907 6908 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6909 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6910 if (!sUserManager.exists(userId)) return null; 6911 if (packageActivities == null) { 6912 return null; 6913 } 6914 mFlags = flags; 6915 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6916 final int N = packageActivities.size(); 6917 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6918 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6919 6920 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6921 for (int i = 0; i < N; ++i) { 6922 intentFilters = packageActivities.get(i).intents; 6923 if (intentFilters != null && intentFilters.size() > 0) { 6924 PackageParser.ActivityIntentInfo[] array = 6925 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6926 intentFilters.toArray(array); 6927 listCut.add(array); 6928 } 6929 } 6930 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6931 } 6932 6933 public final void addActivity(PackageParser.Activity a, String type) { 6934 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6935 mActivities.put(a.getComponentName(), a); 6936 if (DEBUG_SHOW_INFO) 6937 Log.v( 6938 TAG, " " + type + " " + 6939 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6940 if (DEBUG_SHOW_INFO) 6941 Log.v(TAG, " Class=" + a.info.name); 6942 final int NI = a.intents.size(); 6943 for (int j=0; j<NI; j++) { 6944 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6945 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6946 intent.setPriority(0); 6947 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6948 + a.className + " with priority > 0, forcing to 0"); 6949 } 6950 if (DEBUG_SHOW_INFO) { 6951 Log.v(TAG, " IntentFilter:"); 6952 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6953 } 6954 if (!intent.debugCheck()) { 6955 Log.w(TAG, "==> For Activity " + a.info.name); 6956 } 6957 addFilter(intent); 6958 } 6959 } 6960 6961 public final void removeActivity(PackageParser.Activity a, String type) { 6962 mActivities.remove(a.getComponentName()); 6963 if (DEBUG_SHOW_INFO) { 6964 Log.v(TAG, " " + type + " " 6965 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6966 : a.info.name) + ":"); 6967 Log.v(TAG, " Class=" + a.info.name); 6968 } 6969 final int NI = a.intents.size(); 6970 for (int j=0; j<NI; j++) { 6971 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6972 if (DEBUG_SHOW_INFO) { 6973 Log.v(TAG, " IntentFilter:"); 6974 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6975 } 6976 removeFilter(intent); 6977 } 6978 } 6979 6980 @Override 6981 protected boolean allowFilterResult( 6982 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 6983 ActivityInfo filterAi = filter.activity.info; 6984 for (int i=dest.size()-1; i>=0; i--) { 6985 ActivityInfo destAi = dest.get(i).activityInfo; 6986 if (destAi.name == filterAi.name 6987 && destAi.packageName == filterAi.packageName) { 6988 return false; 6989 } 6990 } 6991 return true; 6992 } 6993 6994 @Override 6995 protected ActivityIntentInfo[] newArray(int size) { 6996 return new ActivityIntentInfo[size]; 6997 } 6998 6999 @Override 7000 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7001 if (!sUserManager.exists(userId)) return true; 7002 PackageParser.Package p = filter.activity.owner; 7003 if (p != null) { 7004 PackageSetting ps = (PackageSetting)p.mExtras; 7005 if (ps != null) { 7006 // System apps are never considered stopped for purposes of 7007 // filtering, because there may be no way for the user to 7008 // actually re-launch them. 7009 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7010 && ps.getStopped(userId); 7011 } 7012 } 7013 return false; 7014 } 7015 7016 @Override 7017 protected boolean isPackageForFilter(String packageName, 7018 PackageParser.ActivityIntentInfo info) { 7019 return packageName.equals(info.activity.owner.packageName); 7020 } 7021 7022 @Override 7023 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7024 int match, int userId) { 7025 if (!sUserManager.exists(userId)) return null; 7026 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7027 return null; 7028 } 7029 final PackageParser.Activity activity = info.activity; 7030 if (mSafeMode && (activity.info.applicationInfo.flags 7031 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7032 return null; 7033 } 7034 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7035 if (ps == null) { 7036 return null; 7037 } 7038 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7039 ps.readUserState(userId), userId); 7040 if (ai == null) { 7041 return null; 7042 } 7043 final ResolveInfo res = new ResolveInfo(); 7044 res.activityInfo = ai; 7045 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7046 res.filter = info; 7047 } 7048 res.priority = info.getPriority(); 7049 res.preferredOrder = activity.owner.mPreferredOrder; 7050 //System.out.println("Result: " + res.activityInfo.className + 7051 // " = " + res.priority); 7052 res.match = match; 7053 res.isDefault = info.hasDefault; 7054 res.labelRes = info.labelRes; 7055 res.nonLocalizedLabel = info.nonLocalizedLabel; 7056 if (userNeedsBadging(userId)) { 7057 res.noResourceId = true; 7058 } else { 7059 res.icon = info.icon; 7060 } 7061 res.system = isSystemApp(res.activityInfo.applicationInfo); 7062 return res; 7063 } 7064 7065 @Override 7066 protected void sortResults(List<ResolveInfo> results) { 7067 Collections.sort(results, mResolvePrioritySorter); 7068 } 7069 7070 @Override 7071 protected void dumpFilter(PrintWriter out, String prefix, 7072 PackageParser.ActivityIntentInfo filter) { 7073 out.print(prefix); out.print( 7074 Integer.toHexString(System.identityHashCode(filter.activity))); 7075 out.print(' '); 7076 filter.activity.printComponentShortName(out); 7077 out.print(" filter "); 7078 out.println(Integer.toHexString(System.identityHashCode(filter))); 7079 } 7080 7081// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7082// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7083// final List<ResolveInfo> retList = Lists.newArrayList(); 7084// while (i.hasNext()) { 7085// final ResolveInfo resolveInfo = i.next(); 7086// if (isEnabledLP(resolveInfo.activityInfo)) { 7087// retList.add(resolveInfo); 7088// } 7089// } 7090// return retList; 7091// } 7092 7093 // Keys are String (activity class name), values are Activity. 7094 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7095 = new HashMap<ComponentName, PackageParser.Activity>(); 7096 private int mFlags; 7097 } 7098 7099 private final class ServiceIntentResolver 7100 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7101 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7102 boolean defaultOnly, int userId) { 7103 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7104 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7105 } 7106 7107 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7108 int userId) { 7109 if (!sUserManager.exists(userId)) return null; 7110 mFlags = flags; 7111 return super.queryIntent(intent, resolvedType, 7112 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7113 } 7114 7115 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7116 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7117 if (!sUserManager.exists(userId)) return null; 7118 if (packageServices == null) { 7119 return null; 7120 } 7121 mFlags = flags; 7122 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7123 final int N = packageServices.size(); 7124 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7125 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7126 7127 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7128 for (int i = 0; i < N; ++i) { 7129 intentFilters = packageServices.get(i).intents; 7130 if (intentFilters != null && intentFilters.size() > 0) { 7131 PackageParser.ServiceIntentInfo[] array = 7132 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7133 intentFilters.toArray(array); 7134 listCut.add(array); 7135 } 7136 } 7137 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7138 } 7139 7140 public final void addService(PackageParser.Service s) { 7141 mServices.put(s.getComponentName(), s); 7142 if (DEBUG_SHOW_INFO) { 7143 Log.v(TAG, " " 7144 + (s.info.nonLocalizedLabel != null 7145 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7146 Log.v(TAG, " Class=" + s.info.name); 7147 } 7148 final int NI = s.intents.size(); 7149 int j; 7150 for (j=0; j<NI; j++) { 7151 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7152 if (DEBUG_SHOW_INFO) { 7153 Log.v(TAG, " IntentFilter:"); 7154 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7155 } 7156 if (!intent.debugCheck()) { 7157 Log.w(TAG, "==> For Service " + s.info.name); 7158 } 7159 addFilter(intent); 7160 } 7161 } 7162 7163 public final void removeService(PackageParser.Service s) { 7164 mServices.remove(s.getComponentName()); 7165 if (DEBUG_SHOW_INFO) { 7166 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7167 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7168 Log.v(TAG, " Class=" + s.info.name); 7169 } 7170 final int NI = s.intents.size(); 7171 int j; 7172 for (j=0; j<NI; j++) { 7173 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7174 if (DEBUG_SHOW_INFO) { 7175 Log.v(TAG, " IntentFilter:"); 7176 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7177 } 7178 removeFilter(intent); 7179 } 7180 } 7181 7182 @Override 7183 protected boolean allowFilterResult( 7184 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7185 ServiceInfo filterSi = filter.service.info; 7186 for (int i=dest.size()-1; i>=0; i--) { 7187 ServiceInfo destAi = dest.get(i).serviceInfo; 7188 if (destAi.name == filterSi.name 7189 && destAi.packageName == filterSi.packageName) { 7190 return false; 7191 } 7192 } 7193 return true; 7194 } 7195 7196 @Override 7197 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7198 return new PackageParser.ServiceIntentInfo[size]; 7199 } 7200 7201 @Override 7202 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7203 if (!sUserManager.exists(userId)) return true; 7204 PackageParser.Package p = filter.service.owner; 7205 if (p != null) { 7206 PackageSetting ps = (PackageSetting)p.mExtras; 7207 if (ps != null) { 7208 // System apps are never considered stopped for purposes of 7209 // filtering, because there may be no way for the user to 7210 // actually re-launch them. 7211 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7212 && ps.getStopped(userId); 7213 } 7214 } 7215 return false; 7216 } 7217 7218 @Override 7219 protected boolean isPackageForFilter(String packageName, 7220 PackageParser.ServiceIntentInfo info) { 7221 return packageName.equals(info.service.owner.packageName); 7222 } 7223 7224 @Override 7225 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7226 int match, int userId) { 7227 if (!sUserManager.exists(userId)) return null; 7228 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7229 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7230 return null; 7231 } 7232 final PackageParser.Service service = info.service; 7233 if (mSafeMode && (service.info.applicationInfo.flags 7234 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7235 return null; 7236 } 7237 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7238 if (ps == null) { 7239 return null; 7240 } 7241 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7242 ps.readUserState(userId), userId); 7243 if (si == null) { 7244 return null; 7245 } 7246 final ResolveInfo res = new ResolveInfo(); 7247 res.serviceInfo = si; 7248 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7249 res.filter = filter; 7250 } 7251 res.priority = info.getPriority(); 7252 res.preferredOrder = service.owner.mPreferredOrder; 7253 //System.out.println("Result: " + res.activityInfo.className + 7254 // " = " + res.priority); 7255 res.match = match; 7256 res.isDefault = info.hasDefault; 7257 res.labelRes = info.labelRes; 7258 res.nonLocalizedLabel = info.nonLocalizedLabel; 7259 res.icon = info.icon; 7260 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7261 return res; 7262 } 7263 7264 @Override 7265 protected void sortResults(List<ResolveInfo> results) { 7266 Collections.sort(results, mResolvePrioritySorter); 7267 } 7268 7269 @Override 7270 protected void dumpFilter(PrintWriter out, String prefix, 7271 PackageParser.ServiceIntentInfo filter) { 7272 out.print(prefix); out.print( 7273 Integer.toHexString(System.identityHashCode(filter.service))); 7274 out.print(' '); 7275 filter.service.printComponentShortName(out); 7276 out.print(" filter "); 7277 out.println(Integer.toHexString(System.identityHashCode(filter))); 7278 } 7279 7280// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7281// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7282// final List<ResolveInfo> retList = Lists.newArrayList(); 7283// while (i.hasNext()) { 7284// final ResolveInfo resolveInfo = (ResolveInfo) i; 7285// if (isEnabledLP(resolveInfo.serviceInfo)) { 7286// retList.add(resolveInfo); 7287// } 7288// } 7289// return retList; 7290// } 7291 7292 // Keys are String (activity class name), values are Activity. 7293 private final HashMap<ComponentName, PackageParser.Service> mServices 7294 = new HashMap<ComponentName, PackageParser.Service>(); 7295 private int mFlags; 7296 }; 7297 7298 private final class ProviderIntentResolver 7299 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7300 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7301 boolean defaultOnly, int userId) { 7302 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7303 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7304 } 7305 7306 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7307 int userId) { 7308 if (!sUserManager.exists(userId)) 7309 return null; 7310 mFlags = flags; 7311 return super.queryIntent(intent, resolvedType, 7312 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7313 } 7314 7315 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7316 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7317 if (!sUserManager.exists(userId)) 7318 return null; 7319 if (packageProviders == null) { 7320 return null; 7321 } 7322 mFlags = flags; 7323 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7324 final int N = packageProviders.size(); 7325 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7326 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7327 7328 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7329 for (int i = 0; i < N; ++i) { 7330 intentFilters = packageProviders.get(i).intents; 7331 if (intentFilters != null && intentFilters.size() > 0) { 7332 PackageParser.ProviderIntentInfo[] array = 7333 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7334 intentFilters.toArray(array); 7335 listCut.add(array); 7336 } 7337 } 7338 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7339 } 7340 7341 public final void addProvider(PackageParser.Provider p) { 7342 if (mProviders.containsKey(p.getComponentName())) { 7343 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7344 return; 7345 } 7346 7347 mProviders.put(p.getComponentName(), p); 7348 if (DEBUG_SHOW_INFO) { 7349 Log.v(TAG, " " 7350 + (p.info.nonLocalizedLabel != null 7351 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7352 Log.v(TAG, " Class=" + p.info.name); 7353 } 7354 final int NI = p.intents.size(); 7355 int j; 7356 for (j = 0; j < NI; j++) { 7357 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7358 if (DEBUG_SHOW_INFO) { 7359 Log.v(TAG, " IntentFilter:"); 7360 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7361 } 7362 if (!intent.debugCheck()) { 7363 Log.w(TAG, "==> For Provider " + p.info.name); 7364 } 7365 addFilter(intent); 7366 } 7367 } 7368 7369 public final void removeProvider(PackageParser.Provider p) { 7370 mProviders.remove(p.getComponentName()); 7371 if (DEBUG_SHOW_INFO) { 7372 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7373 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7374 Log.v(TAG, " Class=" + p.info.name); 7375 } 7376 final int NI = p.intents.size(); 7377 int j; 7378 for (j = 0; j < NI; j++) { 7379 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7380 if (DEBUG_SHOW_INFO) { 7381 Log.v(TAG, " IntentFilter:"); 7382 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7383 } 7384 removeFilter(intent); 7385 } 7386 } 7387 7388 @Override 7389 protected boolean allowFilterResult( 7390 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7391 ProviderInfo filterPi = filter.provider.info; 7392 for (int i = dest.size() - 1; i >= 0; i--) { 7393 ProviderInfo destPi = dest.get(i).providerInfo; 7394 if (destPi.name == filterPi.name 7395 && destPi.packageName == filterPi.packageName) { 7396 return false; 7397 } 7398 } 7399 return true; 7400 } 7401 7402 @Override 7403 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7404 return new PackageParser.ProviderIntentInfo[size]; 7405 } 7406 7407 @Override 7408 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7409 if (!sUserManager.exists(userId)) 7410 return true; 7411 PackageParser.Package p = filter.provider.owner; 7412 if (p != null) { 7413 PackageSetting ps = (PackageSetting) p.mExtras; 7414 if (ps != null) { 7415 // System apps are never considered stopped for purposes of 7416 // filtering, because there may be no way for the user to 7417 // actually re-launch them. 7418 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7419 && ps.getStopped(userId); 7420 } 7421 } 7422 return false; 7423 } 7424 7425 @Override 7426 protected boolean isPackageForFilter(String packageName, 7427 PackageParser.ProviderIntentInfo info) { 7428 return packageName.equals(info.provider.owner.packageName); 7429 } 7430 7431 @Override 7432 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7433 int match, int userId) { 7434 if (!sUserManager.exists(userId)) 7435 return null; 7436 final PackageParser.ProviderIntentInfo info = filter; 7437 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7438 return null; 7439 } 7440 final PackageParser.Provider provider = info.provider; 7441 if (mSafeMode && (provider.info.applicationInfo.flags 7442 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7443 return null; 7444 } 7445 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7446 if (ps == null) { 7447 return null; 7448 } 7449 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7450 ps.readUserState(userId), userId); 7451 if (pi == null) { 7452 return null; 7453 } 7454 final ResolveInfo res = new ResolveInfo(); 7455 res.providerInfo = pi; 7456 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7457 res.filter = filter; 7458 } 7459 res.priority = info.getPriority(); 7460 res.preferredOrder = provider.owner.mPreferredOrder; 7461 res.match = match; 7462 res.isDefault = info.hasDefault; 7463 res.labelRes = info.labelRes; 7464 res.nonLocalizedLabel = info.nonLocalizedLabel; 7465 res.icon = info.icon; 7466 res.system = isSystemApp(res.providerInfo.applicationInfo); 7467 return res; 7468 } 7469 7470 @Override 7471 protected void sortResults(List<ResolveInfo> results) { 7472 Collections.sort(results, mResolvePrioritySorter); 7473 } 7474 7475 @Override 7476 protected void dumpFilter(PrintWriter out, String prefix, 7477 PackageParser.ProviderIntentInfo filter) { 7478 out.print(prefix); 7479 out.print( 7480 Integer.toHexString(System.identityHashCode(filter.provider))); 7481 out.print(' '); 7482 filter.provider.printComponentShortName(out); 7483 out.print(" filter "); 7484 out.println(Integer.toHexString(System.identityHashCode(filter))); 7485 } 7486 7487 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7488 = new HashMap<ComponentName, PackageParser.Provider>(); 7489 private int mFlags; 7490 }; 7491 7492 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7493 new Comparator<ResolveInfo>() { 7494 public int compare(ResolveInfo r1, ResolveInfo r2) { 7495 int v1 = r1.priority; 7496 int v2 = r2.priority; 7497 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7498 if (v1 != v2) { 7499 return (v1 > v2) ? -1 : 1; 7500 } 7501 v1 = r1.preferredOrder; 7502 v2 = r2.preferredOrder; 7503 if (v1 != v2) { 7504 return (v1 > v2) ? -1 : 1; 7505 } 7506 if (r1.isDefault != r2.isDefault) { 7507 return r1.isDefault ? -1 : 1; 7508 } 7509 v1 = r1.match; 7510 v2 = r2.match; 7511 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7512 if (v1 != v2) { 7513 return (v1 > v2) ? -1 : 1; 7514 } 7515 if (r1.system != r2.system) { 7516 return r1.system ? -1 : 1; 7517 } 7518 return 0; 7519 } 7520 }; 7521 7522 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7523 new Comparator<ProviderInfo>() { 7524 public int compare(ProviderInfo p1, ProviderInfo p2) { 7525 final int v1 = p1.initOrder; 7526 final int v2 = p2.initOrder; 7527 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7528 } 7529 }; 7530 7531 static final void sendPackageBroadcast(String action, String pkg, 7532 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7533 int[] userIds) { 7534 IActivityManager am = ActivityManagerNative.getDefault(); 7535 if (am != null) { 7536 try { 7537 if (userIds == null) { 7538 userIds = am.getRunningUserIds(); 7539 } 7540 for (int id : userIds) { 7541 final Intent intent = new Intent(action, 7542 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7543 if (extras != null) { 7544 intent.putExtras(extras); 7545 } 7546 if (targetPkg != null) { 7547 intent.setPackage(targetPkg); 7548 } 7549 // Modify the UID when posting to other users 7550 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7551 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7552 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7553 intent.putExtra(Intent.EXTRA_UID, uid); 7554 } 7555 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7556 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7557 if (DEBUG_BROADCASTS) { 7558 RuntimeException here = new RuntimeException("here"); 7559 here.fillInStackTrace(); 7560 Slog.d(TAG, "Sending to user " + id + ": " 7561 + intent.toShortString(false, true, false, false) 7562 + " " + intent.getExtras(), here); 7563 } 7564 am.broadcastIntent(null, intent, null, finishedReceiver, 7565 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7566 finishedReceiver != null, false, id); 7567 } 7568 } catch (RemoteException ex) { 7569 } 7570 } 7571 } 7572 7573 /** 7574 * Check if the external storage media is available. This is true if there 7575 * is a mounted external storage medium or if the external storage is 7576 * emulated. 7577 */ 7578 private boolean isExternalMediaAvailable() { 7579 return mMediaMounted || Environment.isExternalStorageEmulated(); 7580 } 7581 7582 @Override 7583 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7584 // writer 7585 synchronized (mPackages) { 7586 if (!isExternalMediaAvailable()) { 7587 // If the external storage is no longer mounted at this point, 7588 // the caller may not have been able to delete all of this 7589 // packages files and can not delete any more. Bail. 7590 return null; 7591 } 7592 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7593 if (lastPackage != null) { 7594 pkgs.remove(lastPackage); 7595 } 7596 if (pkgs.size() > 0) { 7597 return pkgs.get(0); 7598 } 7599 } 7600 return null; 7601 } 7602 7603 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7604 if (false) { 7605 RuntimeException here = new RuntimeException("here"); 7606 here.fillInStackTrace(); 7607 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7608 + " andCode=" + andCode, here); 7609 } 7610 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7611 userId, andCode ? 1 : 0, packageName)); 7612 } 7613 7614 void startCleaningPackages() { 7615 // reader 7616 synchronized (mPackages) { 7617 if (!isExternalMediaAvailable()) { 7618 return; 7619 } 7620 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7621 return; 7622 } 7623 } 7624 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7625 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7626 IActivityManager am = ActivityManagerNative.getDefault(); 7627 if (am != null) { 7628 try { 7629 am.startService(null, intent, null, UserHandle.USER_OWNER); 7630 } catch (RemoteException e) { 7631 } 7632 } 7633 } 7634 7635 private final class AppDirObserver extends FileObserver { 7636 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 7637 super(path, mask); 7638 mRootDir = path; 7639 mIsRom = isrom; 7640 mIsPrivileged = isPrivileged; 7641 } 7642 7643 public void onEvent(int event, String path) { 7644 String removedPackage = null; 7645 int removedAppId = -1; 7646 int[] removedUsers = null; 7647 String addedPackage = null; 7648 int addedAppId = -1; 7649 int[] addedUsers = null; 7650 7651 // TODO post a message to the handler to obtain serial ordering 7652 synchronized (mInstallLock) { 7653 String fullPathStr = null; 7654 File fullPath = null; 7655 if (path != null) { 7656 fullPath = new File(mRootDir, path); 7657 fullPathStr = fullPath.getPath(); 7658 } 7659 7660 if (DEBUG_APP_DIR_OBSERVER) 7661 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 7662 7663 if (!isApkFile(fullPath)) { 7664 if (DEBUG_APP_DIR_OBSERVER) 7665 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 7666 return; 7667 } 7668 7669 // Ignore packages that are being installed or 7670 // have just been installed. 7671 if (ignoreCodePath(fullPathStr)) { 7672 return; 7673 } 7674 PackageParser.Package p = null; 7675 PackageSetting ps = null; 7676 // reader 7677 synchronized (mPackages) { 7678 p = mAppDirs.get(fullPathStr); 7679 if (p != null) { 7680 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 7681 if (ps != null) { 7682 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7683 } else { 7684 removedUsers = sUserManager.getUserIds(); 7685 } 7686 } 7687 addedUsers = sUserManager.getUserIds(); 7688 } 7689 if ((event&REMOVE_EVENTS) != 0) { 7690 if (ps != null) { 7691 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 7692 removePackageLI(ps, true); 7693 removedPackage = ps.name; 7694 removedAppId = ps.appId; 7695 } 7696 } 7697 7698 if ((event&ADD_EVENTS) != 0) { 7699 if (p == null) { 7700 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 7701 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 7702 if (mIsRom) { 7703 flags |= PackageParser.PARSE_IS_SYSTEM 7704 | PackageParser.PARSE_IS_SYSTEM_DIR; 7705 if (mIsPrivileged) { 7706 flags |= PackageParser.PARSE_IS_PRIVILEGED; 7707 } 7708 } 7709 try { 7710 p = scanPackageLI(fullPath, flags, 7711 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 7712 System.currentTimeMillis(), UserHandle.ALL, null); 7713 } catch (PackageManagerException e) { 7714 Slog.w(TAG, "Failed to scan " + fullPath + ": " + e.getMessage()); 7715 p = null; 7716 } 7717 if (p != null) { 7718 /* 7719 * TODO this seems dangerous as the package may have 7720 * changed since we last acquired the mPackages 7721 * lock. 7722 */ 7723 // writer 7724 synchronized (mPackages) { 7725 updatePermissionsLPw(p.packageName, p, 7726 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 7727 } 7728 addedPackage = p.applicationInfo.packageName; 7729 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 7730 } 7731 } 7732 } 7733 7734 // reader 7735 synchronized (mPackages) { 7736 mSettings.writeLPr(); 7737 } 7738 } 7739 7740 if (removedPackage != null) { 7741 Bundle extras = new Bundle(1); 7742 extras.putInt(Intent.EXTRA_UID, removedAppId); 7743 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 7744 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7745 extras, null, null, removedUsers); 7746 } 7747 if (addedPackage != null) { 7748 Bundle extras = new Bundle(1); 7749 extras.putInt(Intent.EXTRA_UID, addedAppId); 7750 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 7751 extras, null, null, addedUsers); 7752 } 7753 } 7754 7755 private final String mRootDir; 7756 private final boolean mIsRom; 7757 private final boolean mIsPrivileged; 7758 } 7759 7760 @Override 7761 public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags, 7762 String installerPackageName, VerificationParams verificationParams, 7763 String packageAbiOverride) { 7764 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7765 null); 7766 7767 final File originFile = new File(originPath); 7768 final int uid = Binder.getCallingUid(); 7769 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7770 try { 7771 if (observer != null) { 7772 observer.packageInstalled("", null, INSTALL_FAILED_USER_RESTRICTED, null); 7773 } 7774 } catch (RemoteException re) { 7775 } 7776 return; 7777 } 7778 7779 UserHandle user; 7780 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7781 user = UserHandle.ALL; 7782 } else { 7783 user = new UserHandle(UserHandle.getUserId(uid)); 7784 } 7785 7786 final int filteredFlags; 7787 if (uid == Process.SHELL_UID || uid == 0) { 7788 if (DEBUG_INSTALL) { 7789 Slog.v(TAG, "Install from ADB"); 7790 } 7791 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7792 } else { 7793 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7794 } 7795 7796 verificationParams.setInstallerUid(uid); 7797 7798 final Message msg = mHandler.obtainMessage(INIT_COPY); 7799 msg.obj = new InstallParams(originFile, false, observer, filteredFlags, 7800 installerPackageName, verificationParams, user, packageAbiOverride); 7801 mHandler.sendMessage(msg); 7802 } 7803 7804 void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer, 7805 InstallSessionParams params, String installerPackageName, int installerUid, 7806 UserHandle user) { 7807 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7808 params.referrerUri, installerUid, null); 7809 7810 final Message msg = mHandler.obtainMessage(INIT_COPY); 7811 msg.obj = new InstallParams(stageDir, true, observer, params.installFlags, 7812 installerPackageName, verifParams, user, params.abiOverride); 7813 mHandler.sendMessage(msg); 7814 } 7815 7816 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7817 Bundle extras = new Bundle(1); 7818 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7819 7820 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7821 packageName, extras, null, null, new int[] {userId}); 7822 try { 7823 IActivityManager am = ActivityManagerNative.getDefault(); 7824 final boolean isSystem = 7825 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7826 if (isSystem && am.isUserRunning(userId, false)) { 7827 // The just-installed/enabled app is bundled on the system, so presumed 7828 // to be able to run automatically without needing an explicit launch. 7829 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7830 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7831 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7832 .setPackage(packageName); 7833 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7834 android.app.AppOpsManager.OP_NONE, false, false, userId); 7835 } 7836 } catch (RemoteException e) { 7837 // shouldn't happen 7838 Slog.w(TAG, "Unable to bootstrap installed package", e); 7839 } 7840 } 7841 7842 @Override 7843 public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked, 7844 int userId) { 7845 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7846 PackageSetting pkgSetting; 7847 final int uid = Binder.getCallingUid(); 7848 if (UserHandle.getUserId(uid) != userId) { 7849 mContext.enforceCallingOrSelfPermission( 7850 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7851 "setApplicationBlockedSetting for user " + userId); 7852 } 7853 7854 if (blocked && isPackageDeviceAdmin(packageName, userId)) { 7855 Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin"); 7856 return false; 7857 } 7858 7859 long callingId = Binder.clearCallingIdentity(); 7860 try { 7861 boolean sendAdded = false; 7862 boolean sendRemoved = false; 7863 // writer 7864 synchronized (mPackages) { 7865 pkgSetting = mSettings.mPackages.get(packageName); 7866 if (pkgSetting == null) { 7867 return false; 7868 } 7869 if (pkgSetting.getBlocked(userId) != blocked) { 7870 pkgSetting.setBlocked(blocked, userId); 7871 mSettings.writePackageRestrictionsLPr(userId); 7872 if (blocked) { 7873 sendRemoved = true; 7874 } else { 7875 sendAdded = true; 7876 } 7877 } 7878 } 7879 if (sendAdded) { 7880 sendPackageAddedForUser(packageName, pkgSetting, userId); 7881 return true; 7882 } 7883 if (sendRemoved) { 7884 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7885 "blocking pkg"); 7886 sendPackageBlockedForUser(packageName, pkgSetting, userId); 7887 } 7888 } finally { 7889 Binder.restoreCallingIdentity(callingId); 7890 } 7891 return false; 7892 } 7893 7894 private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting, 7895 int userId) { 7896 final PackageRemovedInfo info = new PackageRemovedInfo(); 7897 info.removedPackage = packageName; 7898 info.removedUsers = new int[] {userId}; 7899 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7900 info.sendBroadcast(false, false, false); 7901 } 7902 7903 /** 7904 * Returns true if application is not found or there was an error. Otherwise it returns 7905 * the blocked state of the package for the given user. 7906 */ 7907 @Override 7908 public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) { 7909 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7910 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7911 "getApplicationBlocked for user " + userId); 7912 PackageSetting pkgSetting; 7913 long callingId = Binder.clearCallingIdentity(); 7914 try { 7915 // writer 7916 synchronized (mPackages) { 7917 pkgSetting = mSettings.mPackages.get(packageName); 7918 if (pkgSetting == null) { 7919 return true; 7920 } 7921 return pkgSetting.getBlocked(userId); 7922 } 7923 } finally { 7924 Binder.restoreCallingIdentity(callingId); 7925 } 7926 } 7927 7928 /** 7929 * @hide 7930 */ 7931 @Override 7932 public int installExistingPackageAsUser(String packageName, int userId) { 7933 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7934 null); 7935 PackageSetting pkgSetting; 7936 final int uid = Binder.getCallingUid(); 7937 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7938 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7939 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7940 } 7941 7942 long callingId = Binder.clearCallingIdentity(); 7943 try { 7944 boolean sendAdded = false; 7945 Bundle extras = new Bundle(1); 7946 7947 // writer 7948 synchronized (mPackages) { 7949 pkgSetting = mSettings.mPackages.get(packageName); 7950 if (pkgSetting == null) { 7951 return PackageManager.INSTALL_FAILED_INVALID_URI; 7952 } 7953 if (!pkgSetting.getInstalled(userId)) { 7954 pkgSetting.setInstalled(true, userId); 7955 pkgSetting.setBlocked(false, userId); 7956 mSettings.writePackageRestrictionsLPr(userId); 7957 sendAdded = true; 7958 } 7959 } 7960 7961 if (sendAdded) { 7962 sendPackageAddedForUser(packageName, pkgSetting, userId); 7963 } 7964 } finally { 7965 Binder.restoreCallingIdentity(callingId); 7966 } 7967 7968 return PackageManager.INSTALL_SUCCEEDED; 7969 } 7970 7971 boolean isUserRestricted(int userId, String restrictionKey) { 7972 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7973 if (restrictions.getBoolean(restrictionKey, false)) { 7974 Log.w(TAG, "User is restricted: " + restrictionKey); 7975 return true; 7976 } 7977 return false; 7978 } 7979 7980 @Override 7981 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7982 mContext.enforceCallingOrSelfPermission( 7983 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7984 "Only package verification agents can verify applications"); 7985 7986 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7987 final PackageVerificationResponse response = new PackageVerificationResponse( 7988 verificationCode, Binder.getCallingUid()); 7989 msg.arg1 = id; 7990 msg.obj = response; 7991 mHandler.sendMessage(msg); 7992 } 7993 7994 @Override 7995 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7996 long millisecondsToDelay) { 7997 mContext.enforceCallingOrSelfPermission( 7998 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7999 "Only package verification agents can extend verification timeouts"); 8000 8001 final PackageVerificationState state = mPendingVerification.get(id); 8002 final PackageVerificationResponse response = new PackageVerificationResponse( 8003 verificationCodeAtTimeout, Binder.getCallingUid()); 8004 8005 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8006 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8007 } 8008 if (millisecondsToDelay < 0) { 8009 millisecondsToDelay = 0; 8010 } 8011 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8012 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8013 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8014 } 8015 8016 if ((state != null) && !state.timeoutExtended()) { 8017 state.extendTimeout(); 8018 8019 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8020 msg.arg1 = id; 8021 msg.obj = response; 8022 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8023 } 8024 } 8025 8026 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8027 int verificationCode, UserHandle user) { 8028 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8029 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8030 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8031 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8032 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8033 8034 mContext.sendBroadcastAsUser(intent, user, 8035 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8036 } 8037 8038 private ComponentName matchComponentForVerifier(String packageName, 8039 List<ResolveInfo> receivers) { 8040 ActivityInfo targetReceiver = null; 8041 8042 final int NR = receivers.size(); 8043 for (int i = 0; i < NR; i++) { 8044 final ResolveInfo info = receivers.get(i); 8045 if (info.activityInfo == null) { 8046 continue; 8047 } 8048 8049 if (packageName.equals(info.activityInfo.packageName)) { 8050 targetReceiver = info.activityInfo; 8051 break; 8052 } 8053 } 8054 8055 if (targetReceiver == null) { 8056 return null; 8057 } 8058 8059 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8060 } 8061 8062 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8063 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8064 if (pkgInfo.verifiers.length == 0) { 8065 return null; 8066 } 8067 8068 final int N = pkgInfo.verifiers.length; 8069 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8070 for (int i = 0; i < N; i++) { 8071 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8072 8073 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8074 receivers); 8075 if (comp == null) { 8076 continue; 8077 } 8078 8079 final int verifierUid = getUidForVerifier(verifierInfo); 8080 if (verifierUid == -1) { 8081 continue; 8082 } 8083 8084 if (DEBUG_VERIFY) { 8085 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8086 + " with the correct signature"); 8087 } 8088 sufficientVerifiers.add(comp); 8089 verificationState.addSufficientVerifier(verifierUid); 8090 } 8091 8092 return sufficientVerifiers; 8093 } 8094 8095 private int getUidForVerifier(VerifierInfo verifierInfo) { 8096 synchronized (mPackages) { 8097 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8098 if (pkg == null) { 8099 return -1; 8100 } else if (pkg.mSignatures.length != 1) { 8101 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8102 + " has more than one signature; ignoring"); 8103 return -1; 8104 } 8105 8106 /* 8107 * If the public key of the package's signature does not match 8108 * our expected public key, then this is a different package and 8109 * we should skip. 8110 */ 8111 8112 final byte[] expectedPublicKey; 8113 try { 8114 final Signature verifierSig = pkg.mSignatures[0]; 8115 final PublicKey publicKey = verifierSig.getPublicKey(); 8116 expectedPublicKey = publicKey.getEncoded(); 8117 } catch (CertificateException e) { 8118 return -1; 8119 } 8120 8121 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8122 8123 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8124 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8125 + " does not have the expected public key; ignoring"); 8126 return -1; 8127 } 8128 8129 return pkg.applicationInfo.uid; 8130 } 8131 } 8132 8133 @Override 8134 public void finishPackageInstall(int token) { 8135 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8136 8137 if (DEBUG_INSTALL) { 8138 Slog.v(TAG, "BM finishing package install for " + token); 8139 } 8140 8141 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8142 mHandler.sendMessage(msg); 8143 } 8144 8145 /** 8146 * Get the verification agent timeout. 8147 * 8148 * @return verification timeout in milliseconds 8149 */ 8150 private long getVerificationTimeout() { 8151 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8152 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8153 DEFAULT_VERIFICATION_TIMEOUT); 8154 } 8155 8156 /** 8157 * Get the default verification agent response code. 8158 * 8159 * @return default verification response code 8160 */ 8161 private int getDefaultVerificationResponse() { 8162 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8163 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8164 DEFAULT_VERIFICATION_RESPONSE); 8165 } 8166 8167 /** 8168 * Check whether or not package verification has been enabled. 8169 * 8170 * @return true if verification should be performed 8171 */ 8172 private boolean isVerificationEnabled(int userId, int flags) { 8173 if (!DEFAULT_VERIFY_ENABLE) { 8174 return false; 8175 } 8176 8177 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8178 8179 // Check if installing from ADB 8180 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8181 // Do not run verification in a test harness environment 8182 if (ActivityManager.isRunningInTestHarness()) { 8183 return false; 8184 } 8185 if (ensureVerifyAppsEnabled) { 8186 return true; 8187 } 8188 // Check if the developer does not want package verification for ADB installs 8189 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8190 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8191 return false; 8192 } 8193 } 8194 8195 if (ensureVerifyAppsEnabled) { 8196 return true; 8197 } 8198 8199 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8200 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8201 } 8202 8203 /** 8204 * Get the "allow unknown sources" setting. 8205 * 8206 * @return the current "allow unknown sources" setting 8207 */ 8208 private int getUnknownSourcesSettings() { 8209 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8210 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8211 -1); 8212 } 8213 8214 @Override 8215 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8216 final int uid = Binder.getCallingUid(); 8217 // writer 8218 synchronized (mPackages) { 8219 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8220 if (targetPackageSetting == null) { 8221 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8222 } 8223 8224 PackageSetting installerPackageSetting; 8225 if (installerPackageName != null) { 8226 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8227 if (installerPackageSetting == null) { 8228 throw new IllegalArgumentException("Unknown installer package: " 8229 + installerPackageName); 8230 } 8231 } else { 8232 installerPackageSetting = null; 8233 } 8234 8235 Signature[] callerSignature; 8236 Object obj = mSettings.getUserIdLPr(uid); 8237 if (obj != null) { 8238 if (obj instanceof SharedUserSetting) { 8239 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8240 } else if (obj instanceof PackageSetting) { 8241 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8242 } else { 8243 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8244 } 8245 } else { 8246 throw new SecurityException("Unknown calling uid " + uid); 8247 } 8248 8249 // Verify: can't set installerPackageName to a package that is 8250 // not signed with the same cert as the caller. 8251 if (installerPackageSetting != null) { 8252 if (compareSignatures(callerSignature, 8253 installerPackageSetting.signatures.mSignatures) 8254 != PackageManager.SIGNATURE_MATCH) { 8255 throw new SecurityException( 8256 "Caller does not have same cert as new installer package " 8257 + installerPackageName); 8258 } 8259 } 8260 8261 // Verify: if target already has an installer package, it must 8262 // be signed with the same cert as the caller. 8263 if (targetPackageSetting.installerPackageName != null) { 8264 PackageSetting setting = mSettings.mPackages.get( 8265 targetPackageSetting.installerPackageName); 8266 // If the currently set package isn't valid, then it's always 8267 // okay to change it. 8268 if (setting != null) { 8269 if (compareSignatures(callerSignature, 8270 setting.signatures.mSignatures) 8271 != PackageManager.SIGNATURE_MATCH) { 8272 throw new SecurityException( 8273 "Caller does not have same cert as old installer package " 8274 + targetPackageSetting.installerPackageName); 8275 } 8276 } 8277 } 8278 8279 // Okay! 8280 targetPackageSetting.installerPackageName = installerPackageName; 8281 scheduleWriteSettingsLocked(); 8282 } 8283 } 8284 8285 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8286 // Queue up an async operation since the package installation may take a little while. 8287 mHandler.post(new Runnable() { 8288 public void run() { 8289 mHandler.removeCallbacks(this); 8290 // Result object to be returned 8291 PackageInstalledInfo res = new PackageInstalledInfo(); 8292 res.returnCode = currentStatus; 8293 res.uid = -1; 8294 res.pkg = null; 8295 res.removedInfo = new PackageRemovedInfo(); 8296 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8297 args.doPreInstall(res.returnCode); 8298 synchronized (mInstallLock) { 8299 installPackageLI(args, true, res); 8300 } 8301 args.doPostInstall(res.returnCode, res.uid); 8302 } 8303 8304 // A restore should be performed at this point if (a) the install 8305 // succeeded, (b) the operation is not an update, and (c) the new 8306 // package has a backupAgent defined. 8307 final boolean update = res.removedInfo.removedPackage != null; 8308 boolean doRestore = (!update 8309 && res.pkg != null 8310 && res.pkg.applicationInfo.backupAgentName != null); 8311 8312 // Set up the post-install work request bookkeeping. This will be used 8313 // and cleaned up by the post-install event handling regardless of whether 8314 // there's a restore pass performed. Token values are >= 1. 8315 int token; 8316 if (mNextInstallToken < 0) mNextInstallToken = 1; 8317 token = mNextInstallToken++; 8318 8319 PostInstallData data = new PostInstallData(args, res); 8320 mRunningInstalls.put(token, data); 8321 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8322 8323 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8324 // Pass responsibility to the Backup Manager. It will perform a 8325 // restore if appropriate, then pass responsibility back to the 8326 // Package Manager to run the post-install observer callbacks 8327 // and broadcasts. 8328 IBackupManager bm = IBackupManager.Stub.asInterface( 8329 ServiceManager.getService(Context.BACKUP_SERVICE)); 8330 if (bm != null) { 8331 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8332 + " to BM for possible restore"); 8333 try { 8334 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8335 } catch (RemoteException e) { 8336 // can't happen; the backup manager is local 8337 } catch (Exception e) { 8338 Slog.e(TAG, "Exception trying to enqueue restore", e); 8339 doRestore = false; 8340 } 8341 } else { 8342 Slog.e(TAG, "Backup Manager not found!"); 8343 doRestore = false; 8344 } 8345 } 8346 8347 if (!doRestore) { 8348 // No restore possible, or the Backup Manager was mysteriously not 8349 // available -- just fire the post-install work request directly. 8350 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8351 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8352 mHandler.sendMessage(msg); 8353 } 8354 } 8355 }); 8356 } 8357 8358 private abstract class HandlerParams { 8359 private static final int MAX_RETRIES = 4; 8360 8361 /** 8362 * Number of times startCopy() has been attempted and had a non-fatal 8363 * error. 8364 */ 8365 private int mRetries = 0; 8366 8367 /** User handle for the user requesting the information or installation. */ 8368 private final UserHandle mUser; 8369 8370 HandlerParams(UserHandle user) { 8371 mUser = user; 8372 } 8373 8374 UserHandle getUser() { 8375 return mUser; 8376 } 8377 8378 final boolean startCopy() { 8379 boolean res; 8380 try { 8381 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8382 8383 if (++mRetries > MAX_RETRIES) { 8384 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8385 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8386 handleServiceError(); 8387 return false; 8388 } else { 8389 handleStartCopy(); 8390 res = true; 8391 } 8392 } catch (RemoteException e) { 8393 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8394 mHandler.sendEmptyMessage(MCS_RECONNECT); 8395 res = false; 8396 } 8397 handleReturnCode(); 8398 return res; 8399 } 8400 8401 final void serviceError() { 8402 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8403 handleServiceError(); 8404 handleReturnCode(); 8405 } 8406 8407 abstract void handleStartCopy() throws RemoteException; 8408 abstract void handleServiceError(); 8409 abstract void handleReturnCode(); 8410 } 8411 8412 class MeasureParams extends HandlerParams { 8413 private final PackageStats mStats; 8414 private boolean mSuccess; 8415 8416 private final IPackageStatsObserver mObserver; 8417 8418 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8419 super(new UserHandle(stats.userHandle)); 8420 mObserver = observer; 8421 mStats = stats; 8422 } 8423 8424 @Override 8425 public String toString() { 8426 return "MeasureParams{" 8427 + Integer.toHexString(System.identityHashCode(this)) 8428 + " " + mStats.packageName + "}"; 8429 } 8430 8431 @Override 8432 void handleStartCopy() throws RemoteException { 8433 synchronized (mInstallLock) { 8434 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8435 } 8436 8437 if (mSuccess) { 8438 final boolean mounted; 8439 if (Environment.isExternalStorageEmulated()) { 8440 mounted = true; 8441 } else { 8442 final String status = Environment.getExternalStorageState(); 8443 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8444 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8445 } 8446 8447 if (mounted) { 8448 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8449 8450 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8451 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8452 8453 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8454 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8455 8456 // Always subtract cache size, since it's a subdirectory 8457 mStats.externalDataSize -= mStats.externalCacheSize; 8458 8459 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8460 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8461 8462 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8463 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8464 } 8465 } 8466 } 8467 8468 @Override 8469 void handleReturnCode() { 8470 if (mObserver != null) { 8471 try { 8472 mObserver.onGetStatsCompleted(mStats, mSuccess); 8473 } catch (RemoteException e) { 8474 Slog.i(TAG, "Observer no longer exists."); 8475 } 8476 } 8477 } 8478 8479 @Override 8480 void handleServiceError() { 8481 Slog.e(TAG, "Could not measure application " + mStats.packageName 8482 + " external storage"); 8483 } 8484 } 8485 8486 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8487 throws RemoteException { 8488 long result = 0; 8489 for (File path : paths) { 8490 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8491 } 8492 return result; 8493 } 8494 8495 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8496 for (File path : paths) { 8497 try { 8498 mcs.clearDirectory(path.getAbsolutePath()); 8499 } catch (RemoteException e) { 8500 } 8501 } 8502 } 8503 8504 class InstallParams extends HandlerParams { 8505 /** 8506 * Location where install is coming from, before it has been 8507 * copied/renamed into place. This could be a single monolithic APK 8508 * file, or a cluster directory. This location may be untrusted. 8509 */ 8510 final File originFile; 8511 8512 /** 8513 * Flag indicating that {@link #originFile} has already been staged, 8514 * meaning downstream users don't need to defensively copy the contents. 8515 */ 8516 boolean originStaged; 8517 8518 final IPackageInstallObserver2 observer; 8519 int flags; 8520 final String installerPackageName; 8521 final VerificationParams verificationParams; 8522 private InstallArgs mArgs; 8523 private int mRet; 8524 final String packageAbiOverride; 8525 boolean multiArch; 8526 8527 InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 8528 int flags, String installerPackageName, VerificationParams verificationParams, 8529 UserHandle user, String packageAbiOverride) { 8530 super(user); 8531 this.originFile = Preconditions.checkNotNull(originFile); 8532 this.originStaged = originStaged; 8533 this.observer = observer; 8534 this.flags = flags; 8535 this.installerPackageName = installerPackageName; 8536 this.verificationParams = verificationParams; 8537 this.packageAbiOverride = packageAbiOverride; 8538 } 8539 8540 @Override 8541 public String toString() { 8542 return "InstallParams{" 8543 + Integer.toHexString(System.identityHashCode(this)) 8544 + " " + originFile + "}"; 8545 } 8546 8547 public ManifestDigest getManifestDigest() { 8548 if (verificationParams == null) { 8549 return null; 8550 } 8551 return verificationParams.getManifestDigest(); 8552 } 8553 8554 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8555 String packageName = pkgLite.packageName; 8556 int installLocation = pkgLite.installLocation; 8557 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8558 // reader 8559 synchronized (mPackages) { 8560 PackageParser.Package pkg = mPackages.get(packageName); 8561 if (pkg != null) { 8562 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8563 // Check for downgrading. 8564 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8565 if (pkgLite.versionCode < pkg.mVersionCode) { 8566 Slog.w(TAG, "Can't install update of " + packageName 8567 + " update version " + pkgLite.versionCode 8568 + " is older than installed version " 8569 + pkg.mVersionCode); 8570 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8571 } 8572 } 8573 // Check for updated system application. 8574 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8575 if (onSd) { 8576 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8577 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8578 } 8579 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8580 } else { 8581 if (onSd) { 8582 // Install flag overrides everything. 8583 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8584 } 8585 // If current upgrade specifies particular preference 8586 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8587 // Application explicitly specified internal. 8588 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8589 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8590 // App explictly prefers external. Let policy decide 8591 } else { 8592 // Prefer previous location 8593 if (isExternal(pkg)) { 8594 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8595 } 8596 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8597 } 8598 } 8599 } else { 8600 // Invalid install. Return error code 8601 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8602 } 8603 } 8604 } 8605 // All the special cases have been taken care of. 8606 // Return result based on recommended install location. 8607 if (onSd) { 8608 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8609 } 8610 return pkgLite.recommendedInstallLocation; 8611 } 8612 8613 private long getMemoryLowThreshold() { 8614 final DeviceStorageMonitorInternal 8615 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8616 if (dsm == null) { 8617 return 0L; 8618 } 8619 return dsm.getMemoryLowThreshold(); 8620 } 8621 8622 /* 8623 * Invoke remote method to get package information and install 8624 * location values. Override install location based on default 8625 * policy if needed and then create install arguments based 8626 * on the install location. 8627 */ 8628 public void handleStartCopy() throws RemoteException { 8629 int ret = PackageManager.INSTALL_SUCCEEDED; 8630 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8631 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8632 PackageInfoLite pkgLite = null; 8633 8634 if (onInt && onSd) { 8635 // Check if both bits are set. 8636 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8637 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8638 } else { 8639 final long lowThreshold = getMemoryLowThreshold(); 8640 if (lowThreshold == 0L) { 8641 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8642 } 8643 8644 // Remote call to find out default install location 8645 final String originPath = originFile.getAbsolutePath(); 8646 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold, 8647 packageAbiOverride); 8648 // Keep track of whether this package is a multiArch package until 8649 // we perform a full scan of it. We need to do this because we might 8650 // end up extracting the package shared libraries before we perform 8651 // a full scan. 8652 multiArch = pkgLite.multiArch; 8653 8654 /* 8655 * If we have too little free space, try to free cache 8656 * before giving up. 8657 */ 8658 if (pkgLite.recommendedInstallLocation 8659 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8660 final long size = mContainerService.calculateInstalledSize( 8661 originPath, isForwardLocked(), packageAbiOverride); 8662 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8663 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, 8664 lowThreshold, packageAbiOverride); 8665 } 8666 /* 8667 * The cache free must have deleted the file we 8668 * downloaded to install. 8669 * 8670 * TODO: fix the "freeCache" call to not delete 8671 * the file we care about. 8672 */ 8673 if (pkgLite.recommendedInstallLocation 8674 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8675 pkgLite.recommendedInstallLocation 8676 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8677 } 8678 } 8679 } 8680 8681 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8682 int loc = pkgLite.recommendedInstallLocation; 8683 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8684 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8685 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8686 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8687 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8688 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8689 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8690 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8691 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8692 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8693 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8694 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8695 } else { 8696 // Override with defaults if needed. 8697 loc = installLocationPolicy(pkgLite, flags); 8698 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8699 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8700 } else if (!onSd && !onInt) { 8701 // Override install location with flags 8702 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8703 // Set the flag to install on external media. 8704 flags |= PackageManager.INSTALL_EXTERNAL; 8705 flags &= ~PackageManager.INSTALL_INTERNAL; 8706 } else { 8707 // Make sure the flag for installing on external 8708 // media is unset 8709 flags |= PackageManager.INSTALL_INTERNAL; 8710 flags &= ~PackageManager.INSTALL_EXTERNAL; 8711 } 8712 } 8713 } 8714 } 8715 8716 final InstallArgs args = createInstallArgs(this); 8717 mArgs = args; 8718 8719 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8720 /* 8721 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8722 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8723 */ 8724 int userIdentifier = getUser().getIdentifier(); 8725 if (userIdentifier == UserHandle.USER_ALL 8726 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8727 userIdentifier = UserHandle.USER_OWNER; 8728 } 8729 8730 /* 8731 * Determine if we have any installed package verifiers. If we 8732 * do, then we'll defer to them to verify the packages. 8733 */ 8734 final int requiredUid = mRequiredVerifierPackage == null ? -1 8735 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8736 if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) { 8737 // TODO: send verifier the install session instead of uri 8738 final Intent verification = new Intent( 8739 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8740 verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE); 8741 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8742 8743 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8744 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8745 0 /* TODO: Which userId? */); 8746 8747 if (DEBUG_VERIFY) { 8748 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8749 + verification.toString() + " with " + pkgLite.verifiers.length 8750 + " optional verifiers"); 8751 } 8752 8753 final int verificationId = mPendingVerificationToken++; 8754 8755 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8756 8757 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8758 installerPackageName); 8759 8760 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8761 8762 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8763 pkgLite.packageName); 8764 8765 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8766 pkgLite.versionCode); 8767 8768 if (verificationParams != null) { 8769 if (verificationParams.getVerificationURI() != null) { 8770 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8771 verificationParams.getVerificationURI()); 8772 } 8773 if (verificationParams.getOriginatingURI() != null) { 8774 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8775 verificationParams.getOriginatingURI()); 8776 } 8777 if (verificationParams.getReferrer() != null) { 8778 verification.putExtra(Intent.EXTRA_REFERRER, 8779 verificationParams.getReferrer()); 8780 } 8781 if (verificationParams.getOriginatingUid() >= 0) { 8782 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8783 verificationParams.getOriginatingUid()); 8784 } 8785 if (verificationParams.getInstallerUid() >= 0) { 8786 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8787 verificationParams.getInstallerUid()); 8788 } 8789 } 8790 8791 final PackageVerificationState verificationState = new PackageVerificationState( 8792 requiredUid, args); 8793 8794 mPendingVerification.append(verificationId, verificationState); 8795 8796 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8797 receivers, verificationState); 8798 8799 /* 8800 * If any sufficient verifiers were listed in the package 8801 * manifest, attempt to ask them. 8802 */ 8803 if (sufficientVerifiers != null) { 8804 final int N = sufficientVerifiers.size(); 8805 if (N == 0) { 8806 Slog.i(TAG, "Additional verifiers required, but none installed."); 8807 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8808 } else { 8809 for (int i = 0; i < N; i++) { 8810 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8811 8812 final Intent sufficientIntent = new Intent(verification); 8813 sufficientIntent.setComponent(verifierComponent); 8814 8815 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8816 } 8817 } 8818 } 8819 8820 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8821 mRequiredVerifierPackage, receivers); 8822 if (ret == PackageManager.INSTALL_SUCCEEDED 8823 && mRequiredVerifierPackage != null) { 8824 /* 8825 * Send the intent to the required verification agent, 8826 * but only start the verification timeout after the 8827 * target BroadcastReceivers have run. 8828 */ 8829 verification.setComponent(requiredVerifierComponent); 8830 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8831 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8832 new BroadcastReceiver() { 8833 @Override 8834 public void onReceive(Context context, Intent intent) { 8835 final Message msg = mHandler 8836 .obtainMessage(CHECK_PENDING_VERIFICATION); 8837 msg.arg1 = verificationId; 8838 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8839 } 8840 }, null, 0, null, null); 8841 8842 /* 8843 * We don't want the copy to proceed until verification 8844 * succeeds, so null out this field. 8845 */ 8846 mArgs = null; 8847 } 8848 } else { 8849 /* 8850 * No package verification is enabled, so immediately start 8851 * the remote call to initiate copy using temporary file. 8852 */ 8853 ret = args.copyApk(mContainerService, true); 8854 } 8855 } 8856 8857 mRet = ret; 8858 } 8859 8860 @Override 8861 void handleReturnCode() { 8862 // If mArgs is null, then MCS couldn't be reached. When it 8863 // reconnects, it will try again to install. At that point, this 8864 // will succeed. 8865 if (mArgs != null) { 8866 processPendingInstall(mArgs, mRet); 8867 } 8868 } 8869 8870 @Override 8871 void handleServiceError() { 8872 mArgs = createInstallArgs(this); 8873 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8874 } 8875 8876 public boolean isForwardLocked() { 8877 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8878 } 8879 } 8880 8881 /* 8882 * Utility class used in movePackage api. 8883 * srcArgs and targetArgs are not set for invalid flags and make 8884 * sure to do null checks when invoking methods on them. 8885 * We probably want to return ErrorPrams for both failed installs 8886 * and moves. 8887 */ 8888 class MoveParams extends HandlerParams { 8889 final IPackageMoveObserver observer; 8890 final int flags; 8891 final String packageName; 8892 final InstallArgs srcArgs; 8893 final InstallArgs targetArgs; 8894 int uid; 8895 int mRet; 8896 8897 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8898 String packageName, String[] instructionSets, int uid, UserHandle user, 8899 boolean isMultiArch) { 8900 super(user); 8901 this.srcArgs = srcArgs; 8902 this.observer = observer; 8903 this.flags = flags; 8904 this.packageName = packageName; 8905 this.uid = uid; 8906 if (srcArgs != null) { 8907 final String codePath = srcArgs.getCodePath(); 8908 targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, 8909 instructionSets, isMultiArch); 8910 } else { 8911 targetArgs = null; 8912 } 8913 } 8914 8915 @Override 8916 public String toString() { 8917 return "MoveParams{" 8918 + Integer.toHexString(System.identityHashCode(this)) 8919 + " " + packageName + "}"; 8920 } 8921 8922 public void handleStartCopy() throws RemoteException { 8923 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8924 // Check for storage space on target medium 8925 if (!targetArgs.checkFreeStorage(mContainerService)) { 8926 Log.w(TAG, "Insufficient storage to install"); 8927 return; 8928 } 8929 8930 mRet = srcArgs.doPreCopy(); 8931 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8932 return; 8933 } 8934 8935 mRet = targetArgs.copyApk(mContainerService, false); 8936 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8937 srcArgs.doPostCopy(uid); 8938 return; 8939 } 8940 8941 mRet = srcArgs.doPostCopy(uid); 8942 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8943 return; 8944 } 8945 8946 mRet = targetArgs.doPreInstall(mRet); 8947 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8948 return; 8949 } 8950 8951 if (DEBUG_SD_INSTALL) { 8952 StringBuilder builder = new StringBuilder(); 8953 if (srcArgs != null) { 8954 builder.append("src: "); 8955 builder.append(srcArgs.getCodePath()); 8956 } 8957 if (targetArgs != null) { 8958 builder.append(" target : "); 8959 builder.append(targetArgs.getCodePath()); 8960 } 8961 Log.i(TAG, builder.toString()); 8962 } 8963 } 8964 8965 @Override 8966 void handleReturnCode() { 8967 targetArgs.doPostInstall(mRet, uid); 8968 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8969 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8970 currentStatus = PackageManager.MOVE_SUCCEEDED; 8971 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8972 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8973 } 8974 processPendingMove(this, currentStatus); 8975 } 8976 8977 @Override 8978 void handleServiceError() { 8979 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8980 } 8981 } 8982 8983 /** 8984 * Used during creation of InstallArgs 8985 * 8986 * @param flags package installation flags 8987 * @return true if should be installed on external storage 8988 */ 8989 private static boolean installOnSd(int flags) { 8990 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8991 return false; 8992 } 8993 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8994 return true; 8995 } 8996 return false; 8997 } 8998 8999 /** 9000 * Used during creation of InstallArgs 9001 * 9002 * @param flags package installation flags 9003 * @return true if should be installed as forward locked 9004 */ 9005 private static boolean installForwardLocked(int flags) { 9006 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9007 } 9008 9009 private InstallArgs createInstallArgs(InstallParams params) { 9010 // TODO: extend to support incoming zero-copy locations 9011 9012 if (installOnSd(params.flags) || params.isForwardLocked()) { 9013 return new AsecInstallArgs(params); 9014 } else { 9015 return new FileInstallArgs(params); 9016 } 9017 } 9018 9019 /** 9020 * Create args that describe an existing installed package. Typically used 9021 * when cleaning up old installs, or used as a move source. 9022 */ 9023 private InstallArgs createInstallArgsForExisting(int flags, String codePath, 9024 String resourcePath, String nativeLibraryRoot, String[] instructionSets, 9025 boolean isMultiArch) { 9026 final boolean isInAsec; 9027 if (installOnSd(flags)) { 9028 /* Apps on SD card are always in ASEC containers. */ 9029 isInAsec = true; 9030 } else if (installForwardLocked(flags) 9031 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9032 /* 9033 * Forward-locked apps are only in ASEC containers if they're the 9034 * new style 9035 */ 9036 isInAsec = true; 9037 } else { 9038 isInAsec = false; 9039 } 9040 9041 if (isInAsec) { 9042 return new AsecInstallArgs(codePath, instructionSets, 9043 installOnSd(flags), installForwardLocked(flags), isMultiArch); 9044 } else { 9045 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9046 instructionSets, isMultiArch); 9047 } 9048 } 9049 9050 private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName, 9051 String[] instructionSets, boolean isMultiArch) { 9052 final File codeFile = new File(codePath); 9053 if (installOnSd(flags) || installForwardLocked(flags)) { 9054 String cid = getNextCodePath(codePath, pkgName, "/" 9055 + AsecInstallArgs.RES_FILE_NAME); 9056 return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags), 9057 installForwardLocked(flags), isMultiArch); 9058 } else { 9059 return new FileInstallArgs(codeFile, instructionSets, isMultiArch); 9060 } 9061 } 9062 9063 static abstract class InstallArgs { 9064 /** @see InstallParams#originFile */ 9065 final File originFile; 9066 /** @see InstallParams#originStaged */ 9067 final boolean originStaged; 9068 9069 // TODO: define inherit location 9070 9071 final IPackageInstallObserver2 observer; 9072 // Always refers to PackageManager flags only 9073 final int flags; 9074 final String installerPackageName; 9075 final ManifestDigest manifestDigest; 9076 final UserHandle user; 9077 final String abiOverride; 9078 final boolean multiArch; 9079 9080 // The list of instruction sets supported by this app. This is currently 9081 // only used during the rmdex() phase to clean up resources. We can get rid of this 9082 // if we move dex files under the common app path. 9083 /* nullable */ String[] instructionSets; 9084 9085 InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 9086 int flags, String installerPackageName, ManifestDigest manifestDigest, 9087 UserHandle user, String[] instructionSets, 9088 String abiOverride, boolean multiArch) { 9089 this.originFile = originFile; 9090 this.originStaged = originStaged; 9091 this.flags = flags; 9092 this.observer = observer; 9093 this.installerPackageName = installerPackageName; 9094 this.manifestDigest = manifestDigest; 9095 this.user = user; 9096 this.instructionSets = instructionSets; 9097 this.abiOverride = abiOverride; 9098 this.multiArch = multiArch; 9099 } 9100 9101 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9102 abstract int doPreInstall(int status); 9103 9104 /** 9105 * Rename package into final resting place. All paths on the given 9106 * scanned package should be updated to reflect the rename. 9107 */ 9108 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9109 abstract int doPostInstall(int status, int uid); 9110 9111 /** @see PackageSettingBase#codePathString */ 9112 abstract String getCodePath(); 9113 /** @see PackageSettingBase#resourcePathString */ 9114 abstract String getResourcePath(); 9115 abstract String getLegacyNativeLibraryPath(); 9116 9117 // Need installer lock especially for dex file removal. 9118 abstract void cleanUpResourcesLI(); 9119 abstract boolean doPostDeleteLI(boolean delete); 9120 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9121 9122 /** 9123 * Called before the source arguments are copied. This is used mostly 9124 * for MoveParams when it needs to read the source file to put it in the 9125 * destination. 9126 */ 9127 int doPreCopy() { 9128 return PackageManager.INSTALL_SUCCEEDED; 9129 } 9130 9131 /** 9132 * Called after the source arguments are copied. This is used mostly for 9133 * MoveParams when it needs to read the source file to put it in the 9134 * destination. 9135 * 9136 * @return 9137 */ 9138 int doPostCopy(int uid) { 9139 return PackageManager.INSTALL_SUCCEEDED; 9140 } 9141 9142 protected boolean isFwdLocked() { 9143 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9144 } 9145 9146 UserHandle getUser() { 9147 return user; 9148 } 9149 } 9150 9151 /** 9152 * Logic to handle installation of non-ASEC applications, including copying 9153 * and renaming logic. 9154 */ 9155 class FileInstallArgs extends InstallArgs { 9156 private File codeFile; 9157 private File resourceFile; 9158 private File legacyNativeLibraryPath; 9159 9160 // Example topology: 9161 // /data/app/com.example/base.apk 9162 // /data/app/com.example/split_foo.apk 9163 // /data/app/com.example/lib/arm/libfoo.so 9164 // /data/app/com.example/lib/arm64/libfoo.so 9165 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9166 9167 /** New install */ 9168 FileInstallArgs(InstallParams params) { 9169 super(params.originFile, params.originStaged, params.observer, params.flags, 9170 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9171 null /* instruction sets */, params.packageAbiOverride, 9172 params.multiArch); 9173 if (isFwdLocked()) { 9174 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9175 } 9176 } 9177 9178 /** Existing install */ 9179 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9180 String[] instructionSets, boolean isMultiArch) { 9181 super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch); 9182 this.codeFile = (codePath != null) ? new File(codePath) : null; 9183 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9184 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9185 new File(legacyNativeLibraryPath) : null; 9186 } 9187 9188 /** New install from existing */ 9189 FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) { 9190 super(originFile, false, null, 0, null, null, null, instructionSets, null, 9191 isMultiArch); 9192 } 9193 9194 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9195 final long lowThreshold; 9196 9197 final DeviceStorageMonitorInternal 9198 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9199 if (dsm == null) { 9200 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9201 lowThreshold = 0L; 9202 } else { 9203 if (dsm.isMemoryLow()) { 9204 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9205 return false; 9206 } 9207 9208 lowThreshold = dsm.getMemoryLowThreshold(); 9209 } 9210 9211 return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9212 lowThreshold); 9213 } 9214 9215 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9216 int ret = PackageManager.INSTALL_SUCCEEDED; 9217 9218 if (originStaged) { 9219 Slog.d(TAG, originFile + " already staged; skipping copy"); 9220 codeFile = originFile; 9221 resourceFile = originFile; 9222 } else { 9223 try { 9224 final File tempDir = mInstallerService.allocateSessionDir(); 9225 codeFile = tempDir; 9226 resourceFile = tempDir; 9227 } catch (IOException e) { 9228 Slog.w(TAG, "Failed to create copy file: " + e); 9229 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9230 } 9231 9232 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9233 @Override 9234 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9235 if (!FileUtils.isValidExtFilename(name)) { 9236 throw new IllegalArgumentException("Invalid filename: " + name); 9237 } 9238 try { 9239 final File file = new File(codeFile, name); 9240 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9241 O_RDWR | O_CREAT, 0644); 9242 Os.chmod(file.getAbsolutePath(), 0644); 9243 return new ParcelFileDescriptor(fd); 9244 } catch (ErrnoException e) { 9245 throw new RemoteException("Failed to open: " + e.getMessage()); 9246 } 9247 } 9248 }; 9249 9250 ret = imcs.copyPackage(originFile.getAbsolutePath(), target); 9251 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9252 Slog.e(TAG, "Failed to copy package"); 9253 return ret; 9254 } 9255 } 9256 9257 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9258 NativeLibraryHelper.Handle handle = null; 9259 try { 9260 handle = NativeLibraryHelper.Handle.create(codeFile); 9261 if (multiArch) { 9262 // Warn if we've set an abiOverride for multi-lib packages.. 9263 // By definition, we need to copy both 32 and 64 bit libraries for 9264 // such packages. 9265 if (abiOverride != null) { 9266 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9267 } 9268 9269 int copyRet = PackageManager.NO_NATIVE_LIBRARIES; 9270 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9271 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9272 Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */); 9273 maybeThrowExceptionForMultiArchCopy("Failure copying 32 bit native libraries", copyRet); 9274 } 9275 9276 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9277 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9278 Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */); 9279 maybeThrowExceptionForMultiArchCopy("Failure copying 64 bit native libraries", copyRet); 9280 } 9281 } else { 9282 String[] abiList = (abiOverride != null) ? 9283 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 9284 9285 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null && 9286 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9287 abiList = Build.SUPPORTED_32_BIT_ABIS; 9288 } 9289 9290 int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList, 9291 true /* use isa specific subdirs */); 9292 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9293 Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]"); 9294 return copyRet; 9295 } 9296 } 9297 } catch (IOException e) { 9298 Slog.e(TAG, "Copying native libraries failed", e); 9299 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9300 } catch (PackageManagerException pme) { 9301 Slog.e(TAG, "Copying native libraries failed", pme); 9302 ret = pme.error; 9303 } finally { 9304 IoUtils.closeQuietly(handle); 9305 } 9306 9307 return ret; 9308 } 9309 9310 int doPreInstall(int status) { 9311 if (status != PackageManager.INSTALL_SUCCEEDED) { 9312 cleanUp(); 9313 } 9314 return status; 9315 } 9316 9317 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9318 if (status != PackageManager.INSTALL_SUCCEEDED) { 9319 cleanUp(); 9320 return false; 9321 } else { 9322 final File beforeCodeFile = codeFile; 9323 final File afterCodeFile = getNextCodePath(pkg.packageName); 9324 9325 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9326 try { 9327 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9328 } catch (ErrnoException e) { 9329 Slog.d(TAG, "Failed to rename", e); 9330 return false; 9331 } 9332 9333 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9334 Slog.d(TAG, "Failed to restorecon"); 9335 return false; 9336 } 9337 9338 // Reflect the rename internally 9339 codeFile = afterCodeFile; 9340 resourceFile = afterCodeFile; 9341 9342 // Reflect the rename in scanned details 9343 pkg.codePath = afterCodeFile.getAbsolutePath(); 9344 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9345 pkg.baseCodePath); 9346 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9347 pkg.splitCodePaths); 9348 9349 // Reflect the rename in app info 9350 pkg.applicationInfo.setCodePath(pkg.codePath); 9351 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9352 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9353 pkg.applicationInfo.setResourcePath(pkg.codePath); 9354 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9355 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9356 9357 return true; 9358 } 9359 } 9360 9361 int doPostInstall(int status, int uid) { 9362 if (status != PackageManager.INSTALL_SUCCEEDED) { 9363 cleanUp(); 9364 } 9365 return status; 9366 } 9367 9368 @Override 9369 String getCodePath() { 9370 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9371 } 9372 9373 @Override 9374 String getResourcePath() { 9375 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9376 } 9377 9378 @Override 9379 String getLegacyNativeLibraryPath() { 9380 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9381 } 9382 9383 private boolean cleanUp() { 9384 if (codeFile == null || !codeFile.exists()) { 9385 return false; 9386 } 9387 9388 if (codeFile.isDirectory()) { 9389 FileUtils.deleteContents(codeFile); 9390 } 9391 codeFile.delete(); 9392 9393 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9394 resourceFile.delete(); 9395 } 9396 9397 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9398 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9399 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9400 } 9401 legacyNativeLibraryPath.delete(); 9402 } 9403 9404 return true; 9405 } 9406 9407 void cleanUpResourcesLI() { 9408 // Try enumerating all code paths before deleting 9409 List<String> allCodePaths = Collections.EMPTY_LIST; 9410 if (codeFile != null && codeFile.exists()) { 9411 try { 9412 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9413 allCodePaths = pkg.getAllCodePaths(); 9414 } catch (PackageParserException e) { 9415 // Ignored; we tried our best 9416 } 9417 } 9418 9419 cleanUp(); 9420 9421 if (!allCodePaths.isEmpty()) { 9422 if (instructionSets == null) { 9423 throw new IllegalStateException("instructionSet == null"); 9424 } 9425 9426 for (String codePath : allCodePaths) { 9427 for (String instructionSet : instructionSets) { 9428 int retCode = mInstaller.rmdex(codePath, instructionSet); 9429 if (retCode < 0) { 9430 Slog.w(TAG, "Couldn't remove dex file for package: " 9431 + " at location " + codePath + ", retcode=" + retCode); 9432 // we don't consider this to be a failure of the core package deletion 9433 } 9434 } 9435 } 9436 } 9437 } 9438 9439 boolean doPostDeleteLI(boolean delete) { 9440 // XXX err, shouldn't we respect the delete flag? 9441 cleanUpResourcesLI(); 9442 return true; 9443 } 9444 } 9445 9446 private boolean isAsecExternal(String cid) { 9447 final String asecPath = PackageHelper.getSdFilesystem(cid); 9448 return !asecPath.startsWith(mAsecInternalPath); 9449 } 9450 9451 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9452 PackageManagerException { 9453 if (copyRet < 0) { 9454 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9455 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9456 throw new PackageManagerException(copyRet, message); 9457 } 9458 } 9459 } 9460 9461 /** 9462 * Extract the MountService "container ID" from the full code path of an 9463 * .apk. 9464 */ 9465 static String cidFromCodePath(String fullCodePath) { 9466 int eidx = fullCodePath.lastIndexOf("/"); 9467 String subStr1 = fullCodePath.substring(0, eidx); 9468 int sidx = subStr1.lastIndexOf("/"); 9469 return subStr1.substring(sidx+1, eidx); 9470 } 9471 9472 /** 9473 * Logic to handle installation of ASEC applications, including copying and 9474 * renaming logic. 9475 */ 9476 class AsecInstallArgs extends InstallArgs { 9477 // TODO: teach about handling cluster directories 9478 9479 static final String RES_FILE_NAME = "pkg.apk"; 9480 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9481 9482 String cid; 9483 String packagePath; 9484 String resourcePath; 9485 String legacyNativeLibraryDir; 9486 9487 /** New install */ 9488 AsecInstallArgs(InstallParams params) { 9489 super(params.originFile, params.originStaged, params.observer, params.flags, 9490 params.installerPackageName, params.getManifestDigest(), 9491 params.getUser(), null /* instruction sets */, 9492 params.packageAbiOverride, params.multiArch); 9493 } 9494 9495 /** Existing install */ 9496 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9497 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9498 super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9499 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9500 instructionSets, null, isMultiArch); 9501 // Extract cid from fullCodePath 9502 int eidx = fullCodePath.lastIndexOf("/"); 9503 String subStr1 = fullCodePath.substring(0, eidx); 9504 int sidx = subStr1.lastIndexOf("/"); 9505 cid = subStr1.substring(sidx+1, eidx); 9506 setCachePath(subStr1); 9507 } 9508 9509 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked, 9510 boolean isMultiArch) { 9511 super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9512 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9513 instructionSets, null, isMultiArch); 9514 this.cid = cid; 9515 setCachePath(PackageHelper.getSdDir(cid)); 9516 } 9517 9518 /** New install from existing */ 9519 AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets, 9520 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9521 super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9522 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9523 instructionSets, null, isMultiArch); 9524 this.cid = cid; 9525 } 9526 9527 void createCopyFile() { 9528 cid = getTempContainerId(); 9529 } 9530 9531 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9532 return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9533 abiOverride); 9534 } 9535 9536 private final boolean isExternal() { 9537 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9538 } 9539 9540 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9541 if (temp) { 9542 createCopyFile(); 9543 } else { 9544 /* 9545 * Pre-emptively destroy the container since it's destroyed if 9546 * copying fails due to it existing anyway. 9547 */ 9548 PackageHelper.destroySdDir(cid); 9549 } 9550 9551 final String newCachePath = imcs.copyPackageToContainer( 9552 originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9553 isFwdLocked(), abiOverride); 9554 9555 if (newCachePath != null) { 9556 setCachePath(newCachePath); 9557 return PackageManager.INSTALL_SUCCEEDED; 9558 } else { 9559 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9560 } 9561 } 9562 9563 @Override 9564 String getCodePath() { 9565 return packagePath; 9566 } 9567 9568 @Override 9569 String getResourcePath() { 9570 return resourcePath; 9571 } 9572 9573 @Override 9574 String getLegacyNativeLibraryPath() { 9575 return legacyNativeLibraryDir; 9576 } 9577 9578 int doPreInstall(int status) { 9579 if (status != PackageManager.INSTALL_SUCCEEDED) { 9580 // Destroy container 9581 PackageHelper.destroySdDir(cid); 9582 } else { 9583 boolean mounted = PackageHelper.isContainerMounted(cid); 9584 if (!mounted) { 9585 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9586 Process.SYSTEM_UID); 9587 if (newCachePath != null) { 9588 setCachePath(newCachePath); 9589 } else { 9590 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9591 } 9592 } 9593 } 9594 return status; 9595 } 9596 9597 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9598 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9599 String newCachePath = null; 9600 if (PackageHelper.isContainerMounted(cid)) { 9601 // Unmount the container 9602 if (!PackageHelper.unMountSdDir(cid)) { 9603 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9604 return false; 9605 } 9606 } 9607 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9608 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9609 " which might be stale. Will try to clean up."); 9610 // Clean up the stale container and proceed to recreate. 9611 if (!PackageHelper.destroySdDir(newCacheId)) { 9612 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9613 return false; 9614 } 9615 // Successfully cleaned up stale container. Try to rename again. 9616 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9617 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9618 + " inspite of cleaning it up."); 9619 return false; 9620 } 9621 } 9622 if (!PackageHelper.isContainerMounted(newCacheId)) { 9623 Slog.w(TAG, "Mounting container " + newCacheId); 9624 newCachePath = PackageHelper.mountSdDir(newCacheId, 9625 getEncryptKey(), Process.SYSTEM_UID); 9626 } else { 9627 newCachePath = PackageHelper.getSdDir(newCacheId); 9628 } 9629 if (newCachePath == null) { 9630 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9631 return false; 9632 } 9633 Log.i(TAG, "Succesfully renamed " + cid + 9634 " to " + newCacheId + 9635 " at new path: " + newCachePath); 9636 cid = newCacheId; 9637 setCachePath(newCachePath); 9638 9639 // TODO: extend to support split APKs 9640 pkg.codePath = getCodePath(); 9641 pkg.baseCodePath = getCodePath(); 9642 pkg.splitCodePaths = null; 9643 9644 pkg.applicationInfo.setCodePath(getCodePath()); 9645 pkg.applicationInfo.setBaseCodePath(getCodePath()); 9646 pkg.applicationInfo.setSplitCodePaths(null); 9647 pkg.applicationInfo.setResourcePath(getResourcePath()); 9648 pkg.applicationInfo.setBaseResourcePath(getResourcePath()); 9649 pkg.applicationInfo.setSplitResourcePaths(null); 9650 9651 return true; 9652 } 9653 9654 private void setCachePath(String newCachePath) { 9655 File cachePath = new File(newCachePath); 9656 legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath(); 9657 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9658 9659 if (isFwdLocked()) { 9660 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9661 } else { 9662 resourcePath = packagePath; 9663 } 9664 } 9665 9666 int doPostInstall(int status, int uid) { 9667 if (status != PackageManager.INSTALL_SUCCEEDED) { 9668 cleanUp(); 9669 } else { 9670 final int groupOwner; 9671 final String protectedFile; 9672 if (isFwdLocked()) { 9673 groupOwner = UserHandle.getSharedAppGid(uid); 9674 protectedFile = RES_FILE_NAME; 9675 } else { 9676 groupOwner = -1; 9677 protectedFile = null; 9678 } 9679 9680 if (uid < Process.FIRST_APPLICATION_UID 9681 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9682 Slog.e(TAG, "Failed to finalize " + cid); 9683 PackageHelper.destroySdDir(cid); 9684 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9685 } 9686 9687 boolean mounted = PackageHelper.isContainerMounted(cid); 9688 if (!mounted) { 9689 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9690 } 9691 } 9692 return status; 9693 } 9694 9695 private void cleanUp() { 9696 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9697 9698 // Destroy secure container 9699 PackageHelper.destroySdDir(cid); 9700 } 9701 9702 void cleanUpResourcesLI() { 9703 String sourceFile = getCodePath(); 9704 // Remove dex file 9705 if (instructionSets == null) { 9706 throw new IllegalStateException("instructionSet == null"); 9707 } 9708 for (String instructionSet : instructionSets) { 9709 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9710 if (retCode < 0) { 9711 Slog.w(TAG, "Couldn't remove dex file for package: " 9712 + " at location " 9713 + sourceFile.toString() + ", retcode=" + retCode); 9714 // we don't consider this to be a failure of the core package deletion 9715 } 9716 } 9717 cleanUp(); 9718 } 9719 9720 boolean matchContainer(String app) { 9721 if (cid.startsWith(app)) { 9722 return true; 9723 } 9724 return false; 9725 } 9726 9727 String getPackageName() { 9728 return getAsecPackageName(cid); 9729 } 9730 9731 boolean doPostDeleteLI(boolean delete) { 9732 boolean ret = false; 9733 boolean mounted = PackageHelper.isContainerMounted(cid); 9734 if (mounted) { 9735 // Unmount first 9736 ret = PackageHelper.unMountSdDir(cid); 9737 } 9738 if (ret && delete) { 9739 cleanUpResourcesLI(); 9740 } 9741 return ret; 9742 } 9743 9744 @Override 9745 int doPreCopy() { 9746 if (isFwdLocked()) { 9747 if (!PackageHelper.fixSdPermissions(cid, 9748 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9749 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9750 } 9751 } 9752 9753 return PackageManager.INSTALL_SUCCEEDED; 9754 } 9755 9756 @Override 9757 int doPostCopy(int uid) { 9758 if (isFwdLocked()) { 9759 if (uid < Process.FIRST_APPLICATION_UID 9760 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9761 RES_FILE_NAME)) { 9762 Slog.e(TAG, "Failed to finalize " + cid); 9763 PackageHelper.destroySdDir(cid); 9764 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9765 } 9766 } 9767 9768 return PackageManager.INSTALL_SUCCEEDED; 9769 } 9770 } 9771 9772 static String getAsecPackageName(String packageCid) { 9773 int idx = packageCid.lastIndexOf("-"); 9774 if (idx == -1) { 9775 return packageCid; 9776 } 9777 return packageCid.substring(0, idx); 9778 } 9779 9780 // Utility method used to create code paths based on package name and available index. 9781 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9782 String idxStr = ""; 9783 int idx = 1; 9784 // Fall back to default value of idx=1 if prefix is not 9785 // part of oldCodePath 9786 if (oldCodePath != null) { 9787 String subStr = oldCodePath; 9788 // Drop the suffix right away 9789 if (suffix != null && subStr.endsWith(suffix)) { 9790 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9791 } 9792 // If oldCodePath already contains prefix find out the 9793 // ending index to either increment or decrement. 9794 int sidx = subStr.lastIndexOf(prefix); 9795 if (sidx != -1) { 9796 subStr = subStr.substring(sidx + prefix.length()); 9797 if (subStr != null) { 9798 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9799 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9800 } 9801 try { 9802 idx = Integer.parseInt(subStr); 9803 if (idx <= 1) { 9804 idx++; 9805 } else { 9806 idx--; 9807 } 9808 } catch(NumberFormatException e) { 9809 } 9810 } 9811 } 9812 } 9813 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9814 return prefix + idxStr; 9815 } 9816 9817 private File getNextCodePath(String packageName) { 9818 int suffix = 1; 9819 File result; 9820 do { 9821 result = new File(mAppInstallDir, packageName + "-" + suffix); 9822 suffix++; 9823 } while (result.exists()); 9824 return result; 9825 } 9826 9827 // Utility method used to ignore ADD/REMOVE events 9828 // by directory observer. 9829 private static boolean ignoreCodePath(String fullPathStr) { 9830 String apkName = deriveCodePathName(fullPathStr); 9831 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9832 if (idx != -1 && ((idx+1) < apkName.length())) { 9833 // Make sure the package ends with a numeral 9834 String version = apkName.substring(idx+1); 9835 try { 9836 Integer.parseInt(version); 9837 return true; 9838 } catch (NumberFormatException e) {} 9839 } 9840 return false; 9841 } 9842 9843 // Utility method that returns the relative package path with respect 9844 // to the installation directory. Like say for /data/data/com.test-1.apk 9845 // string com.test-1 is returned. 9846 static String deriveCodePathName(String codePath) { 9847 if (codePath == null) { 9848 return null; 9849 } 9850 final File codeFile = new File(codePath); 9851 final String name = codeFile.getName(); 9852 if (codeFile.isDirectory()) { 9853 return name; 9854 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9855 final int lastDot = name.lastIndexOf('.'); 9856 return name.substring(0, lastDot); 9857 } else { 9858 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9859 return null; 9860 } 9861 } 9862 9863 class PackageInstalledInfo { 9864 String name; 9865 int uid; 9866 // The set of users that originally had this package installed. 9867 int[] origUsers; 9868 // The set of users that now have this package installed. 9869 int[] newUsers; 9870 PackageParser.Package pkg; 9871 int returnCode; 9872 String returnMsg; 9873 PackageRemovedInfo removedInfo; 9874 9875 public void setError(int code, String msg) { 9876 returnCode = code; 9877 returnMsg = msg; 9878 Slog.w(TAG, msg); 9879 } 9880 9881 public void setError(String msg, PackageParserException e) { 9882 returnCode = e.error; 9883 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9884 Slog.w(TAG, msg, e); 9885 } 9886 9887 public void setError(String msg, PackageManagerException e) { 9888 returnCode = e.error; 9889 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9890 Slog.w(TAG, msg, e); 9891 } 9892 9893 // In some error cases we want to convey more info back to the observer 9894 String origPackage; 9895 String origPermission; 9896 } 9897 9898 /* 9899 * Install a non-existing package. 9900 */ 9901 private void installNewPackageLI(PackageParser.Package pkg, 9902 int parseFlags, int scanMode, UserHandle user, 9903 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9904 // Remember this for later, in case we need to rollback this install 9905 String pkgName = pkg.packageName; 9906 9907 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9908 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9909 synchronized(mPackages) { 9910 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9911 // A package with the same name is already installed, though 9912 // it has been renamed to an older name. The package we 9913 // are trying to install should be installed as an update to 9914 // the existing one, but that has not been requested, so bail. 9915 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9916 + " without first uninstalling package running as " 9917 + mSettings.mRenamedPackages.get(pkgName)); 9918 return; 9919 } 9920 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9921 // Don't allow installation over an existing package with the same name. 9922 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9923 + " without first uninstalling."); 9924 return; 9925 } 9926 } 9927 9928 try { 9929 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9930 System.currentTimeMillis(), user, abiOverride); 9931 9932 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9933 // delete the partially installed application. the data directory will have to be 9934 // restored if it was already existing 9935 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9936 // remove package from internal structures. Note that we want deletePackageX to 9937 // delete the package data and cache directories that it created in 9938 // scanPackageLocked, unless those directories existed before we even tried to 9939 // install. 9940 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9941 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9942 res.removedInfo, true); 9943 } 9944 9945 } catch (PackageManagerException e) { 9946 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9947 } 9948 } 9949 9950 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9951 // Upgrade keysets are being used. Determine if new package has a superset of the 9952 // required keys. 9953 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9954 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9955 for (int i = 0; i < upgradeKeySets.length; i++) { 9956 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9957 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9958 return true; 9959 } 9960 } 9961 return false; 9962 } 9963 9964 private void replacePackageLI(PackageParser.Package pkg, 9965 int parseFlags, int scanMode, UserHandle user, 9966 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9967 PackageParser.Package oldPackage; 9968 String pkgName = pkg.packageName; 9969 int[] allUsers; 9970 boolean[] perUserInstalled; 9971 9972 // First find the old package info and check signatures 9973 synchronized(mPackages) { 9974 oldPackage = mPackages.get(pkgName); 9975 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9976 PackageSetting ps = mSettings.mPackages.get(pkgName); 9977 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9978 // default to original signature matching 9979 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9980 != PackageManager.SIGNATURE_MATCH) { 9981 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9982 "New package has a different signature: " + pkgName); 9983 return; 9984 } 9985 } else { 9986 if(!checkUpgradeKeySetLP(ps, pkg)) { 9987 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9988 "New package not signed by keys specified by upgrade-keysets: " 9989 + pkgName); 9990 return; 9991 } 9992 } 9993 9994 // In case of rollback, remember per-user/profile install state 9995 allUsers = sUserManager.getUserIds(); 9996 perUserInstalled = new boolean[allUsers.length]; 9997 for (int i = 0; i < allUsers.length; i++) { 9998 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9999 } 10000 } 10001 10002 // Nuke any cached code 10003 deleteCodeCacheDirsLI(pkgName); 10004 10005 boolean sysPkg = (isSystemApp(oldPackage)); 10006 if (sysPkg) { 10007 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10008 user, allUsers, perUserInstalled, installerPackageName, res, 10009 abiOverride); 10010 } else { 10011 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10012 user, allUsers, perUserInstalled, installerPackageName, res, 10013 abiOverride); 10014 } 10015 } 10016 10017 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10018 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10019 int[] allUsers, boolean[] perUserInstalled, 10020 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10021 String pkgName = deletedPackage.packageName; 10022 boolean deletedPkg = true; 10023 boolean updatedSettings = false; 10024 10025 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10026 + deletedPackage); 10027 long origUpdateTime; 10028 if (pkg.mExtras != null) { 10029 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10030 } else { 10031 origUpdateTime = 0; 10032 } 10033 10034 // First delete the existing package while retaining the data directory 10035 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10036 res.removedInfo, true)) { 10037 // If the existing package wasn't successfully deleted 10038 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10039 deletedPkg = false; 10040 } else { 10041 // Successfully deleted the old package. Now proceed with re-installation 10042 try { 10043 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10044 scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user, abiOverride); 10045 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10046 updatedSettings = true; 10047 } catch (PackageManagerException e) { 10048 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10049 } 10050 } 10051 10052 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10053 // remove package from internal structures. Note that we want deletePackageX to 10054 // delete the package data and cache directories that it created in 10055 // scanPackageLocked, unless those directories existed before we even tried to 10056 // install. 10057 if(updatedSettings) { 10058 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10059 deletePackageLI( 10060 pkgName, null, true, allUsers, perUserInstalled, 10061 PackageManager.DELETE_KEEP_DATA, 10062 res.removedInfo, true); 10063 } 10064 // Since we failed to install the new package we need to restore the old 10065 // package that we deleted. 10066 if (deletedPkg) { 10067 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10068 File restoreFile = new File(deletedPackage.codePath); 10069 // Parse old package 10070 boolean oldOnSd = isExternal(deletedPackage); 10071 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10072 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10073 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10074 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 10075 | SCAN_UPDATE_TIME; 10076 try { 10077 scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null, 10078 null); 10079 } catch (PackageManagerException e) { 10080 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10081 + e.getMessage()); 10082 return; 10083 } 10084 // Restore of old package succeeded. Update permissions. 10085 // writer 10086 synchronized (mPackages) { 10087 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10088 UPDATE_PERMISSIONS_ALL); 10089 // can downgrade to reader 10090 mSettings.writeLPr(); 10091 } 10092 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10093 } 10094 } 10095 } 10096 10097 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10098 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10099 int[] allUsers, boolean[] perUserInstalled, 10100 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10101 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10102 + ", old=" + deletedPackage); 10103 boolean updatedSettings = false; 10104 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 10105 PackageParser.PARSE_IS_SYSTEM; 10106 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10107 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10108 } 10109 String packageName = deletedPackage.packageName; 10110 if (packageName == null) { 10111 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10112 "Attempt to delete null packageName."); 10113 return; 10114 } 10115 PackageParser.Package oldPkg; 10116 PackageSetting oldPkgSetting; 10117 // reader 10118 synchronized (mPackages) { 10119 oldPkg = mPackages.get(packageName); 10120 oldPkgSetting = mSettings.mPackages.get(packageName); 10121 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10122 (oldPkgSetting == null)) { 10123 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10124 "Couldn't find package:" + packageName + " information"); 10125 return; 10126 } 10127 } 10128 10129 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10130 10131 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10132 res.removedInfo.removedPackage = packageName; 10133 // Remove existing system package 10134 removePackageLI(oldPkgSetting, true); 10135 // writer 10136 synchronized (mPackages) { 10137 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10138 // We didn't need to disable the .apk as a current system package, 10139 // which means we are replacing another update that is already 10140 // installed. We need to make sure to delete the older one's .apk. 10141 res.removedInfo.args = createInstallArgsForExisting(0, 10142 deletedPackage.applicationInfo.getCodePath(), 10143 deletedPackage.applicationInfo.getResourcePath(), 10144 deletedPackage.applicationInfo.nativeLibraryRootDir, 10145 getAppDexInstructionSets(deletedPackage.applicationInfo), 10146 isMultiArch(deletedPackage.applicationInfo)); 10147 } else { 10148 res.removedInfo.args = null; 10149 } 10150 } 10151 10152 // Successfully disabled the old package. Now proceed with re-installation 10153 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10154 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10155 10156 PackageParser.Package newPackage = null; 10157 try { 10158 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride); 10159 if (newPackage.mExtras != null) { 10160 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10161 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10162 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10163 10164 // is the update attempting to change shared user? that isn't going to work... 10165 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10166 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10167 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10168 + " to " + newPkgSetting.sharedUser); 10169 updatedSettings = true; 10170 } 10171 } 10172 10173 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10174 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10175 updatedSettings = true; 10176 } 10177 10178 } catch (PackageManagerException e) { 10179 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10180 } 10181 10182 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10183 // Re installation failed. Restore old information 10184 // Remove new pkg information 10185 if (newPackage != null) { 10186 removeInstalledPackageLI(newPackage, true); 10187 } 10188 // Add back the old system package 10189 try { 10190 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, 10191 null); 10192 } catch (PackageManagerException e) { 10193 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10194 } 10195 // Restore the old system information in Settings 10196 synchronized(mPackages) { 10197 if (updatedSettings) { 10198 mSettings.enableSystemPackageLPw(packageName); 10199 mSettings.setInstallerPackageName(packageName, 10200 oldPkgSetting.installerPackageName); 10201 } 10202 mSettings.writeLPr(); 10203 } 10204 } 10205 } 10206 10207 // Utility method used to move dex files during install. 10208 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10209 // TODO: extend to move split APK dex files 10210 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10211 final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo); 10212 for (String instructionSet : instructionSets) { 10213 int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath, 10214 instructionSet); 10215 if (retCode != 0) { 10216 /* 10217 * Programs may be lazily run through dexopt, so the 10218 * source may not exist. However, something seems to 10219 * have gone wrong, so note that dexopt needs to be 10220 * run again and remove the source file. In addition, 10221 * remove the target to make sure there isn't a stale 10222 * file from a previous version of the package. 10223 */ 10224 newPackage.mDexOptNeeded = true; 10225 mInstaller.rmdex(oldCodePath, instructionSet); 10226 mInstaller.rmdex(newPackage.baseCodePath, instructionSet); 10227 } 10228 } 10229 } 10230 return PackageManager.INSTALL_SUCCEEDED; 10231 } 10232 10233 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10234 int[] allUsers, boolean[] perUserInstalled, 10235 PackageInstalledInfo res) { 10236 String pkgName = newPackage.packageName; 10237 synchronized (mPackages) { 10238 //write settings. the installStatus will be incomplete at this stage. 10239 //note that the new package setting would have already been 10240 //added to mPackages. It hasn't been persisted yet. 10241 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10242 mSettings.writeLPr(); 10243 } 10244 10245 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10246 10247 synchronized (mPackages) { 10248 updatePermissionsLPw(newPackage.packageName, newPackage, 10249 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10250 ? UPDATE_PERMISSIONS_ALL : 0)); 10251 // For system-bundled packages, we assume that installing an upgraded version 10252 // of the package implies that the user actually wants to run that new code, 10253 // so we enable the package. 10254 if (isSystemApp(newPackage)) { 10255 // NB: implicit assumption that system package upgrades apply to all users 10256 if (DEBUG_INSTALL) { 10257 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10258 } 10259 PackageSetting ps = mSettings.mPackages.get(pkgName); 10260 if (ps != null) { 10261 if (res.origUsers != null) { 10262 for (int userHandle : res.origUsers) { 10263 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10264 userHandle, installerPackageName); 10265 } 10266 } 10267 // Also convey the prior install/uninstall state 10268 if (allUsers != null && perUserInstalled != null) { 10269 for (int i = 0; i < allUsers.length; i++) { 10270 if (DEBUG_INSTALL) { 10271 Slog.d(TAG, " user " + allUsers[i] 10272 + " => " + perUserInstalled[i]); 10273 } 10274 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10275 } 10276 // these install state changes will be persisted in the 10277 // upcoming call to mSettings.writeLPr(). 10278 } 10279 } 10280 } 10281 res.name = pkgName; 10282 res.uid = newPackage.applicationInfo.uid; 10283 res.pkg = newPackage; 10284 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10285 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10286 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10287 //to update install status 10288 mSettings.writeLPr(); 10289 } 10290 } 10291 10292 private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) { 10293 int pFlags = args.flags; 10294 String installerPackageName = args.installerPackageName; 10295 File tmpPackageFile = new File(args.getCodePath()); 10296 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10297 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10298 boolean replace = false; 10299 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10300 | (newInstall ? SCAN_NEW_INSTALL : 0); 10301 // Result object to be returned 10302 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10303 10304 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10305 // Retrieve PackageSettings and parse package 10306 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10307 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10308 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10309 PackageParser pp = new PackageParser(); 10310 pp.setSeparateProcesses(mSeparateProcesses); 10311 pp.setDisplayMetrics(mMetrics); 10312 10313 final PackageParser.Package pkg; 10314 try { 10315 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10316 } catch (PackageParserException e) { 10317 res.setError("Failed parse during installPackageLI", e); 10318 return; 10319 } 10320 10321 String pkgName = res.name = pkg.packageName; 10322 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10323 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10324 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10325 return; 10326 } 10327 } 10328 10329 try { 10330 pp.collectCertificates(pkg, parseFlags); 10331 pp.collectManifestDigest(pkg); 10332 } catch (PackageParserException e) { 10333 res.setError("Failed collect during installPackageLI", e); 10334 return; 10335 } 10336 10337 /* If the installer passed in a manifest digest, compare it now. */ 10338 if (args.manifestDigest != null) { 10339 if (DEBUG_INSTALL) { 10340 final String parsedManifest = pkg.manifestDigest == null ? "null" 10341 : pkg.manifestDigest.toString(); 10342 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10343 + parsedManifest); 10344 } 10345 10346 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10347 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10348 return; 10349 } 10350 } else if (DEBUG_INSTALL) { 10351 final String parsedManifest = pkg.manifestDigest == null 10352 ? "null" : pkg.manifestDigest.toString(); 10353 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10354 } 10355 10356 // Get rid of all references to package scan path via parser. 10357 pp = null; 10358 String oldCodePath = null; 10359 boolean systemApp = false; 10360 synchronized (mPackages) { 10361 // Check whether the newly-scanned package wants to define an already-defined perm 10362 int N = pkg.permissions.size(); 10363 for (int i = N-1; i >= 0; i--) { 10364 PackageParser.Permission perm = pkg.permissions.get(i); 10365 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10366 if (bp != null) { 10367 // If the defining package is signed with our cert, it's okay. This 10368 // also includes the "updating the same package" case, of course. 10369 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10370 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10371 // If the owning package is the system itself, we log but allow 10372 // install to proceed; we fail the install on all other permission 10373 // redefinitions. 10374 if (!bp.sourcePackage.equals("android")) { 10375 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10376 + pkg.packageName + " attempting to redeclare permission " 10377 + perm.info.name + " already owned by " + bp.sourcePackage); 10378 res.origPermission = perm.info.name; 10379 res.origPackage = bp.sourcePackage; 10380 return; 10381 } else { 10382 Slog.w(TAG, "Package " + pkg.packageName 10383 + " attempting to redeclare system permission " 10384 + perm.info.name + "; ignoring new declaration"); 10385 pkg.permissions.remove(i); 10386 } 10387 } 10388 } 10389 } 10390 10391 // Check if installing already existing package 10392 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10393 String oldName = mSettings.mRenamedPackages.get(pkgName); 10394 if (pkg.mOriginalPackages != null 10395 && pkg.mOriginalPackages.contains(oldName) 10396 && mPackages.containsKey(oldName)) { 10397 // This package is derived from an original package, 10398 // and this device has been updating from that original 10399 // name. We must continue using the original name, so 10400 // rename the new package here. 10401 pkg.setPackageName(oldName); 10402 pkgName = pkg.packageName; 10403 replace = true; 10404 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10405 + oldName + " pkgName=" + pkgName); 10406 } else if (mPackages.containsKey(pkgName)) { 10407 // This package, under its official name, already exists 10408 // on the device; we should replace it. 10409 replace = true; 10410 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10411 } 10412 } 10413 PackageSetting ps = mSettings.mPackages.get(pkgName); 10414 if (ps != null) { 10415 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10416 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10417 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10418 systemApp = (ps.pkg.applicationInfo.flags & 10419 ApplicationInfo.FLAG_SYSTEM) != 0; 10420 } 10421 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10422 } 10423 } 10424 10425 if (systemApp && onSd) { 10426 // Disable updates to system apps on sdcard 10427 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10428 "Cannot install updates to system apps on sdcard"); 10429 return; 10430 } 10431 10432 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10433 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10434 return; 10435 } 10436 10437 if (replace) { 10438 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10439 installerPackageName, res, args.abiOverride); 10440 } else { 10441 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10442 installerPackageName, res, args.abiOverride); 10443 } 10444 synchronized (mPackages) { 10445 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10446 if (ps != null) { 10447 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10448 } 10449 } 10450 } 10451 10452 private static boolean isForwardLocked(PackageParser.Package pkg) { 10453 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10454 } 10455 10456 private static boolean isForwardLocked(ApplicationInfo info) { 10457 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10458 } 10459 10460 private boolean isForwardLocked(PackageSetting ps) { 10461 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10462 } 10463 10464 private static boolean isMultiArch(PackageSetting ps) { 10465 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10466 } 10467 10468 private static boolean isMultiArch(ApplicationInfo info) { 10469 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10470 } 10471 10472 private static boolean isExternal(PackageParser.Package pkg) { 10473 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10474 } 10475 10476 private static boolean isExternal(PackageSetting ps) { 10477 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10478 } 10479 10480 private static boolean isExternal(ApplicationInfo info) { 10481 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10482 } 10483 10484 private static boolean isSystemApp(PackageParser.Package pkg) { 10485 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10486 } 10487 10488 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10489 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10490 } 10491 10492 private static boolean isSystemApp(ApplicationInfo info) { 10493 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10494 } 10495 10496 private static boolean isSystemApp(PackageSetting ps) { 10497 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10498 } 10499 10500 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10501 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10502 } 10503 10504 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10505 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10506 } 10507 10508 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10509 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10510 } 10511 10512 private int packageFlagsToInstallFlags(PackageSetting ps) { 10513 int installFlags = 0; 10514 if (isExternal(ps)) { 10515 installFlags |= PackageManager.INSTALL_EXTERNAL; 10516 } 10517 if (isForwardLocked(ps)) { 10518 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10519 } 10520 return installFlags; 10521 } 10522 10523 private void deleteTempPackageFiles() { 10524 final FilenameFilter filter = new FilenameFilter() { 10525 public boolean accept(File dir, String name) { 10526 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10527 } 10528 }; 10529 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10530 file.delete(); 10531 } 10532 } 10533 10534 @Override 10535 public void deletePackageAsUser(final String packageName, 10536 final IPackageDeleteObserver observer, 10537 final int userId, final int flags) { 10538 mContext.enforceCallingOrSelfPermission( 10539 android.Manifest.permission.DELETE_PACKAGES, null); 10540 final int uid = Binder.getCallingUid(); 10541 if (UserHandle.getUserId(uid) != userId) { 10542 mContext.enforceCallingPermission( 10543 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10544 "deletePackage for user " + userId); 10545 } 10546 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10547 try { 10548 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 10549 } catch (RemoteException re) { 10550 } 10551 return; 10552 } 10553 10554 boolean blocked = false; 10555 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10556 int[] users = sUserManager.getUserIds(); 10557 for (int i = 0; i < users.length; ++i) { 10558 if (getBlockUninstallForUser(packageName, users[i])) { 10559 blocked = true; 10560 break; 10561 } 10562 } 10563 } else { 10564 blocked = getBlockUninstallForUser(packageName, userId); 10565 } 10566 if (blocked) { 10567 try { 10568 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED); 10569 } catch (RemoteException re) { 10570 } 10571 return; 10572 } 10573 10574 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10575 // Queue up an async operation since the package deletion may take a little while. 10576 mHandler.post(new Runnable() { 10577 public void run() { 10578 mHandler.removeCallbacks(this); 10579 final int returnCode = deletePackageX(packageName, userId, flags); 10580 if (observer != null) { 10581 try { 10582 observer.packageDeleted(packageName, returnCode); 10583 } catch (RemoteException e) { 10584 Log.i(TAG, "Observer no longer exists."); 10585 } //end catch 10586 } //end if 10587 } //end run 10588 }); 10589 } 10590 10591 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10592 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10593 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10594 try { 10595 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10596 || dpm.isDeviceOwner(packageName))) { 10597 return true; 10598 } 10599 } catch (RemoteException e) { 10600 } 10601 return false; 10602 } 10603 10604 /** 10605 * This method is an internal method that could be get invoked either 10606 * to delete an installed package or to clean up a failed installation. 10607 * After deleting an installed package, a broadcast is sent to notify any 10608 * listeners that the package has been installed. For cleaning up a failed 10609 * installation, the broadcast is not necessary since the package's 10610 * installation wouldn't have sent the initial broadcast either 10611 * The key steps in deleting a package are 10612 * deleting the package information in internal structures like mPackages, 10613 * deleting the packages base directories through installd 10614 * updating mSettings to reflect current status 10615 * persisting settings for later use 10616 * sending a broadcast if necessary 10617 */ 10618 private int deletePackageX(String packageName, int userId, int flags) { 10619 final PackageRemovedInfo info = new PackageRemovedInfo(); 10620 final boolean res; 10621 10622 if (isPackageDeviceAdmin(packageName, userId)) { 10623 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10624 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10625 } 10626 10627 boolean removedForAllUsers = false; 10628 boolean systemUpdate = false; 10629 10630 // for the uninstall-updates case and restricted profiles, remember the per- 10631 // userhandle installed state 10632 int[] allUsers; 10633 boolean[] perUserInstalled; 10634 synchronized (mPackages) { 10635 PackageSetting ps = mSettings.mPackages.get(packageName); 10636 allUsers = sUserManager.getUserIds(); 10637 perUserInstalled = new boolean[allUsers.length]; 10638 for (int i = 0; i < allUsers.length; i++) { 10639 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10640 } 10641 } 10642 10643 synchronized (mInstallLock) { 10644 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10645 res = deletePackageLI(packageName, 10646 (flags & PackageManager.DELETE_ALL_USERS) != 0 10647 ? UserHandle.ALL : new UserHandle(userId), 10648 true, allUsers, perUserInstalled, 10649 flags | REMOVE_CHATTY, info, true); 10650 systemUpdate = info.isRemovedPackageSystemUpdate; 10651 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10652 removedForAllUsers = true; 10653 } 10654 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10655 + " removedForAllUsers=" + removedForAllUsers); 10656 } 10657 10658 if (res) { 10659 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10660 10661 // If the removed package was a system update, the old system package 10662 // was re-enabled; we need to broadcast this information 10663 if (systemUpdate) { 10664 Bundle extras = new Bundle(1); 10665 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10666 ? info.removedAppId : info.uid); 10667 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10668 10669 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10670 extras, null, null, null); 10671 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10672 extras, null, null, null); 10673 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10674 null, packageName, null, null); 10675 } 10676 } 10677 // Force a gc here. 10678 Runtime.getRuntime().gc(); 10679 // Delete the resources here after sending the broadcast to let 10680 // other processes clean up before deleting resources. 10681 if (info.args != null) { 10682 synchronized (mInstallLock) { 10683 info.args.doPostDeleteLI(true); 10684 } 10685 } 10686 10687 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10688 } 10689 10690 static class PackageRemovedInfo { 10691 String removedPackage; 10692 int uid = -1; 10693 int removedAppId = -1; 10694 int[] removedUsers = null; 10695 boolean isRemovedPackageSystemUpdate = false; 10696 // Clean up resources deleted packages. 10697 InstallArgs args = null; 10698 10699 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10700 Bundle extras = new Bundle(1); 10701 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10702 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10703 if (replacing) { 10704 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10705 } 10706 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10707 if (removedPackage != null) { 10708 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10709 extras, null, null, removedUsers); 10710 if (fullRemove && !replacing) { 10711 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10712 extras, null, null, removedUsers); 10713 } 10714 } 10715 if (removedAppId >= 0) { 10716 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10717 removedUsers); 10718 } 10719 } 10720 } 10721 10722 /* 10723 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10724 * flag is not set, the data directory is removed as well. 10725 * make sure this flag is set for partially installed apps. If not its meaningless to 10726 * delete a partially installed application. 10727 */ 10728 private void removePackageDataLI(PackageSetting ps, 10729 int[] allUserHandles, boolean[] perUserInstalled, 10730 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10731 String packageName = ps.name; 10732 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10733 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10734 // Retrieve object to delete permissions for shared user later on 10735 final PackageSetting deletedPs; 10736 // reader 10737 synchronized (mPackages) { 10738 deletedPs = mSettings.mPackages.get(packageName); 10739 if (outInfo != null) { 10740 outInfo.removedPackage = packageName; 10741 outInfo.removedUsers = deletedPs != null 10742 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10743 : null; 10744 } 10745 } 10746 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10747 removeDataDirsLI(packageName); 10748 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10749 } 10750 // writer 10751 synchronized (mPackages) { 10752 if (deletedPs != null) { 10753 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10754 if (outInfo != null) { 10755 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10756 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10757 } 10758 if (deletedPs != null) { 10759 updatePermissionsLPw(deletedPs.name, null, 0); 10760 if (deletedPs.sharedUser != null) { 10761 // remove permissions associated with package 10762 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10763 } 10764 } 10765 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10766 } 10767 // make sure to preserve per-user disabled state if this removal was just 10768 // a downgrade of a system app to the factory package 10769 if (allUserHandles != null && perUserInstalled != null) { 10770 if (DEBUG_REMOVE) { 10771 Slog.d(TAG, "Propagating install state across downgrade"); 10772 } 10773 for (int i = 0; i < allUserHandles.length; i++) { 10774 if (DEBUG_REMOVE) { 10775 Slog.d(TAG, " user " + allUserHandles[i] 10776 + " => " + perUserInstalled[i]); 10777 } 10778 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10779 } 10780 } 10781 } 10782 // can downgrade to reader 10783 if (writeSettings) { 10784 // Save settings now 10785 mSettings.writeLPr(); 10786 } 10787 } 10788 if (outInfo != null) { 10789 // A user ID was deleted here. Go through all users and remove it 10790 // from KeyStore. 10791 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10792 } 10793 } 10794 10795 static boolean locationIsPrivileged(File path) { 10796 try { 10797 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10798 .getCanonicalPath(); 10799 return path.getCanonicalPath().startsWith(privilegedAppDir); 10800 } catch (IOException e) { 10801 Slog.e(TAG, "Unable to access code path " + path); 10802 } 10803 return false; 10804 } 10805 10806 /* 10807 * Tries to delete system package. 10808 */ 10809 private boolean deleteSystemPackageLI(PackageSetting newPs, 10810 int[] allUserHandles, boolean[] perUserInstalled, 10811 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10812 final boolean applyUserRestrictions 10813 = (allUserHandles != null) && (perUserInstalled != null); 10814 PackageSetting disabledPs = null; 10815 // Confirm if the system package has been updated 10816 // An updated system app can be deleted. This will also have to restore 10817 // the system pkg from system partition 10818 // reader 10819 synchronized (mPackages) { 10820 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10821 } 10822 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10823 + " disabledPs=" + disabledPs); 10824 if (disabledPs == null) { 10825 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10826 return false; 10827 } else if (DEBUG_REMOVE) { 10828 Slog.d(TAG, "Deleting system pkg from data partition"); 10829 } 10830 if (DEBUG_REMOVE) { 10831 if (applyUserRestrictions) { 10832 Slog.d(TAG, "Remembering install states:"); 10833 for (int i = 0; i < allUserHandles.length; i++) { 10834 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10835 } 10836 } 10837 } 10838 // Delete the updated package 10839 outInfo.isRemovedPackageSystemUpdate = true; 10840 if (disabledPs.versionCode < newPs.versionCode) { 10841 // Delete data for downgrades 10842 flags &= ~PackageManager.DELETE_KEEP_DATA; 10843 } else { 10844 // Preserve data by setting flag 10845 flags |= PackageManager.DELETE_KEEP_DATA; 10846 } 10847 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10848 allUserHandles, perUserInstalled, outInfo, writeSettings); 10849 if (!ret) { 10850 return false; 10851 } 10852 // writer 10853 synchronized (mPackages) { 10854 // Reinstate the old system package 10855 mSettings.enableSystemPackageLPw(newPs.name); 10856 // Remove any native libraries from the upgraded package. 10857 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10858 } 10859 // Install the system package 10860 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10861 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10862 if (locationIsPrivileged(disabledPs.codePath)) { 10863 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10864 } 10865 10866 final PackageParser.Package newPkg; 10867 try { 10868 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, 10869 null, null); 10870 } catch (PackageManagerException e) { 10871 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10872 return false; 10873 } 10874 10875 // writer 10876 synchronized (mPackages) { 10877 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10878 setBundledAppAbisAndRoots(newPkg, ps); 10879 updatePermissionsLPw(newPkg.packageName, newPkg, 10880 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10881 if (applyUserRestrictions) { 10882 if (DEBUG_REMOVE) { 10883 Slog.d(TAG, "Propagating install state across reinstall"); 10884 } 10885 for (int i = 0; i < allUserHandles.length; i++) { 10886 if (DEBUG_REMOVE) { 10887 Slog.d(TAG, " user " + allUserHandles[i] 10888 + " => " + perUserInstalled[i]); 10889 } 10890 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10891 } 10892 // Regardless of writeSettings we need to ensure that this restriction 10893 // state propagation is persisted 10894 mSettings.writeAllUsersPackageRestrictionsLPr(); 10895 } 10896 // can downgrade to reader here 10897 if (writeSettings) { 10898 mSettings.writeLPr(); 10899 } 10900 } 10901 return true; 10902 } 10903 10904 private boolean deleteInstalledPackageLI(PackageSetting ps, 10905 boolean deleteCodeAndResources, int flags, 10906 int[] allUserHandles, boolean[] perUserInstalled, 10907 PackageRemovedInfo outInfo, boolean writeSettings) { 10908 if (outInfo != null) { 10909 outInfo.uid = ps.appId; 10910 } 10911 10912 // Delete package data from internal structures and also remove data if flag is set 10913 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10914 10915 // Delete application code and resources 10916 if (deleteCodeAndResources && (outInfo != null)) { 10917 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10918 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10919 getAppDexInstructionSets(ps), isMultiArch(ps)); 10920 } 10921 return true; 10922 } 10923 10924 @Override 10925 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10926 int userId) { 10927 mContext.enforceCallingOrSelfPermission( 10928 android.Manifest.permission.DELETE_PACKAGES, null); 10929 synchronized (mPackages) { 10930 PackageSetting ps = mSettings.mPackages.get(packageName); 10931 if (ps == null) { 10932 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10933 return false; 10934 } 10935 if (!ps.getInstalled(userId)) { 10936 // Can't block uninstall for an app that is not installed or enabled. 10937 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10938 return false; 10939 } 10940 ps.setBlockUninstall(blockUninstall, userId); 10941 mSettings.writePackageRestrictionsLPr(userId); 10942 } 10943 return true; 10944 } 10945 10946 @Override 10947 public boolean getBlockUninstallForUser(String packageName, int userId) { 10948 synchronized (mPackages) { 10949 PackageSetting ps = mSettings.mPackages.get(packageName); 10950 if (ps == null) { 10951 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10952 return false; 10953 } 10954 return ps.getBlockUninstall(userId); 10955 } 10956 } 10957 10958 /* 10959 * This method handles package deletion in general 10960 */ 10961 private boolean deletePackageLI(String packageName, UserHandle user, 10962 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10963 int flags, PackageRemovedInfo outInfo, 10964 boolean writeSettings) { 10965 if (packageName == null) { 10966 Slog.w(TAG, "Attempt to delete null packageName."); 10967 return false; 10968 } 10969 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10970 PackageSetting ps; 10971 boolean dataOnly = false; 10972 int removeUser = -1; 10973 int appId = -1; 10974 synchronized (mPackages) { 10975 ps = mSettings.mPackages.get(packageName); 10976 if (ps == null) { 10977 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10978 return false; 10979 } 10980 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10981 && user.getIdentifier() != UserHandle.USER_ALL) { 10982 // The caller is asking that the package only be deleted for a single 10983 // user. To do this, we just mark its uninstalled state and delete 10984 // its data. If this is a system app, we only allow this to happen if 10985 // they have set the special DELETE_SYSTEM_APP which requests different 10986 // semantics than normal for uninstalling system apps. 10987 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10988 ps.setUserState(user.getIdentifier(), 10989 COMPONENT_ENABLED_STATE_DEFAULT, 10990 false, //installed 10991 true, //stopped 10992 true, //notLaunched 10993 false, //blocked 10994 null, null, null, 10995 false // blockUninstall 10996 ); 10997 if (!isSystemApp(ps)) { 10998 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10999 // Other user still have this package installed, so all 11000 // we need to do is clear this user's data and save that 11001 // it is uninstalled. 11002 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11003 removeUser = user.getIdentifier(); 11004 appId = ps.appId; 11005 mSettings.writePackageRestrictionsLPr(removeUser); 11006 } else { 11007 // We need to set it back to 'installed' so the uninstall 11008 // broadcasts will be sent correctly. 11009 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11010 ps.setInstalled(true, user.getIdentifier()); 11011 } 11012 } else { 11013 // This is a system app, so we assume that the 11014 // other users still have this package installed, so all 11015 // we need to do is clear this user's data and save that 11016 // it is uninstalled. 11017 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11018 removeUser = user.getIdentifier(); 11019 appId = ps.appId; 11020 mSettings.writePackageRestrictionsLPr(removeUser); 11021 } 11022 } 11023 } 11024 11025 if (removeUser >= 0) { 11026 // From above, we determined that we are deleting this only 11027 // for a single user. Continue the work here. 11028 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11029 if (outInfo != null) { 11030 outInfo.removedPackage = packageName; 11031 outInfo.removedAppId = appId; 11032 outInfo.removedUsers = new int[] {removeUser}; 11033 } 11034 mInstaller.clearUserData(packageName, removeUser); 11035 removeKeystoreDataIfNeeded(removeUser, appId); 11036 schedulePackageCleaning(packageName, removeUser, false); 11037 return true; 11038 } 11039 11040 if (dataOnly) { 11041 // Delete application data first 11042 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11043 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11044 return true; 11045 } 11046 11047 boolean ret = false; 11048 if (isSystemApp(ps)) { 11049 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11050 // When an updated system application is deleted we delete the existing resources as well and 11051 // fall back to existing code in system partition 11052 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11053 flags, outInfo, writeSettings); 11054 } else { 11055 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11056 // Kill application pre-emptively especially for apps on sd. 11057 killApplication(packageName, ps.appId, "uninstall pkg"); 11058 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11059 allUserHandles, perUserInstalled, 11060 outInfo, writeSettings); 11061 } 11062 11063 return ret; 11064 } 11065 11066 private final class ClearStorageConnection implements ServiceConnection { 11067 IMediaContainerService mContainerService; 11068 11069 @Override 11070 public void onServiceConnected(ComponentName name, IBinder service) { 11071 synchronized (this) { 11072 mContainerService = IMediaContainerService.Stub.asInterface(service); 11073 notifyAll(); 11074 } 11075 } 11076 11077 @Override 11078 public void onServiceDisconnected(ComponentName name) { 11079 } 11080 } 11081 11082 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11083 final boolean mounted; 11084 if (Environment.isExternalStorageEmulated()) { 11085 mounted = true; 11086 } else { 11087 final String status = Environment.getExternalStorageState(); 11088 11089 mounted = status.equals(Environment.MEDIA_MOUNTED) 11090 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11091 } 11092 11093 if (!mounted) { 11094 return; 11095 } 11096 11097 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11098 int[] users; 11099 if (userId == UserHandle.USER_ALL) { 11100 users = sUserManager.getUserIds(); 11101 } else { 11102 users = new int[] { userId }; 11103 } 11104 final ClearStorageConnection conn = new ClearStorageConnection(); 11105 if (mContext.bindServiceAsUser( 11106 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11107 try { 11108 for (int curUser : users) { 11109 long timeout = SystemClock.uptimeMillis() + 5000; 11110 synchronized (conn) { 11111 long now = SystemClock.uptimeMillis(); 11112 while (conn.mContainerService == null && now < timeout) { 11113 try { 11114 conn.wait(timeout - now); 11115 } catch (InterruptedException e) { 11116 } 11117 } 11118 } 11119 if (conn.mContainerService == null) { 11120 return; 11121 } 11122 11123 final UserEnvironment userEnv = new UserEnvironment(curUser); 11124 clearDirectory(conn.mContainerService, 11125 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11126 if (allData) { 11127 clearDirectory(conn.mContainerService, 11128 userEnv.buildExternalStorageAppDataDirs(packageName)); 11129 clearDirectory(conn.mContainerService, 11130 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11131 } 11132 } 11133 } finally { 11134 mContext.unbindService(conn); 11135 } 11136 } 11137 } 11138 11139 @Override 11140 public void clearApplicationUserData(final String packageName, 11141 final IPackageDataObserver observer, final int userId) { 11142 mContext.enforceCallingOrSelfPermission( 11143 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11144 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11145 // Queue up an async operation since the package deletion may take a little while. 11146 mHandler.post(new Runnable() { 11147 public void run() { 11148 mHandler.removeCallbacks(this); 11149 final boolean succeeded; 11150 synchronized (mInstallLock) { 11151 succeeded = clearApplicationUserDataLI(packageName, userId); 11152 } 11153 clearExternalStorageDataSync(packageName, userId, true); 11154 if (succeeded) { 11155 // invoke DeviceStorageMonitor's update method to clear any notifications 11156 DeviceStorageMonitorInternal 11157 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11158 if (dsm != null) { 11159 dsm.checkMemory(); 11160 } 11161 } 11162 if(observer != null) { 11163 try { 11164 observer.onRemoveCompleted(packageName, succeeded); 11165 } catch (RemoteException e) { 11166 Log.i(TAG, "Observer no longer exists."); 11167 } 11168 } //end if observer 11169 } //end run 11170 }); 11171 } 11172 11173 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11174 if (packageName == null) { 11175 Slog.w(TAG, "Attempt to delete null packageName."); 11176 return false; 11177 } 11178 PackageParser.Package p; 11179 boolean dataOnly = false; 11180 final int appId; 11181 synchronized (mPackages) { 11182 p = mPackages.get(packageName); 11183 if (p == null) { 11184 dataOnly = true; 11185 PackageSetting ps = mSettings.mPackages.get(packageName); 11186 if ((ps == null) || (ps.pkg == null)) { 11187 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11188 return false; 11189 } 11190 p = ps.pkg; 11191 } 11192 if (!dataOnly) { 11193 // need to check this only for fully installed applications 11194 if (p == null) { 11195 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11196 return false; 11197 } 11198 final ApplicationInfo applicationInfo = p.applicationInfo; 11199 if (applicationInfo == null) { 11200 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11201 return false; 11202 } 11203 } 11204 if (p != null && p.applicationInfo != null) { 11205 appId = p.applicationInfo.uid; 11206 } else { 11207 appId = -1; 11208 } 11209 } 11210 int retCode = mInstaller.clearUserData(packageName, userId); 11211 if (retCode < 0) { 11212 Slog.w(TAG, "Couldn't remove cache files for package: " 11213 + packageName); 11214 return false; 11215 } 11216 removeKeystoreDataIfNeeded(userId, appId); 11217 return true; 11218 } 11219 11220 /** 11221 * Remove entries from the keystore daemon. Will only remove it if the 11222 * {@code appId} is valid. 11223 */ 11224 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11225 if (appId < 0) { 11226 return; 11227 } 11228 11229 final KeyStore keyStore = KeyStore.getInstance(); 11230 if (keyStore != null) { 11231 if (userId == UserHandle.USER_ALL) { 11232 for (final int individual : sUserManager.getUserIds()) { 11233 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11234 } 11235 } else { 11236 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11237 } 11238 } else { 11239 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11240 } 11241 } 11242 11243 @Override 11244 public void deleteApplicationCacheFiles(final String packageName, 11245 final IPackageDataObserver observer) { 11246 mContext.enforceCallingOrSelfPermission( 11247 android.Manifest.permission.DELETE_CACHE_FILES, null); 11248 // Queue up an async operation since the package deletion may take a little while. 11249 final int userId = UserHandle.getCallingUserId(); 11250 mHandler.post(new Runnable() { 11251 public void run() { 11252 mHandler.removeCallbacks(this); 11253 final boolean succeded; 11254 synchronized (mInstallLock) { 11255 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11256 } 11257 clearExternalStorageDataSync(packageName, userId, false); 11258 if(observer != null) { 11259 try { 11260 observer.onRemoveCompleted(packageName, succeded); 11261 } catch (RemoteException e) { 11262 Log.i(TAG, "Observer no longer exists."); 11263 } 11264 } //end if observer 11265 } //end run 11266 }); 11267 } 11268 11269 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11270 if (packageName == null) { 11271 Slog.w(TAG, "Attempt to delete null packageName."); 11272 return false; 11273 } 11274 PackageParser.Package p; 11275 synchronized (mPackages) { 11276 p = mPackages.get(packageName); 11277 } 11278 if (p == null) { 11279 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11280 return false; 11281 } 11282 final ApplicationInfo applicationInfo = p.applicationInfo; 11283 if (applicationInfo == null) { 11284 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11285 return false; 11286 } 11287 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11288 if (retCode < 0) { 11289 Slog.w(TAG, "Couldn't remove cache files for package: " 11290 + packageName + " u" + userId); 11291 return false; 11292 } 11293 return true; 11294 } 11295 11296 @Override 11297 public void getPackageSizeInfo(final String packageName, int userHandle, 11298 final IPackageStatsObserver observer) { 11299 mContext.enforceCallingOrSelfPermission( 11300 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11301 if (packageName == null) { 11302 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11303 } 11304 11305 PackageStats stats = new PackageStats(packageName, userHandle); 11306 11307 /* 11308 * Queue up an async operation since the package measurement may take a 11309 * little while. 11310 */ 11311 Message msg = mHandler.obtainMessage(INIT_COPY); 11312 msg.obj = new MeasureParams(stats, observer); 11313 mHandler.sendMessage(msg); 11314 } 11315 11316 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11317 PackageStats pStats) { 11318 if (packageName == null) { 11319 Slog.w(TAG, "Attempt to get size of null packageName."); 11320 return false; 11321 } 11322 PackageParser.Package p; 11323 boolean dataOnly = false; 11324 String libDirRoot = null; 11325 String asecPath = null; 11326 PackageSetting ps = null; 11327 synchronized (mPackages) { 11328 p = mPackages.get(packageName); 11329 ps = mSettings.mPackages.get(packageName); 11330 if(p == null) { 11331 dataOnly = true; 11332 if((ps == null) || (ps.pkg == null)) { 11333 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11334 return false; 11335 } 11336 p = ps.pkg; 11337 } 11338 if (ps != null) { 11339 libDirRoot = ps.legacyNativeLibraryPathString; 11340 } 11341 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11342 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11343 if (secureContainerId != null) { 11344 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11345 } 11346 } 11347 } 11348 String publicSrcDir = null; 11349 if(!dataOnly) { 11350 final ApplicationInfo applicationInfo = p.applicationInfo; 11351 if (applicationInfo == null) { 11352 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11353 return false; 11354 } 11355 if (isForwardLocked(p)) { 11356 publicSrcDir = applicationInfo.getBaseResourcePath(); 11357 } 11358 } 11359 // TODO: extend to measure size of split APKs 11360 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11361 // not just the first level. 11362 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11363 // just the primary. 11364 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11365 publicSrcDir, asecPath, getAppDexInstructionSets(ps), 11366 pStats); 11367 if (res < 0) { 11368 return false; 11369 } 11370 11371 // Fix-up for forward-locked applications in ASEC containers. 11372 if (!isExternal(p)) { 11373 pStats.codeSize += pStats.externalCodeSize; 11374 pStats.externalCodeSize = 0L; 11375 } 11376 11377 return true; 11378 } 11379 11380 11381 @Override 11382 public void addPackageToPreferred(String packageName) { 11383 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11384 } 11385 11386 @Override 11387 public void removePackageFromPreferred(String packageName) { 11388 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11389 } 11390 11391 @Override 11392 public List<PackageInfo> getPreferredPackages(int flags) { 11393 return new ArrayList<PackageInfo>(); 11394 } 11395 11396 private int getUidTargetSdkVersionLockedLPr(int uid) { 11397 Object obj = mSettings.getUserIdLPr(uid); 11398 if (obj instanceof SharedUserSetting) { 11399 final SharedUserSetting sus = (SharedUserSetting) obj; 11400 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11401 final Iterator<PackageSetting> it = sus.packages.iterator(); 11402 while (it.hasNext()) { 11403 final PackageSetting ps = it.next(); 11404 if (ps.pkg != null) { 11405 int v = ps.pkg.applicationInfo.targetSdkVersion; 11406 if (v < vers) vers = v; 11407 } 11408 } 11409 return vers; 11410 } else if (obj instanceof PackageSetting) { 11411 final PackageSetting ps = (PackageSetting) obj; 11412 if (ps.pkg != null) { 11413 return ps.pkg.applicationInfo.targetSdkVersion; 11414 } 11415 } 11416 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11417 } 11418 11419 @Override 11420 public void addPreferredActivity(IntentFilter filter, int match, 11421 ComponentName[] set, ComponentName activity, int userId) { 11422 addPreferredActivityInternal(filter, match, set, activity, true, userId); 11423 } 11424 11425 private void addPreferredActivityInternal(IntentFilter filter, int match, 11426 ComponentName[] set, ComponentName activity, boolean always, int userId) { 11427 // writer 11428 int callingUid = Binder.getCallingUid(); 11429 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11430 if (filter.countActions() == 0) { 11431 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11432 return; 11433 } 11434 synchronized (mPackages) { 11435 if (mContext.checkCallingOrSelfPermission( 11436 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11437 != PackageManager.PERMISSION_GRANTED) { 11438 if (getUidTargetSdkVersionLockedLPr(callingUid) 11439 < Build.VERSION_CODES.FROYO) { 11440 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11441 + callingUid); 11442 return; 11443 } 11444 mContext.enforceCallingOrSelfPermission( 11445 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11446 } 11447 11448 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 11449 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11450 mSettings.editPreferredActivitiesLPw(userId).addFilter( 11451 new PreferredActivity(filter, match, set, activity, always)); 11452 mSettings.writePackageRestrictionsLPr(userId); 11453 } 11454 } 11455 11456 @Override 11457 public void replacePreferredActivity(IntentFilter filter, int match, 11458 ComponentName[] set, ComponentName activity) { 11459 if (filter.countActions() != 1) { 11460 throw new IllegalArgumentException( 11461 "replacePreferredActivity expects filter to have only 1 action."); 11462 } 11463 if (filter.countDataAuthorities() != 0 11464 || filter.countDataPaths() != 0 11465 || filter.countDataSchemes() > 1 11466 || filter.countDataTypes() != 0) { 11467 throw new IllegalArgumentException( 11468 "replacePreferredActivity expects filter to have no data authorities, " + 11469 "paths, or types; and at most one scheme."); 11470 } 11471 synchronized (mPackages) { 11472 if (mContext.checkCallingOrSelfPermission( 11473 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11474 != PackageManager.PERMISSION_GRANTED) { 11475 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11476 < Build.VERSION_CODES.FROYO) { 11477 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11478 + Binder.getCallingUid()); 11479 return; 11480 } 11481 mContext.enforceCallingOrSelfPermission( 11482 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11483 } 11484 11485 final int callingUserId = UserHandle.getCallingUserId(); 11486 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 11487 if (pir != null) { 11488 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 11489 if (filter.countDataSchemes() == 1) { 11490 Uri.Builder builder = new Uri.Builder(); 11491 builder.scheme(filter.getDataScheme(0)); 11492 intent.setData(builder.build()); 11493 } 11494 List<PreferredActivity> matches = pir.queryIntent( 11495 intent, null, true, callingUserId); 11496 if (DEBUG_PREFERRED) { 11497 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 11498 } 11499 for (int i = 0; i < matches.size(); i++) { 11500 PreferredActivity pa = matches.get(i); 11501 if (DEBUG_PREFERRED) { 11502 Slog.i(TAG, "Removing preferred activity " 11503 + pa.mPref.mComponent + ":"); 11504 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11505 } 11506 pir.removeFilter(pa); 11507 } 11508 } 11509 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 11510 } 11511 } 11512 11513 @Override 11514 public void clearPackagePreferredActivities(String packageName) { 11515 final int uid = Binder.getCallingUid(); 11516 // writer 11517 synchronized (mPackages) { 11518 PackageParser.Package pkg = mPackages.get(packageName); 11519 if (pkg == null || pkg.applicationInfo.uid != uid) { 11520 if (mContext.checkCallingOrSelfPermission( 11521 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11522 != PackageManager.PERMISSION_GRANTED) { 11523 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11524 < Build.VERSION_CODES.FROYO) { 11525 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11526 + Binder.getCallingUid()); 11527 return; 11528 } 11529 mContext.enforceCallingOrSelfPermission( 11530 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11531 } 11532 } 11533 11534 int user = UserHandle.getCallingUserId(); 11535 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11536 mSettings.writePackageRestrictionsLPr(user); 11537 scheduleWriteSettingsLocked(); 11538 } 11539 } 11540 } 11541 11542 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11543 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11544 ArrayList<PreferredActivity> removed = null; 11545 boolean changed = false; 11546 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11547 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11548 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11549 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11550 continue; 11551 } 11552 Iterator<PreferredActivity> it = pir.filterIterator(); 11553 while (it.hasNext()) { 11554 PreferredActivity pa = it.next(); 11555 // Mark entry for removal only if it matches the package name 11556 // and the entry is of type "always". 11557 if (packageName == null || 11558 (pa.mPref.mComponent.getPackageName().equals(packageName) 11559 && pa.mPref.mAlways)) { 11560 if (removed == null) { 11561 removed = new ArrayList<PreferredActivity>(); 11562 } 11563 removed.add(pa); 11564 } 11565 } 11566 if (removed != null) { 11567 for (int j=0; j<removed.size(); j++) { 11568 PreferredActivity pa = removed.get(j); 11569 pir.removeFilter(pa); 11570 } 11571 changed = true; 11572 } 11573 } 11574 return changed; 11575 } 11576 11577 @Override 11578 public void resetPreferredActivities(int userId) { 11579 mContext.enforceCallingOrSelfPermission( 11580 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11581 // writer 11582 synchronized (mPackages) { 11583 int user = UserHandle.getCallingUserId(); 11584 clearPackagePreferredActivitiesLPw(null, user); 11585 mSettings.readDefaultPreferredAppsLPw(this, user); 11586 mSettings.writePackageRestrictionsLPr(user); 11587 scheduleWriteSettingsLocked(); 11588 } 11589 } 11590 11591 @Override 11592 public int getPreferredActivities(List<IntentFilter> outFilters, 11593 List<ComponentName> outActivities, String packageName) { 11594 11595 int num = 0; 11596 final int userId = UserHandle.getCallingUserId(); 11597 // reader 11598 synchronized (mPackages) { 11599 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11600 if (pir != null) { 11601 final Iterator<PreferredActivity> it = pir.filterIterator(); 11602 while (it.hasNext()) { 11603 final PreferredActivity pa = it.next(); 11604 if (packageName == null 11605 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11606 && pa.mPref.mAlways)) { 11607 if (outFilters != null) { 11608 outFilters.add(new IntentFilter(pa)); 11609 } 11610 if (outActivities != null) { 11611 outActivities.add(pa.mPref.mComponent); 11612 } 11613 } 11614 } 11615 } 11616 } 11617 11618 return num; 11619 } 11620 11621 @Override 11622 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11623 int userId) { 11624 int callingUid = Binder.getCallingUid(); 11625 if (callingUid != Process.SYSTEM_UID) { 11626 throw new SecurityException( 11627 "addPersistentPreferredActivity can only be run by the system"); 11628 } 11629 if (filter.countActions() == 0) { 11630 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11631 return; 11632 } 11633 synchronized (mPackages) { 11634 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11635 " :"); 11636 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11637 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11638 new PersistentPreferredActivity(filter, activity)); 11639 mSettings.writePackageRestrictionsLPr(userId); 11640 } 11641 } 11642 11643 @Override 11644 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11645 int callingUid = Binder.getCallingUid(); 11646 if (callingUid != Process.SYSTEM_UID) { 11647 throw new SecurityException( 11648 "clearPackagePersistentPreferredActivities can only be run by the system"); 11649 } 11650 ArrayList<PersistentPreferredActivity> removed = null; 11651 boolean changed = false; 11652 synchronized (mPackages) { 11653 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11654 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11655 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11656 .valueAt(i); 11657 if (userId != thisUserId) { 11658 continue; 11659 } 11660 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11661 while (it.hasNext()) { 11662 PersistentPreferredActivity ppa = it.next(); 11663 // Mark entry for removal only if it matches the package name. 11664 if (ppa.mComponent.getPackageName().equals(packageName)) { 11665 if (removed == null) { 11666 removed = new ArrayList<PersistentPreferredActivity>(); 11667 } 11668 removed.add(ppa); 11669 } 11670 } 11671 if (removed != null) { 11672 for (int j=0; j<removed.size(); j++) { 11673 PersistentPreferredActivity ppa = removed.get(j); 11674 ppir.removeFilter(ppa); 11675 } 11676 changed = true; 11677 } 11678 } 11679 11680 if (changed) { 11681 mSettings.writePackageRestrictionsLPr(userId); 11682 } 11683 } 11684 } 11685 11686 @Override 11687 public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId, 11688 int targetUserId, int flags) { 11689 mContext.enforceCallingOrSelfPermission( 11690 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11691 if (intentFilter.countActions() == 0) { 11692 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11693 return; 11694 } 11695 synchronized (mPackages) { 11696 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11697 targetUserId, flags); 11698 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11699 mSettings.writePackageRestrictionsLPr(sourceUserId); 11700 } 11701 } 11702 11703 public void addCrossProfileIntentsForPackage(String packageName, 11704 int sourceUserId, int targetUserId) { 11705 mContext.enforceCallingOrSelfPermission( 11706 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11707 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11708 mSettings.writePackageRestrictionsLPr(sourceUserId); 11709 } 11710 11711 public void removeCrossProfileIntentsForPackage(String packageName, 11712 int sourceUserId, int targetUserId) { 11713 mContext.enforceCallingOrSelfPermission( 11714 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11715 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11716 mSettings.writePackageRestrictionsLPr(sourceUserId); 11717 } 11718 11719 @Override 11720 public void clearCrossProfileIntentFilters(int sourceUserId) { 11721 mContext.enforceCallingOrSelfPermission( 11722 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11723 synchronized (mPackages) { 11724 CrossProfileIntentResolver resolver = 11725 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11726 HashSet<CrossProfileIntentFilter> set = 11727 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11728 for (CrossProfileIntentFilter filter : set) { 11729 if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) { 11730 resolver.removeFilter(filter); 11731 } 11732 } 11733 mSettings.writePackageRestrictionsLPr(sourceUserId); 11734 } 11735 } 11736 11737 @Override 11738 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11739 Intent intent = new Intent(Intent.ACTION_MAIN); 11740 intent.addCategory(Intent.CATEGORY_HOME); 11741 11742 final int callingUserId = UserHandle.getCallingUserId(); 11743 List<ResolveInfo> list = queryIntentActivities(intent, null, 11744 PackageManager.GET_META_DATA, callingUserId); 11745 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11746 true, false, false, callingUserId); 11747 11748 allHomeCandidates.clear(); 11749 if (list != null) { 11750 for (ResolveInfo ri : list) { 11751 allHomeCandidates.add(ri); 11752 } 11753 } 11754 return (preferred == null || preferred.activityInfo == null) 11755 ? null 11756 : new ComponentName(preferred.activityInfo.packageName, 11757 preferred.activityInfo.name); 11758 } 11759 11760 @Override 11761 public void setApplicationEnabledSetting(String appPackageName, 11762 int newState, int flags, int userId, String callingPackage) { 11763 if (!sUserManager.exists(userId)) return; 11764 if (callingPackage == null) { 11765 callingPackage = Integer.toString(Binder.getCallingUid()); 11766 } 11767 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11768 } 11769 11770 @Override 11771 public void setComponentEnabledSetting(ComponentName componentName, 11772 int newState, int flags, int userId) { 11773 if (!sUserManager.exists(userId)) return; 11774 setEnabledSetting(componentName.getPackageName(), 11775 componentName.getClassName(), newState, flags, userId, null); 11776 } 11777 11778 private void setEnabledSetting(final String packageName, String className, int newState, 11779 final int flags, int userId, String callingPackage) { 11780 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11781 || newState == COMPONENT_ENABLED_STATE_ENABLED 11782 || newState == COMPONENT_ENABLED_STATE_DISABLED 11783 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11784 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11785 throw new IllegalArgumentException("Invalid new component state: " 11786 + newState); 11787 } 11788 PackageSetting pkgSetting; 11789 final int uid = Binder.getCallingUid(); 11790 final int permission = mContext.checkCallingOrSelfPermission( 11791 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11792 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11793 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11794 boolean sendNow = false; 11795 boolean isApp = (className == null); 11796 String componentName = isApp ? packageName : className; 11797 int packageUid = -1; 11798 ArrayList<String> components; 11799 11800 // writer 11801 synchronized (mPackages) { 11802 pkgSetting = mSettings.mPackages.get(packageName); 11803 if (pkgSetting == null) { 11804 if (className == null) { 11805 throw new IllegalArgumentException( 11806 "Unknown package: " + packageName); 11807 } 11808 throw new IllegalArgumentException( 11809 "Unknown component: " + packageName 11810 + "/" + className); 11811 } 11812 // Allow root and verify that userId is not being specified by a different user 11813 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11814 throw new SecurityException( 11815 "Permission Denial: attempt to change component state from pid=" 11816 + Binder.getCallingPid() 11817 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11818 } 11819 if (className == null) { 11820 // We're dealing with an application/package level state change 11821 if (pkgSetting.getEnabled(userId) == newState) { 11822 // Nothing to do 11823 return; 11824 } 11825 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11826 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11827 // Don't care about who enables an app. 11828 callingPackage = null; 11829 } 11830 pkgSetting.setEnabled(newState, userId, callingPackage); 11831 // pkgSetting.pkg.mSetEnabled = newState; 11832 } else { 11833 // We're dealing with a component level state change 11834 // First, verify that this is a valid class name. 11835 PackageParser.Package pkg = pkgSetting.pkg; 11836 if (pkg == null || !pkg.hasComponentClassName(className)) { 11837 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11838 throw new IllegalArgumentException("Component class " + className 11839 + " does not exist in " + packageName); 11840 } else { 11841 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11842 + className + " does not exist in " + packageName); 11843 } 11844 } 11845 switch (newState) { 11846 case COMPONENT_ENABLED_STATE_ENABLED: 11847 if (!pkgSetting.enableComponentLPw(className, userId)) { 11848 return; 11849 } 11850 break; 11851 case COMPONENT_ENABLED_STATE_DISABLED: 11852 if (!pkgSetting.disableComponentLPw(className, userId)) { 11853 return; 11854 } 11855 break; 11856 case COMPONENT_ENABLED_STATE_DEFAULT: 11857 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11858 return; 11859 } 11860 break; 11861 default: 11862 Slog.e(TAG, "Invalid new component state: " + newState); 11863 return; 11864 } 11865 } 11866 mSettings.writePackageRestrictionsLPr(userId); 11867 components = mPendingBroadcasts.get(userId, packageName); 11868 final boolean newPackage = components == null; 11869 if (newPackage) { 11870 components = new ArrayList<String>(); 11871 } 11872 if (!components.contains(componentName)) { 11873 components.add(componentName); 11874 } 11875 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11876 sendNow = true; 11877 // Purge entry from pending broadcast list if another one exists already 11878 // since we are sending one right away. 11879 mPendingBroadcasts.remove(userId, packageName); 11880 } else { 11881 if (newPackage) { 11882 mPendingBroadcasts.put(userId, packageName, components); 11883 } 11884 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11885 // Schedule a message 11886 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11887 } 11888 } 11889 } 11890 11891 long callingId = Binder.clearCallingIdentity(); 11892 try { 11893 if (sendNow) { 11894 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11895 sendPackageChangedBroadcast(packageName, 11896 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11897 } 11898 } finally { 11899 Binder.restoreCallingIdentity(callingId); 11900 } 11901 } 11902 11903 private void sendPackageChangedBroadcast(String packageName, 11904 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11905 if (DEBUG_INSTALL) 11906 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11907 + componentNames); 11908 Bundle extras = new Bundle(4); 11909 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11910 String nameList[] = new String[componentNames.size()]; 11911 componentNames.toArray(nameList); 11912 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11913 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11914 extras.putInt(Intent.EXTRA_UID, packageUid); 11915 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11916 new int[] {UserHandle.getUserId(packageUid)}); 11917 } 11918 11919 @Override 11920 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11921 if (!sUserManager.exists(userId)) return; 11922 final int uid = Binder.getCallingUid(); 11923 final int permission = mContext.checkCallingOrSelfPermission( 11924 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11925 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11926 enforceCrossUserPermission(uid, userId, true, "stop package"); 11927 // writer 11928 synchronized (mPackages) { 11929 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11930 uid, userId)) { 11931 scheduleWritePackageRestrictionsLocked(userId); 11932 } 11933 } 11934 } 11935 11936 @Override 11937 public String getInstallerPackageName(String packageName) { 11938 // reader 11939 synchronized (mPackages) { 11940 return mSettings.getInstallerPackageNameLPr(packageName); 11941 } 11942 } 11943 11944 @Override 11945 public int getApplicationEnabledSetting(String packageName, int userId) { 11946 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11947 int uid = Binder.getCallingUid(); 11948 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11949 // reader 11950 synchronized (mPackages) { 11951 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11952 } 11953 } 11954 11955 @Override 11956 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11957 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11958 int uid = Binder.getCallingUid(); 11959 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11960 // reader 11961 synchronized (mPackages) { 11962 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11963 } 11964 } 11965 11966 @Override 11967 public void enterSafeMode() { 11968 enforceSystemOrRoot("Only the system can request entering safe mode"); 11969 11970 if (!mSystemReady) { 11971 mSafeMode = true; 11972 } 11973 } 11974 11975 @Override 11976 public void systemReady() { 11977 mSystemReady = true; 11978 11979 // Read the compatibilty setting when the system is ready. 11980 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11981 mContext.getContentResolver(), 11982 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11983 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11984 if (DEBUG_SETTINGS) { 11985 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11986 } 11987 11988 synchronized (mPackages) { 11989 // Verify that all of the preferred activity components actually 11990 // exist. It is possible for applications to be updated and at 11991 // that point remove a previously declared activity component that 11992 // had been set as a preferred activity. We try to clean this up 11993 // the next time we encounter that preferred activity, but it is 11994 // possible for the user flow to never be able to return to that 11995 // situation so here we do a sanity check to make sure we haven't 11996 // left any junk around. 11997 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11998 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11999 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12000 removed.clear(); 12001 for (PreferredActivity pa : pir.filterSet()) { 12002 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12003 removed.add(pa); 12004 } 12005 } 12006 if (removed.size() > 0) { 12007 for (int r=0; r<removed.size(); r++) { 12008 PreferredActivity pa = removed.get(r); 12009 Slog.w(TAG, "Removing dangling preferred activity: " 12010 + pa.mPref.mComponent); 12011 pir.removeFilter(pa); 12012 } 12013 mSettings.writePackageRestrictionsLPr( 12014 mSettings.mPreferredActivities.keyAt(i)); 12015 } 12016 } 12017 } 12018 sUserManager.systemReady(); 12019 } 12020 12021 @Override 12022 public boolean isSafeMode() { 12023 return mSafeMode; 12024 } 12025 12026 @Override 12027 public boolean hasSystemUidErrors() { 12028 return mHasSystemUidErrors; 12029 } 12030 12031 static String arrayToString(int[] array) { 12032 StringBuffer buf = new StringBuffer(128); 12033 buf.append('['); 12034 if (array != null) { 12035 for (int i=0; i<array.length; i++) { 12036 if (i > 0) buf.append(", "); 12037 buf.append(array[i]); 12038 } 12039 } 12040 buf.append(']'); 12041 return buf.toString(); 12042 } 12043 12044 static class DumpState { 12045 public static final int DUMP_LIBS = 1 << 0; 12046 public static final int DUMP_FEATURES = 1 << 1; 12047 public static final int DUMP_RESOLVERS = 1 << 2; 12048 public static final int DUMP_PERMISSIONS = 1 << 3; 12049 public static final int DUMP_PACKAGES = 1 << 4; 12050 public static final int DUMP_SHARED_USERS = 1 << 5; 12051 public static final int DUMP_MESSAGES = 1 << 6; 12052 public static final int DUMP_PROVIDERS = 1 << 7; 12053 public static final int DUMP_VERIFIERS = 1 << 8; 12054 public static final int DUMP_PREFERRED = 1 << 9; 12055 public static final int DUMP_PREFERRED_XML = 1 << 10; 12056 public static final int DUMP_KEYSETS = 1 << 11; 12057 public static final int DUMP_VERSION = 1 << 12; 12058 public static final int DUMP_INSTALLS = 1 << 13; 12059 12060 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12061 12062 private int mTypes; 12063 12064 private int mOptions; 12065 12066 private boolean mTitlePrinted; 12067 12068 private SharedUserSetting mSharedUser; 12069 12070 public boolean isDumping(int type) { 12071 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12072 return true; 12073 } 12074 12075 return (mTypes & type) != 0; 12076 } 12077 12078 public void setDump(int type) { 12079 mTypes |= type; 12080 } 12081 12082 public boolean isOptionEnabled(int option) { 12083 return (mOptions & option) != 0; 12084 } 12085 12086 public void setOptionEnabled(int option) { 12087 mOptions |= option; 12088 } 12089 12090 public boolean onTitlePrinted() { 12091 final boolean printed = mTitlePrinted; 12092 mTitlePrinted = true; 12093 return printed; 12094 } 12095 12096 public boolean getTitlePrinted() { 12097 return mTitlePrinted; 12098 } 12099 12100 public void setTitlePrinted(boolean enabled) { 12101 mTitlePrinted = enabled; 12102 } 12103 12104 public SharedUserSetting getSharedUser() { 12105 return mSharedUser; 12106 } 12107 12108 public void setSharedUser(SharedUserSetting user) { 12109 mSharedUser = user; 12110 } 12111 } 12112 12113 @Override 12114 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12115 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12116 != PackageManager.PERMISSION_GRANTED) { 12117 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12118 + Binder.getCallingPid() 12119 + ", uid=" + Binder.getCallingUid() 12120 + " without permission " 12121 + android.Manifest.permission.DUMP); 12122 return; 12123 } 12124 12125 DumpState dumpState = new DumpState(); 12126 boolean fullPreferred = false; 12127 boolean checkin = false; 12128 12129 String packageName = null; 12130 12131 int opti = 0; 12132 while (opti < args.length) { 12133 String opt = args[opti]; 12134 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12135 break; 12136 } 12137 opti++; 12138 if ("-a".equals(opt)) { 12139 // Right now we only know how to print all. 12140 } else if ("-h".equals(opt)) { 12141 pw.println("Package manager dump options:"); 12142 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12143 pw.println(" --checkin: dump for a checkin"); 12144 pw.println(" -f: print details of intent filters"); 12145 pw.println(" -h: print this help"); 12146 pw.println(" cmd may be one of:"); 12147 pw.println(" l[ibraries]: list known shared libraries"); 12148 pw.println(" f[ibraries]: list device features"); 12149 pw.println(" k[eysets]: print known keysets"); 12150 pw.println(" r[esolvers]: dump intent resolvers"); 12151 pw.println(" perm[issions]: dump permissions"); 12152 pw.println(" pref[erred]: print preferred package settings"); 12153 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12154 pw.println(" prov[iders]: dump content providers"); 12155 pw.println(" p[ackages]: dump installed packages"); 12156 pw.println(" s[hared-users]: dump shared user IDs"); 12157 pw.println(" m[essages]: print collected runtime messages"); 12158 pw.println(" v[erifiers]: print package verifier info"); 12159 pw.println(" version: print database version info"); 12160 pw.println(" write: write current settings now"); 12161 pw.println(" <package.name>: info about given package"); 12162 pw.println(" installs: details about install sessions"); 12163 return; 12164 } else if ("--checkin".equals(opt)) { 12165 checkin = true; 12166 } else if ("-f".equals(opt)) { 12167 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12168 } else { 12169 pw.println("Unknown argument: " + opt + "; use -h for help"); 12170 } 12171 } 12172 12173 // Is the caller requesting to dump a particular piece of data? 12174 if (opti < args.length) { 12175 String cmd = args[opti]; 12176 opti++; 12177 // Is this a package name? 12178 if ("android".equals(cmd) || cmd.contains(".")) { 12179 packageName = cmd; 12180 // When dumping a single package, we always dump all of its 12181 // filter information since the amount of data will be reasonable. 12182 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12183 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12184 dumpState.setDump(DumpState.DUMP_LIBS); 12185 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12186 dumpState.setDump(DumpState.DUMP_FEATURES); 12187 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12188 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12189 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12190 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12191 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12192 dumpState.setDump(DumpState.DUMP_PREFERRED); 12193 } else if ("preferred-xml".equals(cmd)) { 12194 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12195 if (opti < args.length && "--full".equals(args[opti])) { 12196 fullPreferred = true; 12197 opti++; 12198 } 12199 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12200 dumpState.setDump(DumpState.DUMP_PACKAGES); 12201 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12202 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12203 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12204 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12205 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12206 dumpState.setDump(DumpState.DUMP_MESSAGES); 12207 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12208 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12209 } else if ("version".equals(cmd)) { 12210 dumpState.setDump(DumpState.DUMP_VERSION); 12211 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12212 dumpState.setDump(DumpState.DUMP_KEYSETS); 12213 } else if ("write".equals(cmd)) { 12214 synchronized (mPackages) { 12215 mSettings.writeLPr(); 12216 pw.println("Settings written."); 12217 return; 12218 } 12219 } else if ("installs".equals(cmd)) { 12220 dumpState.setDump(DumpState.DUMP_INSTALLS); 12221 } 12222 } 12223 12224 if (checkin) { 12225 pw.println("vers,1"); 12226 } 12227 12228 // reader 12229 synchronized (mPackages) { 12230 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12231 if (!checkin) { 12232 if (dumpState.onTitlePrinted()) 12233 pw.println(); 12234 pw.println("Database versions:"); 12235 pw.print(" SDK Version:"); 12236 pw.print(" internal="); 12237 pw.print(mSettings.mInternalSdkPlatform); 12238 pw.print(" external="); 12239 pw.println(mSettings.mExternalSdkPlatform); 12240 pw.print(" DB Version:"); 12241 pw.print(" internal="); 12242 pw.print(mSettings.mInternalDatabaseVersion); 12243 pw.print(" external="); 12244 pw.println(mSettings.mExternalDatabaseVersion); 12245 } 12246 } 12247 12248 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12249 if (!checkin) { 12250 if (dumpState.onTitlePrinted()) 12251 pw.println(); 12252 pw.println("Verifiers:"); 12253 pw.print(" Required: "); 12254 pw.print(mRequiredVerifierPackage); 12255 pw.print(" (uid="); 12256 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12257 pw.println(")"); 12258 } else if (mRequiredVerifierPackage != null) { 12259 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12260 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12261 } 12262 } 12263 12264 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12265 boolean printedHeader = false; 12266 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12267 while (it.hasNext()) { 12268 String name = it.next(); 12269 SharedLibraryEntry ent = mSharedLibraries.get(name); 12270 if (!checkin) { 12271 if (!printedHeader) { 12272 if (dumpState.onTitlePrinted()) 12273 pw.println(); 12274 pw.println("Libraries:"); 12275 printedHeader = true; 12276 } 12277 pw.print(" "); 12278 } else { 12279 pw.print("lib,"); 12280 } 12281 pw.print(name); 12282 if (!checkin) { 12283 pw.print(" -> "); 12284 } 12285 if (ent.path != null) { 12286 if (!checkin) { 12287 pw.print("(jar) "); 12288 pw.print(ent.path); 12289 } else { 12290 pw.print(",jar,"); 12291 pw.print(ent.path); 12292 } 12293 } else { 12294 if (!checkin) { 12295 pw.print("(apk) "); 12296 pw.print(ent.apk); 12297 } else { 12298 pw.print(",apk,"); 12299 pw.print(ent.apk); 12300 } 12301 } 12302 pw.println(); 12303 } 12304 } 12305 12306 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12307 if (dumpState.onTitlePrinted()) 12308 pw.println(); 12309 if (!checkin) { 12310 pw.println("Features:"); 12311 } 12312 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12313 while (it.hasNext()) { 12314 String name = it.next(); 12315 if (!checkin) { 12316 pw.print(" "); 12317 } else { 12318 pw.print("feat,"); 12319 } 12320 pw.println(name); 12321 } 12322 } 12323 12324 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12325 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12326 : "Activity Resolver Table:", " ", packageName, 12327 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12328 dumpState.setTitlePrinted(true); 12329 } 12330 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12331 : "Receiver Resolver Table:", " ", packageName, 12332 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12333 dumpState.setTitlePrinted(true); 12334 } 12335 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12336 : "Service Resolver Table:", " ", packageName, 12337 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12338 dumpState.setTitlePrinted(true); 12339 } 12340 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12341 : "Provider Resolver Table:", " ", packageName, 12342 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12343 dumpState.setTitlePrinted(true); 12344 } 12345 } 12346 12347 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12348 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12349 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12350 int user = mSettings.mPreferredActivities.keyAt(i); 12351 if (pir.dump(pw, 12352 dumpState.getTitlePrinted() 12353 ? "\nPreferred Activities User " + user + ":" 12354 : "Preferred Activities User " + user + ":", " ", 12355 packageName, true)) { 12356 dumpState.setTitlePrinted(true); 12357 } 12358 } 12359 } 12360 12361 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12362 pw.flush(); 12363 FileOutputStream fout = new FileOutputStream(fd); 12364 BufferedOutputStream str = new BufferedOutputStream(fout); 12365 XmlSerializer serializer = new FastXmlSerializer(); 12366 try { 12367 serializer.setOutput(str, "utf-8"); 12368 serializer.startDocument(null, true); 12369 serializer.setFeature( 12370 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12371 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12372 serializer.endDocument(); 12373 serializer.flush(); 12374 } catch (IllegalArgumentException e) { 12375 pw.println("Failed writing: " + e); 12376 } catch (IllegalStateException e) { 12377 pw.println("Failed writing: " + e); 12378 } catch (IOException e) { 12379 pw.println("Failed writing: " + e); 12380 } 12381 } 12382 12383 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12384 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12385 } 12386 12387 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12388 boolean printedSomething = false; 12389 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12390 if (packageName != null && !packageName.equals(p.info.packageName)) { 12391 continue; 12392 } 12393 if (!printedSomething) { 12394 if (dumpState.onTitlePrinted()) 12395 pw.println(); 12396 pw.println("Registered ContentProviders:"); 12397 printedSomething = true; 12398 } 12399 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12400 pw.print(" "); pw.println(p.toString()); 12401 } 12402 printedSomething = false; 12403 for (Map.Entry<String, PackageParser.Provider> entry : 12404 mProvidersByAuthority.entrySet()) { 12405 PackageParser.Provider p = entry.getValue(); 12406 if (packageName != null && !packageName.equals(p.info.packageName)) { 12407 continue; 12408 } 12409 if (!printedSomething) { 12410 if (dumpState.onTitlePrinted()) 12411 pw.println(); 12412 pw.println("ContentProvider Authorities:"); 12413 printedSomething = true; 12414 } 12415 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12416 pw.print(" "); pw.println(p.toString()); 12417 if (p.info != null && p.info.applicationInfo != null) { 12418 final String appInfo = p.info.applicationInfo.toString(); 12419 pw.print(" applicationInfo="); pw.println(appInfo); 12420 } 12421 } 12422 } 12423 12424 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12425 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12426 } 12427 12428 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12429 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12430 } 12431 12432 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12433 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12434 } 12435 12436 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) { 12437 if (dumpState.onTitlePrinted()) pw.println(); 12438 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12439 } 12440 12441 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12442 if (dumpState.onTitlePrinted()) pw.println(); 12443 mSettings.dumpReadMessagesLPr(pw, dumpState); 12444 12445 pw.println(); 12446 pw.println("Package warning messages:"); 12447 final File fname = getSettingsProblemFile(); 12448 FileInputStream in = null; 12449 try { 12450 in = new FileInputStream(fname); 12451 final int avail = in.available(); 12452 final byte[] data = new byte[avail]; 12453 in.read(data); 12454 pw.print(new String(data)); 12455 } catch (FileNotFoundException e) { 12456 } catch (IOException e) { 12457 } finally { 12458 if (in != null) { 12459 try { 12460 in.close(); 12461 } catch (IOException e) { 12462 } 12463 } 12464 } 12465 } 12466 } 12467 } 12468 12469 // ------- apps on sdcard specific code ------- 12470 static final boolean DEBUG_SD_INSTALL = false; 12471 12472 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12473 12474 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12475 12476 private boolean mMediaMounted = false; 12477 12478 private String getEncryptKey() { 12479 try { 12480 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12481 SD_ENCRYPTION_KEYSTORE_NAME); 12482 if (sdEncKey == null) { 12483 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12484 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12485 if (sdEncKey == null) { 12486 Slog.e(TAG, "Failed to create encryption keys"); 12487 return null; 12488 } 12489 } 12490 return sdEncKey; 12491 } catch (NoSuchAlgorithmException nsae) { 12492 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12493 return null; 12494 } catch (IOException ioe) { 12495 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12496 return null; 12497 } 12498 12499 } 12500 12501 /* package */static String getTempContainerId() { 12502 int tmpIdx = 1; 12503 String list[] = PackageHelper.getSecureContainerList(); 12504 if (list != null) { 12505 for (final String name : list) { 12506 // Ignore null and non-temporary container entries 12507 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12508 continue; 12509 } 12510 12511 String subStr = name.substring(mTempContainerPrefix.length()); 12512 try { 12513 int cid = Integer.parseInt(subStr); 12514 if (cid >= tmpIdx) { 12515 tmpIdx = cid + 1; 12516 } 12517 } catch (NumberFormatException e) { 12518 } 12519 } 12520 } 12521 return mTempContainerPrefix + tmpIdx; 12522 } 12523 12524 /* 12525 * Update media status on PackageManager. 12526 */ 12527 @Override 12528 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12529 int callingUid = Binder.getCallingUid(); 12530 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12531 throw new SecurityException("Media status can only be updated by the system"); 12532 } 12533 // reader; this apparently protects mMediaMounted, but should probably 12534 // be a different lock in that case. 12535 synchronized (mPackages) { 12536 Log.i(TAG, "Updating external media status from " 12537 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12538 + (mediaStatus ? "mounted" : "unmounted")); 12539 if (DEBUG_SD_INSTALL) 12540 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12541 + ", mMediaMounted=" + mMediaMounted); 12542 if (mediaStatus == mMediaMounted) { 12543 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12544 : 0, -1); 12545 mHandler.sendMessage(msg); 12546 return; 12547 } 12548 mMediaMounted = mediaStatus; 12549 } 12550 // Queue up an async operation since the package installation may take a 12551 // little while. 12552 mHandler.post(new Runnable() { 12553 public void run() { 12554 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12555 } 12556 }); 12557 } 12558 12559 /** 12560 * Called by MountService when the initial ASECs to scan are available. 12561 * Should block until all the ASEC containers are finished being scanned. 12562 */ 12563 public void scanAvailableAsecs() { 12564 updateExternalMediaStatusInner(true, false, false); 12565 if (mShouldRestoreconData) { 12566 SELinuxMMAC.setRestoreconDone(); 12567 mShouldRestoreconData = false; 12568 } 12569 } 12570 12571 /* 12572 * Collect information of applications on external media, map them against 12573 * existing containers and update information based on current mount status. 12574 * Please note that we always have to report status if reportStatus has been 12575 * set to true especially when unloading packages. 12576 */ 12577 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12578 boolean externalStorage) { 12579 // Collection of uids 12580 int uidArr[] = null; 12581 // Collection of stale containers 12582 HashSet<String> removeCids = new HashSet<String>(); 12583 // Collection of packages on external media with valid containers. 12584 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12585 // Get list of secure containers. 12586 final String list[] = PackageHelper.getSecureContainerList(); 12587 if (list == null || list.length == 0) { 12588 Log.i(TAG, "No secure containers on sdcard"); 12589 } else { 12590 // Process list of secure containers and categorize them 12591 // as active or stale based on their package internal state. 12592 int uidList[] = new int[list.length]; 12593 int num = 0; 12594 // reader 12595 synchronized (mPackages) { 12596 for (String cid : list) { 12597 if (DEBUG_SD_INSTALL) 12598 Log.i(TAG, "Processing container " + cid); 12599 String pkgName = getAsecPackageName(cid); 12600 if (pkgName == null) { 12601 if (DEBUG_SD_INSTALL) 12602 Log.i(TAG, "Container : " + cid + " stale"); 12603 removeCids.add(cid); 12604 continue; 12605 } 12606 if (DEBUG_SD_INSTALL) 12607 Log.i(TAG, "Looking for pkg : " + pkgName); 12608 12609 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12610 if (ps == null) { 12611 Log.i(TAG, "Deleting container with no matching settings " + cid); 12612 removeCids.add(cid); 12613 continue; 12614 } 12615 12616 /* 12617 * Skip packages that are not external if we're unmounting 12618 * external storage. 12619 */ 12620 if (externalStorage && !isMounted && !isExternal(ps)) { 12621 continue; 12622 } 12623 12624 final AsecInstallArgs args = new AsecInstallArgs(cid, 12625 getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps)); 12626 // The package status is changed only if the code path 12627 // matches between settings and the container id. 12628 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12629 if (DEBUG_SD_INSTALL) { 12630 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12631 + " at code path: " + ps.codePathString); 12632 } 12633 12634 // We do have a valid package installed on sdcard 12635 processCids.put(args, ps.codePathString); 12636 final int uid = ps.appId; 12637 if (uid != -1) { 12638 uidList[num++] = uid; 12639 } 12640 } else { 12641 Log.i(TAG, "Deleting stale container for " + cid); 12642 removeCids.add(cid); 12643 } 12644 } 12645 } 12646 12647 if (num > 0) { 12648 // Sort uid list 12649 Arrays.sort(uidList, 0, num); 12650 // Throw away duplicates 12651 uidArr = new int[num]; 12652 uidArr[0] = uidList[0]; 12653 int di = 0; 12654 for (int i = 1; i < num; i++) { 12655 if (uidList[i - 1] != uidList[i]) { 12656 uidArr[di++] = uidList[i]; 12657 } 12658 } 12659 } 12660 } 12661 // Process packages with valid entries. 12662 if (isMounted) { 12663 if (DEBUG_SD_INSTALL) 12664 Log.i(TAG, "Loading packages"); 12665 loadMediaPackages(processCids, uidArr, removeCids); 12666 startCleaningPackages(); 12667 } else { 12668 if (DEBUG_SD_INSTALL) 12669 Log.i(TAG, "Unloading packages"); 12670 unloadMediaPackages(processCids, uidArr, reportStatus); 12671 } 12672 } 12673 12674 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12675 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12676 int size = pkgList.size(); 12677 if (size > 0) { 12678 // Send broadcasts here 12679 Bundle extras = new Bundle(); 12680 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12681 .toArray(new String[size])); 12682 if (uidArr != null) { 12683 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12684 } 12685 if (replacing) { 12686 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12687 } 12688 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12689 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12690 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12691 } 12692 } 12693 12694 /* 12695 * Look at potentially valid container ids from processCids If package 12696 * information doesn't match the one on record or package scanning fails, 12697 * the cid is added to list of removeCids. We currently don't delete stale 12698 * containers. 12699 */ 12700 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12701 HashSet<String> removeCids) { 12702 ArrayList<String> pkgList = new ArrayList<String>(); 12703 Set<AsecInstallArgs> keys = processCids.keySet(); 12704 boolean doGc = false; 12705 for (AsecInstallArgs args : keys) { 12706 String codePath = processCids.get(args); 12707 if (DEBUG_SD_INSTALL) 12708 Log.i(TAG, "Loading container : " + args.cid); 12709 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12710 try { 12711 // Make sure there are no container errors first. 12712 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12713 Slog.e(TAG, "Failed to mount cid : " + args.cid 12714 + " when installing from sdcard"); 12715 continue; 12716 } 12717 // Check code path here. 12718 if (codePath == null || !codePath.equals(args.getCodePath())) { 12719 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12720 + " does not match one in settings " + codePath); 12721 continue; 12722 } 12723 // Parse package 12724 int parseFlags = mDefParseFlags; 12725 if (args.isExternal()) { 12726 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12727 } 12728 if (args.isFwdLocked()) { 12729 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12730 } 12731 12732 doGc = true; 12733 synchronized (mInstallLock) { 12734 PackageParser.Package pkg = null; 12735 try { 12736 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null, null); 12737 } catch (PackageManagerException e) { 12738 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12739 } 12740 // Scan the package 12741 if (pkg != null) { 12742 /* 12743 * TODO why is the lock being held? doPostInstall is 12744 * called in other places without the lock. This needs 12745 * to be straightened out. 12746 */ 12747 // writer 12748 synchronized (mPackages) { 12749 retCode = PackageManager.INSTALL_SUCCEEDED; 12750 pkgList.add(pkg.packageName); 12751 // Post process args 12752 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12753 pkg.applicationInfo.uid); 12754 } 12755 } else { 12756 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12757 } 12758 } 12759 12760 } finally { 12761 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12762 // Don't destroy container here. Wait till gc clears things 12763 // up. 12764 removeCids.add(args.cid); 12765 } 12766 } 12767 } 12768 // writer 12769 synchronized (mPackages) { 12770 // If the platform SDK has changed since the last time we booted, 12771 // we need to re-grant app permission to catch any new ones that 12772 // appear. This is really a hack, and means that apps can in some 12773 // cases get permissions that the user didn't initially explicitly 12774 // allow... it would be nice to have some better way to handle 12775 // this situation. 12776 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12777 if (regrantPermissions) 12778 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12779 + mSdkVersion + "; regranting permissions for external storage"); 12780 mSettings.mExternalSdkPlatform = mSdkVersion; 12781 12782 // Make sure group IDs have been assigned, and any permission 12783 // changes in other apps are accounted for 12784 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12785 | (regrantPermissions 12786 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12787 : 0)); 12788 12789 mSettings.updateExternalDatabaseVersion(); 12790 12791 // can downgrade to reader 12792 // Persist settings 12793 mSettings.writeLPr(); 12794 } 12795 // Send a broadcast to let everyone know we are done processing 12796 if (pkgList.size() > 0) { 12797 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12798 } 12799 // Force gc to avoid any stale parser references that we might have. 12800 if (doGc) { 12801 Runtime.getRuntime().gc(); 12802 } 12803 // List stale containers and destroy stale temporary containers. 12804 if (removeCids != null) { 12805 for (String cid : removeCids) { 12806 if (cid.startsWith(mTempContainerPrefix)) { 12807 Log.i(TAG, "Destroying stale temporary container " + cid); 12808 PackageHelper.destroySdDir(cid); 12809 } else { 12810 Log.w(TAG, "Container " + cid + " is stale"); 12811 } 12812 } 12813 } 12814 } 12815 12816 /* 12817 * Utility method to unload a list of specified containers 12818 */ 12819 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12820 // Just unmount all valid containers. 12821 for (AsecInstallArgs arg : cidArgs) { 12822 synchronized (mInstallLock) { 12823 arg.doPostDeleteLI(false); 12824 } 12825 } 12826 } 12827 12828 /* 12829 * Unload packages mounted on external media. This involves deleting package 12830 * data from internal structures, sending broadcasts about diabled packages, 12831 * gc'ing to free up references, unmounting all secure containers 12832 * corresponding to packages on external media, and posting a 12833 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12834 * that we always have to post this message if status has been requested no 12835 * matter what. 12836 */ 12837 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12838 final boolean reportStatus) { 12839 if (DEBUG_SD_INSTALL) 12840 Log.i(TAG, "unloading media packages"); 12841 ArrayList<String> pkgList = new ArrayList<String>(); 12842 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12843 final Set<AsecInstallArgs> keys = processCids.keySet(); 12844 for (AsecInstallArgs args : keys) { 12845 String pkgName = args.getPackageName(); 12846 if (DEBUG_SD_INSTALL) 12847 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12848 // Delete package internally 12849 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12850 synchronized (mInstallLock) { 12851 boolean res = deletePackageLI(pkgName, null, false, null, null, 12852 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12853 if (res) { 12854 pkgList.add(pkgName); 12855 } else { 12856 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12857 failedList.add(args); 12858 } 12859 } 12860 } 12861 12862 // reader 12863 synchronized (mPackages) { 12864 // We didn't update the settings after removing each package; 12865 // write them now for all packages. 12866 mSettings.writeLPr(); 12867 } 12868 12869 // We have to absolutely send UPDATED_MEDIA_STATUS only 12870 // after confirming that all the receivers processed the ordered 12871 // broadcast when packages get disabled, force a gc to clean things up. 12872 // and unload all the containers. 12873 if (pkgList.size() > 0) { 12874 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12875 new IIntentReceiver.Stub() { 12876 public void performReceive(Intent intent, int resultCode, String data, 12877 Bundle extras, boolean ordered, boolean sticky, 12878 int sendingUser) throws RemoteException { 12879 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12880 reportStatus ? 1 : 0, 1, keys); 12881 mHandler.sendMessage(msg); 12882 } 12883 }); 12884 } else { 12885 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12886 keys); 12887 mHandler.sendMessage(msg); 12888 } 12889 } 12890 12891 /** Binder call */ 12892 @Override 12893 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12894 final int flags) { 12895 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12896 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12897 int returnCode = PackageManager.MOVE_SUCCEEDED; 12898 int currFlags = 0; 12899 int newFlags = 0; 12900 // reader 12901 synchronized (mPackages) { 12902 PackageParser.Package pkg = mPackages.get(packageName); 12903 if (pkg == null) { 12904 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12905 } else { 12906 // Disable moving fwd locked apps and system packages 12907 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12908 Slog.w(TAG, "Cannot move system application"); 12909 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12910 } else if (pkg.mOperationPending) { 12911 Slog.w(TAG, "Attempt to move package which has pending operations"); 12912 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12913 } else { 12914 // Find install location first 12915 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12916 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12917 Slog.w(TAG, "Ambigous flags specified for move location."); 12918 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12919 } else { 12920 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12921 : PackageManager.INSTALL_INTERNAL; 12922 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12923 : PackageManager.INSTALL_INTERNAL; 12924 12925 if (newFlags == currFlags) { 12926 Slog.w(TAG, "No move required. Trying to move to same location"); 12927 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12928 } else { 12929 if (isForwardLocked(pkg)) { 12930 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12931 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12932 } 12933 } 12934 } 12935 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12936 pkg.mOperationPending = true; 12937 } 12938 } 12939 } 12940 12941 /* 12942 * TODO this next block probably shouldn't be inside the lock. We 12943 * can't guarantee these won't change after this is fired off 12944 * anyway. 12945 */ 12946 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12947 processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false), 12948 returnCode); 12949 } else { 12950 Message msg = mHandler.obtainMessage(INIT_COPY); 12951 final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 12952 final boolean multiArch = isMultiArch(pkg.applicationInfo); 12953 InstallArgs srcArgs = createInstallArgsForExisting(currFlags, 12954 pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(), 12955 pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch); 12956 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 12957 instructionSets, pkg.applicationInfo.uid, user, multiArch); 12958 msg.obj = mp; 12959 mHandler.sendMessage(msg); 12960 } 12961 } 12962 } 12963 12964 private void processPendingMove(final MoveParams mp, final int currentStatus) { 12965 // Queue up an async operation since the package deletion may take a 12966 // little while. 12967 mHandler.post(new Runnable() { 12968 public void run() { 12969 // TODO fix this; this does nothing. 12970 mHandler.removeCallbacks(this); 12971 int returnCode = currentStatus; 12972 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 12973 int uidArr[] = null; 12974 ArrayList<String> pkgList = null; 12975 synchronized (mPackages) { 12976 PackageParser.Package pkg = mPackages.get(mp.packageName); 12977 if (pkg == null) { 12978 Slog.w(TAG, " Package " + mp.packageName 12979 + " doesn't exist. Aborting move"); 12980 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12981 } else if (!mp.srcArgs.getCodePath().equals( 12982 pkg.applicationInfo.getCodePath())) { 12983 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 12984 + mp.srcArgs.getCodePath() + " to " 12985 + pkg.applicationInfo.getCodePath() 12986 + " Aborting move and returning error"); 12987 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12988 } else { 12989 uidArr = new int[] { 12990 pkg.applicationInfo.uid 12991 }; 12992 pkgList = new ArrayList<String>(); 12993 pkgList.add(mp.packageName); 12994 } 12995 } 12996 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12997 // Send resources unavailable broadcast 12998 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 12999 // Update package code and resource paths 13000 synchronized (mInstallLock) { 13001 synchronized (mPackages) { 13002 PackageParser.Package pkg = mPackages.get(mp.packageName); 13003 // Recheck for package again. 13004 if (pkg == null) { 13005 Slog.w(TAG, " Package " + mp.packageName 13006 + " doesn't exist. Aborting move"); 13007 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13008 } else if (!mp.srcArgs.getCodePath().equals( 13009 pkg.applicationInfo.getCodePath())) { 13010 Slog.w(TAG, "Package " + mp.packageName 13011 + " code path changed from " + mp.srcArgs.getCodePath() 13012 + " to " + pkg.applicationInfo.getCodePath() 13013 + " Aborting move and returning error"); 13014 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13015 } else { 13016 final String oldCodePath = pkg.codePath; 13017 final String newCodePath = mp.targetArgs.getCodePath(); 13018 final String newResPath = mp.targetArgs.getResourcePath(); 13019 // TODO: This assumes the new style of installation. 13020 // should we look at legacyNativeLibraryPath ? 13021 final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath(); 13022 final File newNativeDir = new File(newNativeRoot); 13023 13024 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 13025 // TODO(multiArch): Fix this so that it looks at the existing 13026 // recorded CPU abis from the package. There's no need for a separate 13027 // round of ABI scanning here. 13028 NativeLibraryHelper.Handle handle = null; 13029 try { 13030 handle = NativeLibraryHelper.Handle.create( 13031 new File(newCodePath)); 13032 final int abi = NativeLibraryHelper.findSupportedAbi( 13033 handle, Build.SUPPORTED_ABIS); 13034 if (abi >= 0) { 13035 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 13036 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 13037 } 13038 } catch (IOException ioe) { 13039 Slog.w(TAG, "Unable to extract native libs for package :" 13040 + mp.packageName, ioe); 13041 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13042 } finally { 13043 IoUtils.closeQuietly(handle); 13044 } 13045 } 13046 13047 final int[] users = sUserManager.getUserIds(); 13048 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13049 for (int user : users) { 13050 // TODO(multiArch): Fix this so that it links to the 13051 // correct directory. We're currently pointing to root. but we 13052 // must point to the arch specific subdirectory (if applicable). 13053 // 13054 // TODO(multiArch): Bogus reference to nativeLibraryDir. 13055 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 13056 newNativeRoot, user) < 0) { 13057 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13058 } 13059 } 13060 } 13061 13062 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13063 pkg.codePath = newCodePath; 13064 pkg.baseCodePath = newCodePath; 13065 // Move dex files around 13066 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 13067 // Moving of dex files failed. Set 13068 // error code and abort move. 13069 pkg.codePath = oldCodePath; 13070 pkg.baseCodePath = oldCodePath; 13071 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13072 } 13073 } 13074 13075 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13076 pkg.applicationInfo.setCodePath(newCodePath); 13077 pkg.applicationInfo.setBaseCodePath(newCodePath); 13078 pkg.applicationInfo.setSplitCodePaths(null); 13079 pkg.applicationInfo.setResourcePath(newResPath); 13080 pkg.applicationInfo.setBaseResourcePath(newResPath); 13081 pkg.applicationInfo.setSplitResourcePaths(null); 13082 13083 PackageSetting ps = (PackageSetting) pkg.mExtras; 13084 ps.codePath = new File(pkg.applicationInfo.getCodePath()); 13085 ps.codePathString = ps.codePath.getPath(); 13086 ps.resourcePath = new File(pkg.applicationInfo.getResourcePath()); 13087 ps.resourcePathString = ps.resourcePath.getPath(); 13088 13089 // Note that we don't have to recalculate the primary and secondary 13090 // CPU ABIs because they must already have been calculated during the 13091 // initial install of the app. 13092 ps.legacyNativeLibraryPathString = null; 13093 13094 // Set the application info flag 13095 // correctly. 13096 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 13097 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13098 } else { 13099 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13100 } 13101 ps.setFlags(pkg.applicationInfo.flags); 13102 mAppDirs.remove(oldCodePath); 13103 mAppDirs.put(newCodePath, pkg); 13104 // Persist settings 13105 mSettings.writeLPr(); 13106 } 13107 } 13108 } 13109 } 13110 // Send resources available broadcast 13111 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13112 } 13113 } 13114 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13115 // Clean up failed installation 13116 if (mp.targetArgs != null) { 13117 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 13118 -1); 13119 } 13120 } else { 13121 // Force a gc to clear things up. 13122 Runtime.getRuntime().gc(); 13123 // Delete older code 13124 synchronized (mInstallLock) { 13125 mp.srcArgs.doPostDeleteLI(true); 13126 } 13127 } 13128 13129 // Allow more operations on this file if we didn't fail because 13130 // an operation was already pending for this package. 13131 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 13132 synchronized (mPackages) { 13133 PackageParser.Package pkg = mPackages.get(mp.packageName); 13134 if (pkg != null) { 13135 pkg.mOperationPending = false; 13136 } 13137 } 13138 } 13139 13140 IPackageMoveObserver observer = mp.observer; 13141 if (observer != null) { 13142 try { 13143 observer.packageMoved(mp.packageName, returnCode); 13144 } catch (RemoteException e) { 13145 Log.i(TAG, "Observer no longer exists."); 13146 } 13147 } 13148 } 13149 }); 13150 } 13151 13152 @Override 13153 public boolean setInstallLocation(int loc) { 13154 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13155 null); 13156 if (getInstallLocation() == loc) { 13157 return true; 13158 } 13159 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13160 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13161 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13162 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13163 return true; 13164 } 13165 return false; 13166 } 13167 13168 @Override 13169 public int getInstallLocation() { 13170 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13171 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13172 PackageHelper.APP_INSTALL_AUTO); 13173 } 13174 13175 /** Called by UserManagerService */ 13176 void cleanUpUserLILPw(int userHandle) { 13177 mDirtyUsers.remove(userHandle); 13178 mSettings.removeUserLPw(userHandle); 13179 mPendingBroadcasts.remove(userHandle); 13180 if (mInstaller != null) { 13181 // Technically, we shouldn't be doing this with the package lock 13182 // held. However, this is very rare, and there is already so much 13183 // other disk I/O going on, that we'll let it slide for now. 13184 mInstaller.removeUserDataDirs(userHandle); 13185 } 13186 mUserNeedsBadging.delete(userHandle); 13187 } 13188 13189 /** Called by UserManagerService */ 13190 void createNewUserLILPw(int userHandle, File path) { 13191 if (mInstaller != null) { 13192 mInstaller.createUserConfig(userHandle); 13193 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13194 } 13195 } 13196 13197 @Override 13198 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13199 mContext.enforceCallingOrSelfPermission( 13200 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13201 "Only package verification agents can read the verifier device identity"); 13202 13203 synchronized (mPackages) { 13204 return mSettings.getVerifierDeviceIdentityLPw(); 13205 } 13206 } 13207 13208 @Override 13209 public void setPermissionEnforced(String permission, boolean enforced) { 13210 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13211 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13212 synchronized (mPackages) { 13213 if (mSettings.mReadExternalStorageEnforced == null 13214 || mSettings.mReadExternalStorageEnforced != enforced) { 13215 mSettings.mReadExternalStorageEnforced = enforced; 13216 mSettings.writeLPr(); 13217 } 13218 } 13219 // kill any non-foreground processes so we restart them and 13220 // grant/revoke the GID. 13221 final IActivityManager am = ActivityManagerNative.getDefault(); 13222 if (am != null) { 13223 final long token = Binder.clearCallingIdentity(); 13224 try { 13225 am.killProcessesBelowForeground("setPermissionEnforcement"); 13226 } catch (RemoteException e) { 13227 } finally { 13228 Binder.restoreCallingIdentity(token); 13229 } 13230 } 13231 } else { 13232 throw new IllegalArgumentException("No selective enforcement for " + permission); 13233 } 13234 } 13235 13236 @Override 13237 @Deprecated 13238 public boolean isPermissionEnforced(String permission) { 13239 return true; 13240 } 13241 13242 @Override 13243 public boolean isStorageLow() { 13244 final long token = Binder.clearCallingIdentity(); 13245 try { 13246 final DeviceStorageMonitorInternal 13247 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13248 if (dsm != null) { 13249 return dsm.isMemoryLow(); 13250 } else { 13251 return false; 13252 } 13253 } finally { 13254 Binder.restoreCallingIdentity(token); 13255 } 13256 } 13257 13258 @Override 13259 public IPackageInstaller getPackageInstaller() { 13260 return mInstallerService; 13261 } 13262 13263 private boolean userNeedsBadging(int userId) { 13264 int index = mUserNeedsBadging.indexOfKey(userId); 13265 if (index < 0) { 13266 final UserInfo userInfo; 13267 final long token = Binder.clearCallingIdentity(); 13268 try { 13269 userInfo = sUserManager.getUserInfo(userId); 13270 } finally { 13271 Binder.restoreCallingIdentity(token); 13272 } 13273 final boolean b; 13274 if (userInfo != null && userInfo.isManagedProfile()) { 13275 b = true; 13276 } else { 13277 b = false; 13278 } 13279 mUserNeedsBadging.put(userId, b); 13280 return b; 13281 } 13282 return mUserNeedsBadging.valueAt(index); 13283 } 13284 13285 @Override 13286 public KeySetHandle getKeySetByAlias(String packageName, String alias) { 13287 if (packageName == null || alias == null) { 13288 return null; 13289 } 13290 synchronized(mPackages) { 13291 final PackageParser.Package pkg = mPackages.get(packageName); 13292 if (pkg == null) { 13293 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13294 throw new IllegalArgumentException("Unknown package: " + packageName); 13295 } 13296 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13297 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13298 throw new SecurityException("May not access KeySets defined by" 13299 + " aliases in other applications."); 13300 } 13301 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13302 return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias); 13303 } 13304 } 13305 13306 @Override 13307 public KeySetHandle getSigningKeySet(String packageName) { 13308 if (packageName == null) { 13309 return null; 13310 } 13311 synchronized(mPackages) { 13312 final PackageParser.Package pkg = mPackages.get(packageName); 13313 if (pkg == null) { 13314 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13315 throw new IllegalArgumentException("Unknown package: " + packageName); 13316 } 13317 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13318 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13319 throw new SecurityException("May not access signing KeySet of other apps."); 13320 } 13321 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13322 return ksms.getSigningKeySetByPackageNameLPr(packageName); 13323 } 13324 } 13325 13326 @Override 13327 public boolean isPackageSignedByKeySet(String packageName, IBinder ks) { 13328 if (packageName == null || ks == null) { 13329 return false; 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 (ks instanceof KeySetHandle) { 13338 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13339 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks); 13340 } 13341 return false; 13342 } 13343 } 13344 13345 @Override 13346 public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) { 13347 if (packageName == null || ks == null) { 13348 return false; 13349 } 13350 synchronized(mPackages) { 13351 final PackageParser.Package pkg = mPackages.get(packageName); 13352 if (pkg == null) { 13353 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13354 throw new IllegalArgumentException("Unknown package: " + packageName); 13355 } 13356 if (ks instanceof KeySetHandle) { 13357 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13358 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks); 13359 } 13360 return false; 13361 } 13362 } 13363} 13364