PackageManagerService.java revision 33f5ddd1bea21296938f2cba196f95d223aa247c
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 45import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 46import static android.content.pm.PackageParser.isApkFile; 47import static android.os.Process.PACKAGE_INFO_GID; 48import static android.os.Process.SYSTEM_UID; 49import static android.system.OsConstants.O_CREAT; 50import static android.system.OsConstants.O_RDWR; 51import static android.system.OsConstants.S_IRGRP; 52import static android.system.OsConstants.S_IROTH; 53import static android.system.OsConstants.S_IRWXU; 54import static android.system.OsConstants.S_IXGRP; 55import static android.system.OsConstants.S_IXOTH; 56import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 57import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 58import static com.android.internal.util.ArrayUtils.appendInt; 59import static com.android.internal.util.ArrayUtils.removeInt; 60 61import android.util.ArrayMap; 62 63import com.android.internal.R; 64import com.android.internal.app.IMediaContainerService; 65import com.android.internal.app.ResolverActivity; 66import com.android.internal.content.NativeLibraryHelper; 67import com.android.internal.content.PackageHelper; 68import com.android.internal.os.IParcelFileDescriptorFactory; 69import com.android.internal.util.ArrayUtils; 70import com.android.internal.util.FastPrintWriter; 71import com.android.internal.util.FastXmlSerializer; 72import com.android.internal.util.IndentingPrintWriter; 73import com.android.internal.util.Preconditions; 74import com.android.server.EventLogTags; 75import com.android.server.IntentResolver; 76import com.android.server.LocalServices; 77import com.android.server.ServiceThread; 78import com.android.server.SystemConfig; 79import com.android.server.Watchdog; 80import com.android.server.pm.Settings.DatabaseVersion; 81import com.android.server.storage.DeviceStorageMonitorInternal; 82 83import org.xmlpull.v1.XmlSerializer; 84 85import android.app.ActivityManager; 86import android.app.ActivityManagerNative; 87import android.app.IActivityManager; 88import android.app.admin.IDevicePolicyManager; 89import android.app.backup.IBackupManager; 90import android.content.BroadcastReceiver; 91import android.content.ComponentName; 92import android.content.Context; 93import android.content.IIntentReceiver; 94import android.content.Intent; 95import android.content.IntentFilter; 96import android.content.IntentSender; 97import android.content.IntentSender.SendIntentException; 98import android.content.ServiceConnection; 99import android.content.pm.ActivityInfo; 100import android.content.pm.ApplicationInfo; 101import android.content.pm.FeatureInfo; 102import android.content.pm.IPackageDataObserver; 103import android.content.pm.IPackageDeleteObserver; 104import android.content.pm.IPackageInstallObserver2; 105import android.content.pm.IPackageInstaller; 106import android.content.pm.IPackageManager; 107import android.content.pm.IPackageMoveObserver; 108import android.content.pm.IPackageStatsObserver; 109import android.content.pm.InstallSessionParams; 110import android.content.pm.InstrumentationInfo; 111import android.content.pm.ManifestDigest; 112import android.content.pm.PackageCleanItem; 113import android.content.pm.PackageInfo; 114import android.content.pm.PackageInfoLite; 115import android.content.pm.PackageManager; 116import android.content.pm.PackageParser.ActivityIntentInfo; 117import android.content.pm.PackageParser.PackageLite; 118import android.content.pm.PackageParser.PackageParserException; 119import android.content.pm.PackageParser; 120import android.content.pm.PackageStats; 121import android.content.pm.PackageUserState; 122import android.content.pm.ParceledListSlice; 123import android.content.pm.PermissionGroupInfo; 124import android.content.pm.PermissionInfo; 125import android.content.pm.ProviderInfo; 126import android.content.pm.ResolveInfo; 127import android.content.pm.ServiceInfo; 128import android.content.pm.Signature; 129import android.content.pm.UserInfo; 130import android.content.pm.VerificationParams; 131import android.content.pm.VerifierDeviceIdentity; 132import android.content.pm.VerifierInfo; 133import android.content.res.Resources; 134import android.hardware.display.DisplayManager; 135import android.net.Uri; 136import android.os.Binder; 137import android.os.Build; 138import android.os.Bundle; 139import android.os.Environment; 140import android.os.Environment.UserEnvironment; 141import android.os.FileObserver; 142import android.os.FileUtils; 143import android.os.Handler; 144import android.os.IBinder; 145import android.os.Looper; 146import android.os.Message; 147import android.os.Parcel; 148import android.os.ParcelFileDescriptor; 149import android.os.Process; 150import android.os.RemoteException; 151import android.os.SELinux; 152import android.os.ServiceManager; 153import android.os.SystemClock; 154import android.os.SystemProperties; 155import android.os.UserHandle; 156import android.os.UserManager; 157import android.security.KeyStore; 158import android.security.SystemKeyStore; 159import android.system.ErrnoException; 160import android.system.Os; 161import android.system.StructStat; 162import android.text.TextUtils; 163import android.util.ArraySet; 164import android.util.AtomicFile; 165import android.util.DisplayMetrics; 166import android.util.EventLog; 167import android.util.ExceptionUtils; 168import android.util.Log; 169import android.util.LogPrinter; 170import android.util.PrintStreamPrinter; 171import android.util.Slog; 172import android.util.SparseArray; 173import android.util.SparseBooleanArray; 174import android.view.Display; 175 176import java.io.BufferedInputStream; 177import java.io.BufferedOutputStream; 178import java.io.File; 179import java.io.FileDescriptor; 180import java.io.FileInputStream; 181import java.io.FileNotFoundException; 182import java.io.FileOutputStream; 183import java.io.FilenameFilter; 184import java.io.IOException; 185import java.io.InputStream; 186import java.io.PrintWriter; 187import java.nio.charset.StandardCharsets; 188import java.security.NoSuchAlgorithmException; 189import java.security.PublicKey; 190import java.security.cert.CertificateEncodingException; 191import java.security.cert.CertificateException; 192import java.text.SimpleDateFormat; 193import java.util.ArrayList; 194import java.util.Arrays; 195import java.util.Collection; 196import java.util.Collections; 197import java.util.Comparator; 198import java.util.Date; 199import java.util.HashMap; 200import java.util.HashSet; 201import java.util.Iterator; 202import java.util.List; 203import java.util.Map; 204import java.util.Set; 205import java.util.concurrent.atomic.AtomicBoolean; 206import java.util.concurrent.atomic.AtomicLong; 207 208import dalvik.system.DexFile; 209import dalvik.system.StaleDexCacheError; 210import dalvik.system.VMRuntime; 211 212import libcore.io.IoUtils; 213 214/** 215 * Keep track of all those .apks everywhere. 216 * 217 * This is very central to the platform's security; please run the unit 218 * tests whenever making modifications here: 219 * 220mmm frameworks/base/tests/AndroidTests 221adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 222adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 223 * 224 * {@hide} 225 */ 226public class PackageManagerService extends IPackageManager.Stub { 227 static final String TAG = "PackageManager"; 228 static final boolean DEBUG_SETTINGS = false; 229 static final boolean DEBUG_PREFERRED = false; 230 static final boolean DEBUG_UPGRADE = false; 231 private static final boolean DEBUG_INSTALL = false; 232 private static final boolean DEBUG_REMOVE = false; 233 private static final boolean DEBUG_BROADCASTS = false; 234 private static final boolean DEBUG_SHOW_INFO = false; 235 private static final boolean DEBUG_PACKAGE_INFO = false; 236 private static final boolean DEBUG_INTENT_MATCHING = false; 237 private static final boolean DEBUG_PACKAGE_SCANNING = false; 238 private static final boolean DEBUG_APP_DIR_OBSERVER = false; 239 private static final boolean DEBUG_VERIFY = false; 240 private static final boolean DEBUG_DEXOPT = false; 241 private static final boolean DEBUG_ABI_SELECTION = false; 242 243 private static final int RADIO_UID = Process.PHONE_UID; 244 private static final int LOG_UID = Process.LOG_UID; 245 private static final int NFC_UID = Process.NFC_UID; 246 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 247 private static final int SHELL_UID = Process.SHELL_UID; 248 249 // Cap the size of permission trees that 3rd party apps can define 250 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 251 252 private static final int REMOVE_EVENTS = 253 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM; 254 private static final int ADD_EVENTS = 255 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO; 256 257 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS; 258 // Suffix used during package installation when copying/moving 259 // package apks to install directory. 260 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 261 262 static final int SCAN_MONITOR = 1<<0; 263 static final int SCAN_NO_DEX = 1<<1; 264 static final int SCAN_FORCE_DEX = 1<<2; 265 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 266 static final int SCAN_NEW_INSTALL = 1<<4; 267 static final int SCAN_NO_PATHS = 1<<5; 268 static final int SCAN_UPDATE_TIME = 1<<6; 269 static final int SCAN_DEFER_DEX = 1<<7; 270 static final int SCAN_BOOTING = 1<<8; 271 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 272 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 273 274 static final int REMOVE_CHATTY = 1<<16; 275 276 /** 277 * Timeout (in milliseconds) after which the watchdog should declare that 278 * our handler thread is wedged. The usual default for such things is one 279 * minute but we sometimes do very lengthy I/O operations on this thread, 280 * such as installing multi-gigabyte applications, so ours needs to be longer. 281 */ 282 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 283 284 /** 285 * Whether verification is enabled by default. 286 */ 287 private static final boolean DEFAULT_VERIFY_ENABLE = true; 288 289 /** 290 * The default maximum time to wait for the verification agent to return in 291 * milliseconds. 292 */ 293 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 294 295 /** 296 * The default response for package verification timeout. 297 * 298 * This can be either PackageManager.VERIFICATION_ALLOW or 299 * PackageManager.VERIFICATION_REJECT. 300 */ 301 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 302 303 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 304 305 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 306 DEFAULT_CONTAINER_PACKAGE, 307 "com.android.defcontainer.DefaultContainerService"); 308 309 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 310 311 private static final String LIB_DIR_NAME = "lib"; 312 private static final String LIB64_DIR_NAME = "lib64"; 313 314 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 315 316 static final String mTempContainerPrefix = "smdl2tmp"; 317 318 private static String sPreferredInstructionSet; 319 320 final ServiceThread mHandlerThread; 321 322 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 323 private static final String IDMAP_SUFFIX = "@idmap"; 324 325 final PackageHandler mHandler; 326 327 final int mSdkVersion = Build.VERSION.SDK_INT; 328 329 final Context mContext; 330 final boolean mFactoryTest; 331 final boolean mOnlyCore; 332 final DisplayMetrics mMetrics; 333 final int mDefParseFlags; 334 final String[] mSeparateProcesses; 335 336 // This is where all application persistent data goes. 337 final File mAppDataDir; 338 339 // This is where all application persistent data goes for secondary users. 340 final File mUserAppDataDir; 341 342 /** The location for ASEC container files on internal storage. */ 343 final String mAsecInternalPath; 344 345 // This is the object monitoring the framework dir. 346 final FileObserver mFrameworkInstallObserver; 347 348 // This is the object monitoring the system app dir. 349 final FileObserver mSystemInstallObserver; 350 351 // This is the object monitoring the privileged system app dir. 352 final FileObserver mPrivilegedInstallObserver; 353 354 // This is the object monitoring the vendor app dir. 355 final FileObserver mVendorInstallObserver; 356 357 // This is the object monitoring the vendor overlay package dir. 358 final FileObserver mVendorOverlayInstallObserver; 359 360 // This is the object monitoring the OEM app dir. 361 final FileObserver mOemInstallObserver; 362 363 // This is the object monitoring mAppInstallDir. 364 final FileObserver mAppInstallObserver; 365 366 // This is the object monitoring mDrmAppPrivateInstallDir. 367 final FileObserver mDrmAppInstallObserver; 368 369 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 370 // LOCK HELD. Can be called with mInstallLock held. 371 final Installer mInstaller; 372 373 /** Directory where installed third-party apps stored */ 374 final File mAppInstallDir; 375 376 /** 377 * Directory to which applications installed internally have their 378 * 32 bit native libraries copied. 379 */ 380 private File mAppLib32InstallDir; 381 382 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 383 // apps. 384 final File mDrmAppPrivateInstallDir; 385 386 // ---------------------------------------------------------------- 387 388 // Lock for state used when installing and doing other long running 389 // operations. Methods that must be called with this lock held have 390 // the suffix "LI". 391 final Object mInstallLock = new Object(); 392 393 // These are the directories in the 3rd party applications installed dir 394 // that we have currently loaded packages from. Keys are the application's 395 // installed zip file (absolute codePath), and values are Package. 396 final HashMap<String, PackageParser.Package> mAppDirs = 397 new HashMap<String, PackageParser.Package>(); 398 399 // ---------------------------------------------------------------- 400 401 // Keys are String (package name), values are Package. This also serves 402 // as the lock for the global state. Methods that must be called with 403 // this lock held have the prefix "LP". 404 final HashMap<String, PackageParser.Package> mPackages = 405 new HashMap<String, PackageParser.Package>(); 406 407 // Tracks available target package names -> overlay package paths. 408 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 409 new HashMap<String, HashMap<String, PackageParser.Package>>(); 410 411 final Settings mSettings; 412 boolean mRestoredSettings; 413 414 // System configuration read by SystemConfig. 415 final int[] mGlobalGids; 416 final SparseArray<HashSet<String>> mSystemPermissions; 417 final HashMap<String, FeatureInfo> mAvailableFeatures; 418 419 // If mac_permissions.xml was found for seinfo labeling. 420 boolean mFoundPolicyFile; 421 422 // If a recursive restorecon of /data/data/<pkg> is needed. 423 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 424 425 public static final class SharedLibraryEntry { 426 public final String path; 427 public final String apk; 428 429 SharedLibraryEntry(String _path, String _apk) { 430 path = _path; 431 apk = _apk; 432 } 433 } 434 435 // Currently known shared libraries. 436 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 437 new HashMap<String, SharedLibraryEntry>(); 438 439 // All available activities, for your resolving pleasure. 440 final ActivityIntentResolver mActivities = 441 new ActivityIntentResolver(); 442 443 // All available receivers, for your resolving pleasure. 444 final ActivityIntentResolver mReceivers = 445 new ActivityIntentResolver(); 446 447 // All available services, for your resolving pleasure. 448 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 449 450 // All available providers, for your resolving pleasure. 451 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 452 453 // Mapping from provider base names (first directory in content URI codePath) 454 // to the provider information. 455 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 456 new HashMap<String, PackageParser.Provider>(); 457 458 // Mapping from instrumentation class names to info about them. 459 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 460 new HashMap<ComponentName, PackageParser.Instrumentation>(); 461 462 // Mapping from permission names to info about them. 463 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 464 new HashMap<String, PackageParser.PermissionGroup>(); 465 466 // Packages whose data we have transfered into another package, thus 467 // should no longer exist. 468 final HashSet<String> mTransferedPackages = new HashSet<String>(); 469 470 // Broadcast actions that are only available to the system. 471 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 472 473 /** List of packages waiting for verification. */ 474 final SparseArray<PackageVerificationState> mPendingVerification 475 = new SparseArray<PackageVerificationState>(); 476 477 /** Set of packages associated with each app op permission. */ 478 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 479 480 final PackageInstallerService mInstallerService; 481 482 HashSet<PackageParser.Package> mDeferredDexOpt = null; 483 484 // Cache of users who need badging. 485 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 486 487 /** Token for keys in mPendingVerification. */ 488 private int mPendingVerificationToken = 0; 489 490 boolean mSystemReady; 491 boolean mSafeMode; 492 boolean mHasSystemUidErrors; 493 494 ApplicationInfo mAndroidApplication; 495 final ActivityInfo mResolveActivity = new ActivityInfo(); 496 final ResolveInfo mResolveInfo = new ResolveInfo(); 497 ComponentName mResolveComponentName; 498 PackageParser.Package mPlatformPackage; 499 ComponentName mCustomResolverComponentName; 500 501 boolean mResolverReplaced = false; 502 503 // Set of pending broadcasts for aggregating enable/disable of components. 504 static class PendingPackageBroadcasts { 505 // for each user id, a map of <package name -> components within that package> 506 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 507 508 public PendingPackageBroadcasts() { 509 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 510 } 511 512 public ArrayList<String> get(int userId, String packageName) { 513 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 514 return packages.get(packageName); 515 } 516 517 public void put(int userId, String packageName, ArrayList<String> components) { 518 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 519 packages.put(packageName, components); 520 } 521 522 public void remove(int userId, String packageName) { 523 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 524 if (packages != null) { 525 packages.remove(packageName); 526 } 527 } 528 529 public void remove(int userId) { 530 mUidMap.remove(userId); 531 } 532 533 public int userIdCount() { 534 return mUidMap.size(); 535 } 536 537 public int userIdAt(int n) { 538 return mUidMap.keyAt(n); 539 } 540 541 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 542 return mUidMap.get(userId); 543 } 544 545 public int size() { 546 // total number of pending broadcast entries across all userIds 547 int num = 0; 548 for (int i = 0; i< mUidMap.size(); i++) { 549 num += mUidMap.valueAt(i).size(); 550 } 551 return num; 552 } 553 554 public void clear() { 555 mUidMap.clear(); 556 } 557 558 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 559 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 560 if (map == null) { 561 map = new HashMap<String, ArrayList<String>>(); 562 mUidMap.put(userId, map); 563 } 564 return map; 565 } 566 } 567 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 568 569 // Service Connection to remote media container service to copy 570 // package uri's from external media onto secure containers 571 // or internal storage. 572 private IMediaContainerService mContainerService = null; 573 574 static final int SEND_PENDING_BROADCAST = 1; 575 static final int MCS_BOUND = 3; 576 static final int END_COPY = 4; 577 static final int INIT_COPY = 5; 578 static final int MCS_UNBIND = 6; 579 static final int START_CLEANING_PACKAGE = 7; 580 static final int FIND_INSTALL_LOC = 8; 581 static final int POST_INSTALL = 9; 582 static final int MCS_RECONNECT = 10; 583 static final int MCS_GIVE_UP = 11; 584 static final int UPDATED_MEDIA_STATUS = 12; 585 static final int WRITE_SETTINGS = 13; 586 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 587 static final int PACKAGE_VERIFIED = 15; 588 static final int CHECK_PENDING_VERIFICATION = 16; 589 590 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 591 592 // Delay time in millisecs 593 static final int BROADCAST_DELAY = 10 * 1000; 594 595 static UserManagerService sUserManager; 596 597 // Stores a list of users whose package restrictions file needs to be updated 598 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 599 600 final private DefaultContainerConnection mDefContainerConn = 601 new DefaultContainerConnection(); 602 class DefaultContainerConnection implements ServiceConnection { 603 public void onServiceConnected(ComponentName name, IBinder service) { 604 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 605 IMediaContainerService imcs = 606 IMediaContainerService.Stub.asInterface(service); 607 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 608 } 609 610 public void onServiceDisconnected(ComponentName name) { 611 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 612 } 613 }; 614 615 // Recordkeeping of restore-after-install operations that are currently in flight 616 // between the Package Manager and the Backup Manager 617 class PostInstallData { 618 public InstallArgs args; 619 public PackageInstalledInfo res; 620 621 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 622 args = _a; 623 res = _r; 624 } 625 }; 626 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 627 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 628 629 private final String mRequiredVerifierPackage; 630 631 private final PackageUsage mPackageUsage = new PackageUsage(); 632 633 private class PackageUsage { 634 private static final int WRITE_INTERVAL 635 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 636 637 private final Object mFileLock = new Object(); 638 private final AtomicLong mLastWritten = new AtomicLong(0); 639 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 640 641 private boolean mIsHistoricalPackageUsageAvailable = true; 642 643 boolean isHistoricalPackageUsageAvailable() { 644 return mIsHistoricalPackageUsageAvailable; 645 } 646 647 void write(boolean force) { 648 if (force) { 649 writeInternal(); 650 return; 651 } 652 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 653 && !DEBUG_DEXOPT) { 654 return; 655 } 656 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 657 new Thread("PackageUsage_DiskWriter") { 658 @Override 659 public void run() { 660 try { 661 writeInternal(); 662 } finally { 663 mBackgroundWriteRunning.set(false); 664 } 665 } 666 }.start(); 667 } 668 } 669 670 private void writeInternal() { 671 synchronized (mPackages) { 672 synchronized (mFileLock) { 673 AtomicFile file = getFile(); 674 FileOutputStream f = null; 675 try { 676 f = file.startWrite(); 677 BufferedOutputStream out = new BufferedOutputStream(f); 678 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 679 StringBuilder sb = new StringBuilder(); 680 for (PackageParser.Package pkg : mPackages.values()) { 681 if (pkg.mLastPackageUsageTimeInMills == 0) { 682 continue; 683 } 684 sb.setLength(0); 685 sb.append(pkg.packageName); 686 sb.append(' '); 687 sb.append((long)pkg.mLastPackageUsageTimeInMills); 688 sb.append('\n'); 689 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 690 } 691 out.flush(); 692 file.finishWrite(f); 693 } catch (IOException e) { 694 if (f != null) { 695 file.failWrite(f); 696 } 697 Log.e(TAG, "Failed to write package usage times", e); 698 } 699 } 700 } 701 mLastWritten.set(SystemClock.elapsedRealtime()); 702 } 703 704 void readLP() { 705 synchronized (mFileLock) { 706 AtomicFile file = getFile(); 707 BufferedInputStream in = null; 708 try { 709 in = new BufferedInputStream(file.openRead()); 710 StringBuffer sb = new StringBuffer(); 711 while (true) { 712 String packageName = readToken(in, sb, ' '); 713 if (packageName == null) { 714 break; 715 } 716 String timeInMillisString = readToken(in, sb, '\n'); 717 if (timeInMillisString == null) { 718 throw new IOException("Failed to find last usage time for package " 719 + packageName); 720 } 721 PackageParser.Package pkg = mPackages.get(packageName); 722 if (pkg == null) { 723 continue; 724 } 725 long timeInMillis; 726 try { 727 timeInMillis = Long.parseLong(timeInMillisString.toString()); 728 } catch (NumberFormatException e) { 729 throw new IOException("Failed to parse " + timeInMillisString 730 + " as a long.", e); 731 } 732 pkg.mLastPackageUsageTimeInMills = timeInMillis; 733 } 734 } catch (FileNotFoundException expected) { 735 mIsHistoricalPackageUsageAvailable = false; 736 } catch (IOException e) { 737 Log.w(TAG, "Failed to read package usage times", e); 738 } finally { 739 IoUtils.closeQuietly(in); 740 } 741 } 742 mLastWritten.set(SystemClock.elapsedRealtime()); 743 } 744 745 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 746 throws IOException { 747 sb.setLength(0); 748 while (true) { 749 int ch = in.read(); 750 if (ch == -1) { 751 if (sb.length() == 0) { 752 return null; 753 } 754 throw new IOException("Unexpected EOF"); 755 } 756 if (ch == endOfToken) { 757 return sb.toString(); 758 } 759 sb.append((char)ch); 760 } 761 } 762 763 private AtomicFile getFile() { 764 File dataDir = Environment.getDataDirectory(); 765 File systemDir = new File(dataDir, "system"); 766 File fname = new File(systemDir, "package-usage.list"); 767 return new AtomicFile(fname); 768 } 769 } 770 771 class PackageHandler extends Handler { 772 private boolean mBound = false; 773 final ArrayList<HandlerParams> mPendingInstalls = 774 new ArrayList<HandlerParams>(); 775 776 private boolean connectToService() { 777 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 778 " DefaultContainerService"); 779 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 780 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 781 if (mContext.bindServiceAsUser(service, mDefContainerConn, 782 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 783 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 784 mBound = true; 785 return true; 786 } 787 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 788 return false; 789 } 790 791 private void disconnectService() { 792 mContainerService = null; 793 mBound = false; 794 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 795 mContext.unbindService(mDefContainerConn); 796 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 797 } 798 799 PackageHandler(Looper looper) { 800 super(looper); 801 } 802 803 public void handleMessage(Message msg) { 804 try { 805 doHandleMessage(msg); 806 } finally { 807 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 808 } 809 } 810 811 void doHandleMessage(Message msg) { 812 switch (msg.what) { 813 case INIT_COPY: { 814 HandlerParams params = (HandlerParams) msg.obj; 815 int idx = mPendingInstalls.size(); 816 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 817 // If a bind was already initiated we dont really 818 // need to do anything. The pending install 819 // will be processed later on. 820 if (!mBound) { 821 // If this is the only one pending we might 822 // have to bind to the service again. 823 if (!connectToService()) { 824 Slog.e(TAG, "Failed to bind to media container service"); 825 params.serviceError(); 826 return; 827 } else { 828 // Once we bind to the service, the first 829 // pending request will be processed. 830 mPendingInstalls.add(idx, params); 831 } 832 } else { 833 mPendingInstalls.add(idx, params); 834 // Already bound to the service. Just make 835 // sure we trigger off processing the first request. 836 if (idx == 0) { 837 mHandler.sendEmptyMessage(MCS_BOUND); 838 } 839 } 840 break; 841 } 842 case MCS_BOUND: { 843 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 844 if (msg.obj != null) { 845 mContainerService = (IMediaContainerService) msg.obj; 846 } 847 if (mContainerService == null) { 848 // Something seriously wrong. Bail out 849 Slog.e(TAG, "Cannot bind to media container service"); 850 for (HandlerParams params : mPendingInstalls) { 851 // Indicate service bind error 852 params.serviceError(); 853 } 854 mPendingInstalls.clear(); 855 } else if (mPendingInstalls.size() > 0) { 856 HandlerParams params = mPendingInstalls.get(0); 857 if (params != null) { 858 if (params.startCopy()) { 859 // We are done... look for more work or to 860 // go idle. 861 if (DEBUG_SD_INSTALL) Log.i(TAG, 862 "Checking for more work or unbind..."); 863 // Delete pending install 864 if (mPendingInstalls.size() > 0) { 865 mPendingInstalls.remove(0); 866 } 867 if (mPendingInstalls.size() == 0) { 868 if (mBound) { 869 if (DEBUG_SD_INSTALL) Log.i(TAG, 870 "Posting delayed MCS_UNBIND"); 871 removeMessages(MCS_UNBIND); 872 Message ubmsg = obtainMessage(MCS_UNBIND); 873 // Unbind after a little delay, to avoid 874 // continual thrashing. 875 sendMessageDelayed(ubmsg, 10000); 876 } 877 } else { 878 // There are more pending requests in queue. 879 // Just post MCS_BOUND message to trigger processing 880 // of next pending install. 881 if (DEBUG_SD_INSTALL) Log.i(TAG, 882 "Posting MCS_BOUND for next work"); 883 mHandler.sendEmptyMessage(MCS_BOUND); 884 } 885 } 886 } 887 } else { 888 // Should never happen ideally. 889 Slog.w(TAG, "Empty queue"); 890 } 891 break; 892 } 893 case MCS_RECONNECT: { 894 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 895 if (mPendingInstalls.size() > 0) { 896 if (mBound) { 897 disconnectService(); 898 } 899 if (!connectToService()) { 900 Slog.e(TAG, "Failed to bind to media container service"); 901 for (HandlerParams params : mPendingInstalls) { 902 // Indicate service bind error 903 params.serviceError(); 904 } 905 mPendingInstalls.clear(); 906 } 907 } 908 break; 909 } 910 case MCS_UNBIND: { 911 // If there is no actual work left, then time to unbind. 912 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 913 914 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 915 if (mBound) { 916 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 917 918 disconnectService(); 919 } 920 } else if (mPendingInstalls.size() > 0) { 921 // There are more pending requests in queue. 922 // Just post MCS_BOUND message to trigger processing 923 // of next pending install. 924 mHandler.sendEmptyMessage(MCS_BOUND); 925 } 926 927 break; 928 } 929 case MCS_GIVE_UP: { 930 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 931 mPendingInstalls.remove(0); 932 break; 933 } 934 case SEND_PENDING_BROADCAST: { 935 String packages[]; 936 ArrayList<String> components[]; 937 int size = 0; 938 int uids[]; 939 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 940 synchronized (mPackages) { 941 if (mPendingBroadcasts == null) { 942 return; 943 } 944 size = mPendingBroadcasts.size(); 945 if (size <= 0) { 946 // Nothing to be done. Just return 947 return; 948 } 949 packages = new String[size]; 950 components = new ArrayList[size]; 951 uids = new int[size]; 952 int i = 0; // filling out the above arrays 953 954 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 955 int packageUserId = mPendingBroadcasts.userIdAt(n); 956 Iterator<Map.Entry<String, ArrayList<String>>> it 957 = mPendingBroadcasts.packagesForUserId(packageUserId) 958 .entrySet().iterator(); 959 while (it.hasNext() && i < size) { 960 Map.Entry<String, ArrayList<String>> ent = it.next(); 961 packages[i] = ent.getKey(); 962 components[i] = ent.getValue(); 963 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 964 uids[i] = (ps != null) 965 ? UserHandle.getUid(packageUserId, ps.appId) 966 : -1; 967 i++; 968 } 969 } 970 size = i; 971 mPendingBroadcasts.clear(); 972 } 973 // Send broadcasts 974 for (int i = 0; i < size; i++) { 975 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 976 } 977 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 978 break; 979 } 980 case START_CLEANING_PACKAGE: { 981 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 982 final String packageName = (String)msg.obj; 983 final int userId = msg.arg1; 984 final boolean andCode = msg.arg2 != 0; 985 synchronized (mPackages) { 986 if (userId == UserHandle.USER_ALL) { 987 int[] users = sUserManager.getUserIds(); 988 for (int user : users) { 989 mSettings.addPackageToCleanLPw( 990 new PackageCleanItem(user, packageName, andCode)); 991 } 992 } else { 993 mSettings.addPackageToCleanLPw( 994 new PackageCleanItem(userId, packageName, andCode)); 995 } 996 } 997 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 998 startCleaningPackages(); 999 } break; 1000 case POST_INSTALL: { 1001 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1002 PostInstallData data = mRunningInstalls.get(msg.arg1); 1003 mRunningInstalls.delete(msg.arg1); 1004 boolean deleteOld = false; 1005 1006 if (data != null) { 1007 InstallArgs args = data.args; 1008 PackageInstalledInfo res = data.res; 1009 1010 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1011 res.removedInfo.sendBroadcast(false, true, false); 1012 Bundle extras = new Bundle(1); 1013 extras.putInt(Intent.EXTRA_UID, res.uid); 1014 // Determine the set of users who are adding this 1015 // package for the first time vs. those who are seeing 1016 // an update. 1017 int[] firstUsers; 1018 int[] updateUsers = new int[0]; 1019 if (res.origUsers == null || res.origUsers.length == 0) { 1020 firstUsers = res.newUsers; 1021 } else { 1022 firstUsers = new int[0]; 1023 for (int i=0; i<res.newUsers.length; i++) { 1024 int user = res.newUsers[i]; 1025 boolean isNew = true; 1026 for (int j=0; j<res.origUsers.length; j++) { 1027 if (res.origUsers[j] == user) { 1028 isNew = false; 1029 break; 1030 } 1031 } 1032 if (isNew) { 1033 int[] newFirst = new int[firstUsers.length+1]; 1034 System.arraycopy(firstUsers, 0, newFirst, 0, 1035 firstUsers.length); 1036 newFirst[firstUsers.length] = user; 1037 firstUsers = newFirst; 1038 } else { 1039 int[] newUpdate = new int[updateUsers.length+1]; 1040 System.arraycopy(updateUsers, 0, newUpdate, 0, 1041 updateUsers.length); 1042 newUpdate[updateUsers.length] = user; 1043 updateUsers = newUpdate; 1044 } 1045 } 1046 } 1047 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1048 res.pkg.applicationInfo.packageName, 1049 extras, null, null, firstUsers); 1050 final boolean update = res.removedInfo.removedPackage != null; 1051 if (update) { 1052 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1053 } 1054 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1055 res.pkg.applicationInfo.packageName, 1056 extras, null, null, updateUsers); 1057 if (update) { 1058 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1059 res.pkg.applicationInfo.packageName, 1060 extras, null, null, updateUsers); 1061 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1062 null, null, 1063 res.pkg.applicationInfo.packageName, null, updateUsers); 1064 1065 // treat asec-hosted packages like removable media on upgrade 1066 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1067 if (DEBUG_INSTALL) { 1068 Slog.i(TAG, "upgrading pkg " + res.pkg 1069 + " is ASEC-hosted -> AVAILABLE"); 1070 } 1071 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1072 ArrayList<String> pkgList = new ArrayList<String>(1); 1073 pkgList.add(res.pkg.applicationInfo.packageName); 1074 sendResourcesChangedBroadcast(true, true, 1075 pkgList,uidArray, null); 1076 } 1077 } 1078 if (res.removedInfo.args != null) { 1079 // Remove the replaced package's older resources safely now 1080 deleteOld = true; 1081 } 1082 1083 // Log current value of "unknown sources" setting 1084 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1085 getUnknownSourcesSettings()); 1086 } 1087 // Force a gc to clear up things 1088 Runtime.getRuntime().gc(); 1089 // We delete after a gc for applications on sdcard. 1090 if (deleteOld) { 1091 synchronized (mInstallLock) { 1092 res.removedInfo.args.doPostDeleteLI(true); 1093 } 1094 } 1095 if (args.observer != null) { 1096 try { 1097 Bundle extras = extrasForInstallResult(res); 1098 args.observer.packageInstalled(res.name, extras, res.returnCode, 1099 res.returnMsg); 1100 } catch (RemoteException e) { 1101 Slog.i(TAG, "Observer no longer exists."); 1102 } 1103 } 1104 } else { 1105 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1106 } 1107 } break; 1108 case UPDATED_MEDIA_STATUS: { 1109 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1110 boolean reportStatus = msg.arg1 == 1; 1111 boolean doGc = msg.arg2 == 1; 1112 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1113 if (doGc) { 1114 // Force a gc to clear up stale containers. 1115 Runtime.getRuntime().gc(); 1116 } 1117 if (msg.obj != null) { 1118 @SuppressWarnings("unchecked") 1119 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1120 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1121 // Unload containers 1122 unloadAllContainers(args); 1123 } 1124 if (reportStatus) { 1125 try { 1126 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1127 PackageHelper.getMountService().finishMediaUpdate(); 1128 } catch (RemoteException e) { 1129 Log.e(TAG, "MountService not running?"); 1130 } 1131 } 1132 } break; 1133 case WRITE_SETTINGS: { 1134 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1135 synchronized (mPackages) { 1136 removeMessages(WRITE_SETTINGS); 1137 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1138 mSettings.writeLPr(); 1139 mDirtyUsers.clear(); 1140 } 1141 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1142 } break; 1143 case WRITE_PACKAGE_RESTRICTIONS: { 1144 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1145 synchronized (mPackages) { 1146 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1147 for (int userId : mDirtyUsers) { 1148 mSettings.writePackageRestrictionsLPr(userId); 1149 } 1150 mDirtyUsers.clear(); 1151 } 1152 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1153 } break; 1154 case CHECK_PENDING_VERIFICATION: { 1155 final int verificationId = msg.arg1; 1156 final PackageVerificationState state = mPendingVerification.get(verificationId); 1157 1158 if ((state != null) && !state.timeoutExtended()) { 1159 final InstallArgs args = state.getInstallArgs(); 1160 final Uri originUri = Uri.fromFile(args.originFile); 1161 1162 Slog.i(TAG, "Verification timed out for " + originUri); 1163 mPendingVerification.remove(verificationId); 1164 1165 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1166 1167 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1168 Slog.i(TAG, "Continuing with installation of " + originUri); 1169 state.setVerifierResponse(Binder.getCallingUid(), 1170 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1171 broadcastPackageVerified(verificationId, originUri, 1172 PackageManager.VERIFICATION_ALLOW, 1173 state.getInstallArgs().getUser()); 1174 try { 1175 ret = args.copyApk(mContainerService, true); 1176 } catch (RemoteException e) { 1177 Slog.e(TAG, "Could not contact the ContainerService"); 1178 } 1179 } else { 1180 broadcastPackageVerified(verificationId, originUri, 1181 PackageManager.VERIFICATION_REJECT, 1182 state.getInstallArgs().getUser()); 1183 } 1184 1185 processPendingInstall(args, ret); 1186 mHandler.sendEmptyMessage(MCS_UNBIND); 1187 } 1188 break; 1189 } 1190 case PACKAGE_VERIFIED: { 1191 final int verificationId = msg.arg1; 1192 1193 final PackageVerificationState state = mPendingVerification.get(verificationId); 1194 if (state == null) { 1195 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1196 break; 1197 } 1198 1199 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1200 1201 state.setVerifierResponse(response.callerUid, response.code); 1202 1203 if (state.isVerificationComplete()) { 1204 mPendingVerification.remove(verificationId); 1205 1206 final InstallArgs args = state.getInstallArgs(); 1207 final Uri originUri = Uri.fromFile(args.originFile); 1208 1209 int ret; 1210 if (state.isInstallAllowed()) { 1211 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1212 broadcastPackageVerified(verificationId, originUri, 1213 response.code, state.getInstallArgs().getUser()); 1214 try { 1215 ret = args.copyApk(mContainerService, true); 1216 } catch (RemoteException e) { 1217 Slog.e(TAG, "Could not contact the ContainerService"); 1218 } 1219 } else { 1220 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1221 } 1222 1223 processPendingInstall(args, ret); 1224 1225 mHandler.sendEmptyMessage(MCS_UNBIND); 1226 } 1227 1228 break; 1229 } 1230 } 1231 } 1232 } 1233 1234 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1235 Bundle extras = null; 1236 switch (res.returnCode) { 1237 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1238 extras = new Bundle(); 1239 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1240 res.origPermission); 1241 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1242 res.origPackage); 1243 break; 1244 } 1245 } 1246 return extras; 1247 } 1248 1249 void scheduleWriteSettingsLocked() { 1250 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1251 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1252 } 1253 } 1254 1255 void scheduleWritePackageRestrictionsLocked(int userId) { 1256 if (!sUserManager.exists(userId)) return; 1257 mDirtyUsers.add(userId); 1258 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1259 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1260 } 1261 } 1262 1263 public static final PackageManagerService main(Context context, Installer installer, 1264 boolean factoryTest, boolean onlyCore) { 1265 PackageManagerService m = new PackageManagerService(context, installer, 1266 factoryTest, onlyCore); 1267 ServiceManager.addService("package", m); 1268 return m; 1269 } 1270 1271 static String[] splitString(String str, char sep) { 1272 int count = 1; 1273 int i = 0; 1274 while ((i=str.indexOf(sep, i)) >= 0) { 1275 count++; 1276 i++; 1277 } 1278 1279 String[] res = new String[count]; 1280 i=0; 1281 count = 0; 1282 int lastI=0; 1283 while ((i=str.indexOf(sep, i)) >= 0) { 1284 res[count] = str.substring(lastI, i); 1285 count++; 1286 i++; 1287 lastI = i; 1288 } 1289 res[count] = str.substring(lastI, str.length()); 1290 return res; 1291 } 1292 1293 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1294 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1295 Context.DISPLAY_SERVICE); 1296 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1297 } 1298 1299 public PackageManagerService(Context context, Installer installer, 1300 boolean factoryTest, boolean onlyCore) { 1301 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1302 SystemClock.uptimeMillis()); 1303 1304 if (mSdkVersion <= 0) { 1305 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1306 } 1307 1308 mContext = context; 1309 mFactoryTest = factoryTest; 1310 mOnlyCore = onlyCore; 1311 mMetrics = new DisplayMetrics(); 1312 mSettings = new Settings(context); 1313 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1314 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1315 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1316 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1317 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1318 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1319 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1320 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1321 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1322 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1323 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1324 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1325 1326 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1327 if (separateProcesses != null && separateProcesses.length() > 0) { 1328 if ("*".equals(separateProcesses)) { 1329 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1330 mSeparateProcesses = null; 1331 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1332 } else { 1333 mDefParseFlags = 0; 1334 mSeparateProcesses = separateProcesses.split(","); 1335 Slog.w(TAG, "Running with debug.separate_processes: " 1336 + separateProcesses); 1337 } 1338 } else { 1339 mDefParseFlags = 0; 1340 mSeparateProcesses = null; 1341 } 1342 1343 mInstaller = installer; 1344 1345 getDefaultDisplayMetrics(context, mMetrics); 1346 1347 SystemConfig systemConfig = SystemConfig.getInstance(); 1348 mGlobalGids = systemConfig.getGlobalGids(); 1349 mSystemPermissions = systemConfig.getSystemPermissions(); 1350 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1351 1352 synchronized (mInstallLock) { 1353 // writer 1354 synchronized (mPackages) { 1355 mHandlerThread = new ServiceThread(TAG, 1356 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1357 mHandlerThread.start(); 1358 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1359 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1360 1361 File dataDir = Environment.getDataDirectory(); 1362 mAppDataDir = new File(dataDir, "data"); 1363 mAppInstallDir = new File(dataDir, "app"); 1364 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1365 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1366 mUserAppDataDir = new File(dataDir, "user"); 1367 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1368 1369 sUserManager = new UserManagerService(context, this, 1370 mInstallLock, mPackages); 1371 1372 // Propagate permission configuration in to package manager. 1373 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1374 = systemConfig.getPermissions(); 1375 for (int i=0; i<permConfig.size(); i++) { 1376 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1377 BasePermission bp = mSettings.mPermissions.get(perm.name); 1378 if (bp == null) { 1379 bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN); 1380 mSettings.mPermissions.put(perm.name, bp); 1381 } 1382 if (perm.gids != null) { 1383 bp.gids = appendInts(bp.gids, perm.gids); 1384 } 1385 } 1386 1387 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1388 for (int i=0; i<libConfig.size(); i++) { 1389 mSharedLibraries.put(libConfig.keyAt(i), 1390 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1391 } 1392 1393 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1394 1395 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1396 mSdkVersion, mOnlyCore); 1397 1398 String customResolverActivity = Resources.getSystem().getString( 1399 R.string.config_customResolverActivity); 1400 if (TextUtils.isEmpty(customResolverActivity)) { 1401 customResolverActivity = null; 1402 } else { 1403 mCustomResolverComponentName = ComponentName.unflattenFromString( 1404 customResolverActivity); 1405 } 1406 1407 long startTime = SystemClock.uptimeMillis(); 1408 1409 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1410 startTime); 1411 1412 // Set flag to monitor and not change apk file paths when 1413 // scanning install directories. 1414 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1415 1416 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1417 1418 /** 1419 * Add everything in the in the boot class path to the 1420 * list of process files because dexopt will have been run 1421 * if necessary during zygote startup. 1422 */ 1423 String bootClassPath = System.getProperty("java.boot.class.path"); 1424 if (bootClassPath != null) { 1425 String[] paths = splitString(bootClassPath, ':'); 1426 for (int i=0; i<paths.length; i++) { 1427 alreadyDexOpted.add(paths[i]); 1428 } 1429 } else { 1430 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1431 } 1432 1433 boolean didDexOptLibraryOrTool = false; 1434 1435 final List<String> instructionSets = getAllInstructionSets(); 1436 1437 /** 1438 * Ensure all external libraries have had dexopt run on them. 1439 */ 1440 if (mSharedLibraries.size() > 0) { 1441 // NOTE: For now, we're compiling these system "shared libraries" 1442 // (and framework jars) into all available architectures. It's possible 1443 // to compile them only when we come across an app that uses them (there's 1444 // already logic for that in scanPackageLI) but that adds some complexity. 1445 for (String instructionSet : instructionSets) { 1446 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1447 final String lib = libEntry.path; 1448 if (lib == null) { 1449 continue; 1450 } 1451 1452 try { 1453 if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) { 1454 alreadyDexOpted.add(lib); 1455 1456 // The list of "shared libraries" we have at this point is 1457 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet); 1458 didDexOptLibraryOrTool = true; 1459 } 1460 } catch (FileNotFoundException e) { 1461 Slog.w(TAG, "Library not found: " + lib); 1462 } catch (IOException e) { 1463 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1464 + e.getMessage()); 1465 } 1466 } 1467 } 1468 } 1469 1470 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1471 1472 // Gross hack for now: we know this file doesn't contain any 1473 // code, so don't dexopt it to avoid the resulting log spew. 1474 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1475 1476 // Gross hack for now: we know this file is only part of 1477 // the boot class path for art, so don't dexopt it to 1478 // avoid the resulting log spew. 1479 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1480 1481 /** 1482 * And there are a number of commands implemented in Java, which 1483 * we currently need to do the dexopt on so that they can be 1484 * run from a non-root shell. 1485 */ 1486 String[] frameworkFiles = frameworkDir.list(); 1487 if (frameworkFiles != null) { 1488 // TODO: We could compile these only for the most preferred ABI. We should 1489 // first double check that the dex files for these commands are not referenced 1490 // by other system apps. 1491 for (String instructionSet : instructionSets) { 1492 for (int i=0; i<frameworkFiles.length; i++) { 1493 File libPath = new File(frameworkDir, frameworkFiles[i]); 1494 String path = libPath.getPath(); 1495 // Skip the file if we already did it. 1496 if (alreadyDexOpted.contains(path)) { 1497 continue; 1498 } 1499 // Skip the file if it is not a type we want to dexopt. 1500 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1501 continue; 1502 } 1503 try { 1504 if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) { 1505 mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet); 1506 didDexOptLibraryOrTool = true; 1507 } 1508 } catch (FileNotFoundException e) { 1509 Slog.w(TAG, "Jar not found: " + path); 1510 } catch (IOException e) { 1511 Slog.w(TAG, "Exception reading jar: " + path, e); 1512 } 1513 } 1514 } 1515 } 1516 1517 if (didDexOptLibraryOrTool) { 1518 // If we dexopted a library or tool, then something on the system has 1519 // changed. Consider this significant, and wipe away all other 1520 // existing dexopt files to ensure we don't leave any dangling around. 1521 // 1522 // TODO: This should be revisited because it isn't as good an indicator 1523 // as it used to be. It used to include the boot classpath but at some point 1524 // DexFile.isDexOptNeeded started returning false for the boot 1525 // class path files in all cases. It is very possible in a 1526 // small maintenance release update that the library and tool 1527 // jars may be unchanged but APK could be removed resulting in 1528 // unused dalvik-cache files. 1529 for (String instructionSet : instructionSets) { 1530 mInstaller.pruneDexCache(instructionSet); 1531 } 1532 1533 // Additionally, delete all dex files from the root directory 1534 // since there shouldn't be any there anyway, unless we're upgrading 1535 // from an older OS version or a build that contained the "old" style 1536 // flat scheme. 1537 mInstaller.pruneDexCache("."); 1538 } 1539 1540 // Collect vendor overlay packages. 1541 // (Do this before scanning any apps.) 1542 // For security and version matching reason, only consider 1543 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1544 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1545 mVendorOverlayInstallObserver = new AppDirObserver( 1546 vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false); 1547 mVendorOverlayInstallObserver.startWatching(); 1548 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1549 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1550 1551 // Find base frameworks (resource packages without code). 1552 mFrameworkInstallObserver = new AppDirObserver( 1553 frameworkDir.getPath(), OBSERVER_EVENTS, true, false); 1554 mFrameworkInstallObserver.startWatching(); 1555 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1556 | PackageParser.PARSE_IS_SYSTEM_DIR 1557 | PackageParser.PARSE_IS_PRIVILEGED, 1558 scanMode | SCAN_NO_DEX, 0); 1559 1560 // Collected privileged system packages. 1561 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1562 mPrivilegedInstallObserver = new AppDirObserver( 1563 privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true); 1564 mPrivilegedInstallObserver.startWatching(); 1565 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1566 | PackageParser.PARSE_IS_SYSTEM_DIR 1567 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1568 1569 // Collect ordinary system packages. 1570 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1571 mSystemInstallObserver = new AppDirObserver( 1572 systemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1573 mSystemInstallObserver.startWatching(); 1574 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1575 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1576 1577 // Collect all vendor packages. 1578 File vendorAppDir = new File("/vendor/app"); 1579 try { 1580 vendorAppDir = vendorAppDir.getCanonicalFile(); 1581 } catch (IOException e) { 1582 // failed to look up canonical path, continue with original one 1583 } 1584 mVendorInstallObserver = new AppDirObserver( 1585 vendorAppDir.getPath(), OBSERVER_EVENTS, true, false); 1586 mVendorInstallObserver.startWatching(); 1587 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1588 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1589 1590 // Collect all OEM packages. 1591 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1592 mOemInstallObserver = new AppDirObserver( 1593 oemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1594 mOemInstallObserver.startWatching(); 1595 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1596 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1597 1598 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1599 mInstaller.moveFiles(); 1600 1601 // Prune any system packages that no longer exist. 1602 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1603 if (!mOnlyCore) { 1604 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1605 while (psit.hasNext()) { 1606 PackageSetting ps = psit.next(); 1607 1608 /* 1609 * If this is not a system app, it can't be a 1610 * disable system app. 1611 */ 1612 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1613 continue; 1614 } 1615 1616 /* 1617 * If the package is scanned, it's not erased. 1618 */ 1619 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1620 if (scannedPkg != null) { 1621 /* 1622 * If the system app is both scanned and in the 1623 * disabled packages list, then it must have been 1624 * added via OTA. Remove it from the currently 1625 * scanned package so the previously user-installed 1626 * application can be scanned. 1627 */ 1628 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1629 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1630 + "; removing system app"); 1631 removePackageLI(ps, true); 1632 } 1633 1634 continue; 1635 } 1636 1637 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1638 psit.remove(); 1639 String msg = "System package " + ps.name 1640 + " no longer exists; wiping its data"; 1641 reportSettingsProblem(Log.WARN, msg); 1642 removeDataDirsLI(ps.name); 1643 } else { 1644 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1645 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1646 possiblyDeletedUpdatedSystemApps.add(ps.name); 1647 } 1648 } 1649 } 1650 } 1651 1652 //look for any incomplete package installations 1653 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1654 //clean up list 1655 for(int i = 0; i < deletePkgsList.size(); i++) { 1656 //clean up here 1657 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1658 } 1659 //delete tmp files 1660 deleteTempPackageFiles(); 1661 1662 // Remove any shared userIDs that have no associated packages 1663 mSettings.pruneSharedUsersLPw(); 1664 1665 if (!mOnlyCore) { 1666 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1667 SystemClock.uptimeMillis()); 1668 mAppInstallObserver = new AppDirObserver( 1669 mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1670 mAppInstallObserver.startWatching(); 1671 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1672 1673 mDrmAppInstallObserver = new AppDirObserver( 1674 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1675 mDrmAppInstallObserver.startWatching(); 1676 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1677 scanMode, 0); 1678 1679 /** 1680 * Remove disable package settings for any updated system 1681 * apps that were removed via an OTA. If they're not a 1682 * previously-updated app, remove them completely. 1683 * Otherwise, just revoke their system-level permissions. 1684 */ 1685 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1686 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1687 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1688 1689 String msg; 1690 if (deletedPkg == null) { 1691 msg = "Updated system package " + deletedAppName 1692 + " no longer exists; wiping its data"; 1693 removeDataDirsLI(deletedAppName); 1694 } else { 1695 msg = "Updated system app + " + deletedAppName 1696 + " no longer present; removing system privileges for " 1697 + deletedAppName; 1698 1699 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1700 1701 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1702 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1703 } 1704 reportSettingsProblem(Log.WARN, msg); 1705 } 1706 } else { 1707 mAppInstallObserver = null; 1708 mDrmAppInstallObserver = null; 1709 } 1710 1711 // Now that we know all of the shared libraries, update all clients to have 1712 // the correct library paths. 1713 updateAllSharedLibrariesLPw(); 1714 1715 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1716 // NOTE: We ignore potential failures here during a system scan (like 1717 // the rest of the commands above) because there's precious little we 1718 // can do about it. A settings error is reported, though. 1719 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1720 false /* force dexopt */, false /* defer dexopt */); 1721 } 1722 1723 // Now that we know all the packages we are keeping, 1724 // read and update their last usage times. 1725 mPackageUsage.readLP(); 1726 1727 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1728 SystemClock.uptimeMillis()); 1729 Slog.i(TAG, "Time to scan packages: " 1730 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1731 + " seconds"); 1732 1733 // If the platform SDK has changed since the last time we booted, 1734 // we need to re-grant app permission to catch any new ones that 1735 // appear. This is really a hack, and means that apps can in some 1736 // cases get permissions that the user didn't initially explicitly 1737 // allow... it would be nice to have some better way to handle 1738 // this situation. 1739 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1740 != mSdkVersion; 1741 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1742 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1743 + "; regranting permissions for internal storage"); 1744 mSettings.mInternalSdkPlatform = mSdkVersion; 1745 1746 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1747 | (regrantPermissions 1748 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1749 : 0)); 1750 1751 // If this is the first boot, and it is a normal boot, then 1752 // we need to initialize the default preferred apps. 1753 if (!mRestoredSettings && !onlyCore) { 1754 mSettings.readDefaultPreferredAppsLPw(this, 0); 1755 } 1756 1757 // If this is first boot after an OTA, and a normal boot, then 1758 // we need to clear code cache directories. 1759 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1760 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1761 for (String pkgName : mSettings.mPackages.keySet()) { 1762 deleteCodeCacheDirsLI(pkgName); 1763 } 1764 mSettings.mFingerprint = Build.FINGERPRINT; 1765 } 1766 1767 // All the changes are done during package scanning. 1768 mSettings.updateInternalDatabaseVersion(); 1769 1770 // can downgrade to reader 1771 mSettings.writeLPr(); 1772 1773 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1774 SystemClock.uptimeMillis()); 1775 1776 1777 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1778 } // synchronized (mPackages) 1779 } // synchronized (mInstallLock) 1780 1781 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1782 1783 // Now after opening every single application zip, make sure they 1784 // are all flushed. Not really needed, but keeps things nice and 1785 // tidy. 1786 Runtime.getRuntime().gc(); 1787 } 1788 1789 @Override 1790 public boolean isFirstBoot() { 1791 return !mRestoredSettings; 1792 } 1793 1794 @Override 1795 public boolean isOnlyCoreApps() { 1796 return mOnlyCore; 1797 } 1798 1799 private String getRequiredVerifierLPr() { 1800 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1801 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1802 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1803 1804 String requiredVerifier = null; 1805 1806 final int N = receivers.size(); 1807 for (int i = 0; i < N; i++) { 1808 final ResolveInfo info = receivers.get(i); 1809 1810 if (info.activityInfo == null) { 1811 continue; 1812 } 1813 1814 final String packageName = info.activityInfo.packageName; 1815 1816 final PackageSetting ps = mSettings.mPackages.get(packageName); 1817 if (ps == null) { 1818 continue; 1819 } 1820 1821 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1822 if (!gp.grantedPermissions 1823 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1824 continue; 1825 } 1826 1827 if (requiredVerifier != null) { 1828 throw new RuntimeException("There can be only one required verifier"); 1829 } 1830 1831 requiredVerifier = packageName; 1832 } 1833 1834 return requiredVerifier; 1835 } 1836 1837 @Override 1838 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1839 throws RemoteException { 1840 try { 1841 return super.onTransact(code, data, reply, flags); 1842 } catch (RuntimeException e) { 1843 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1844 Slog.wtf(TAG, "Package Manager Crash", e); 1845 } 1846 throw e; 1847 } 1848 } 1849 1850 void cleanupInstallFailedPackage(PackageSetting ps) { 1851 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1852 removeDataDirsLI(ps.name); 1853 1854 // TODO: try cleaning up codePath directory contents first, since it 1855 // might be a cluster 1856 1857 if (ps.codePath != null) { 1858 if (!ps.codePath.delete()) { 1859 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1860 } 1861 } 1862 if (ps.resourcePath != null) { 1863 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1864 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1865 } 1866 } 1867 mSettings.removePackageLPw(ps.name); 1868 } 1869 1870 static int[] appendInts(int[] cur, int[] add) { 1871 if (add == null) return cur; 1872 if (cur == null) return add; 1873 final int N = add.length; 1874 for (int i=0; i<N; i++) { 1875 cur = appendInt(cur, add[i]); 1876 } 1877 return cur; 1878 } 1879 1880 static int[] removeInts(int[] cur, int[] rem) { 1881 if (rem == null) return cur; 1882 if (cur == null) return cur; 1883 final int N = rem.length; 1884 for (int i=0; i<N; i++) { 1885 cur = removeInt(cur, rem[i]); 1886 } 1887 return cur; 1888 } 1889 1890 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1891 if (!sUserManager.exists(userId)) return null; 1892 final PackageSetting ps = (PackageSetting) p.mExtras; 1893 if (ps == null) { 1894 return null; 1895 } 1896 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1897 final PackageUserState state = ps.readUserState(userId); 1898 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1899 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1900 state, userId); 1901 } 1902 1903 @Override 1904 public boolean isPackageAvailable(String packageName, int userId) { 1905 if (!sUserManager.exists(userId)) return false; 1906 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1907 synchronized (mPackages) { 1908 PackageParser.Package p = mPackages.get(packageName); 1909 if (p != null) { 1910 final PackageSetting ps = (PackageSetting) p.mExtras; 1911 if (ps != null) { 1912 final PackageUserState state = ps.readUserState(userId); 1913 if (state != null) { 1914 return PackageParser.isAvailable(state); 1915 } 1916 } 1917 } 1918 } 1919 return false; 1920 } 1921 1922 @Override 1923 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1924 if (!sUserManager.exists(userId)) return null; 1925 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1926 // reader 1927 synchronized (mPackages) { 1928 PackageParser.Package p = mPackages.get(packageName); 1929 if (DEBUG_PACKAGE_INFO) 1930 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1931 if (p != null) { 1932 return generatePackageInfo(p, flags, userId); 1933 } 1934 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1935 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1936 } 1937 } 1938 return null; 1939 } 1940 1941 @Override 1942 public String[] currentToCanonicalPackageNames(String[] names) { 1943 String[] out = new String[names.length]; 1944 // reader 1945 synchronized (mPackages) { 1946 for (int i=names.length-1; i>=0; i--) { 1947 PackageSetting ps = mSettings.mPackages.get(names[i]); 1948 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1949 } 1950 } 1951 return out; 1952 } 1953 1954 @Override 1955 public String[] canonicalToCurrentPackageNames(String[] names) { 1956 String[] out = new String[names.length]; 1957 // reader 1958 synchronized (mPackages) { 1959 for (int i=names.length-1; i>=0; i--) { 1960 String cur = mSettings.mRenamedPackages.get(names[i]); 1961 out[i] = cur != null ? cur : names[i]; 1962 } 1963 } 1964 return out; 1965 } 1966 1967 @Override 1968 public int getPackageUid(String packageName, int userId) { 1969 if (!sUserManager.exists(userId)) return -1; 1970 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1971 // reader 1972 synchronized (mPackages) { 1973 PackageParser.Package p = mPackages.get(packageName); 1974 if(p != null) { 1975 return UserHandle.getUid(userId, p.applicationInfo.uid); 1976 } 1977 PackageSetting ps = mSettings.mPackages.get(packageName); 1978 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1979 return -1; 1980 } 1981 p = ps.pkg; 1982 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1983 } 1984 } 1985 1986 @Override 1987 public int[] getPackageGids(String packageName) { 1988 // reader 1989 synchronized (mPackages) { 1990 PackageParser.Package p = mPackages.get(packageName); 1991 if (DEBUG_PACKAGE_INFO) 1992 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1993 if (p != null) { 1994 final PackageSetting ps = (PackageSetting)p.mExtras; 1995 return ps.getGids(); 1996 } 1997 } 1998 // stupid thing to indicate an error. 1999 return new int[0]; 2000 } 2001 2002 static final PermissionInfo generatePermissionInfo( 2003 BasePermission bp, int flags) { 2004 if (bp.perm != null) { 2005 return PackageParser.generatePermissionInfo(bp.perm, flags); 2006 } 2007 PermissionInfo pi = new PermissionInfo(); 2008 pi.name = bp.name; 2009 pi.packageName = bp.sourcePackage; 2010 pi.nonLocalizedLabel = bp.name; 2011 pi.protectionLevel = bp.protectionLevel; 2012 return pi; 2013 } 2014 2015 @Override 2016 public PermissionInfo getPermissionInfo(String name, int flags) { 2017 // reader 2018 synchronized (mPackages) { 2019 final BasePermission p = mSettings.mPermissions.get(name); 2020 if (p != null) { 2021 return generatePermissionInfo(p, flags); 2022 } 2023 return null; 2024 } 2025 } 2026 2027 @Override 2028 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2029 // reader 2030 synchronized (mPackages) { 2031 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2032 for (BasePermission p : mSettings.mPermissions.values()) { 2033 if (group == null) { 2034 if (p.perm == null || p.perm.info.group == null) { 2035 out.add(generatePermissionInfo(p, flags)); 2036 } 2037 } else { 2038 if (p.perm != null && group.equals(p.perm.info.group)) { 2039 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2040 } 2041 } 2042 } 2043 2044 if (out.size() > 0) { 2045 return out; 2046 } 2047 return mPermissionGroups.containsKey(group) ? out : null; 2048 } 2049 } 2050 2051 @Override 2052 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2053 // reader 2054 synchronized (mPackages) { 2055 return PackageParser.generatePermissionGroupInfo( 2056 mPermissionGroups.get(name), flags); 2057 } 2058 } 2059 2060 @Override 2061 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2062 // reader 2063 synchronized (mPackages) { 2064 final int N = mPermissionGroups.size(); 2065 ArrayList<PermissionGroupInfo> out 2066 = new ArrayList<PermissionGroupInfo>(N); 2067 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2068 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2069 } 2070 return out; 2071 } 2072 } 2073 2074 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2075 int userId) { 2076 if (!sUserManager.exists(userId)) return null; 2077 PackageSetting ps = mSettings.mPackages.get(packageName); 2078 if (ps != null) { 2079 if (ps.pkg == null) { 2080 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2081 flags, userId); 2082 if (pInfo != null) { 2083 return pInfo.applicationInfo; 2084 } 2085 return null; 2086 } 2087 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2088 ps.readUserState(userId), userId); 2089 } 2090 return null; 2091 } 2092 2093 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2094 int userId) { 2095 if (!sUserManager.exists(userId)) return null; 2096 PackageSetting ps = mSettings.mPackages.get(packageName); 2097 if (ps != null) { 2098 PackageParser.Package pkg = ps.pkg; 2099 if (pkg == null) { 2100 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2101 return null; 2102 } 2103 // Only data remains, so we aren't worried about code paths 2104 pkg = new PackageParser.Package(packageName); 2105 pkg.applicationInfo.packageName = packageName; 2106 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2107 pkg.applicationInfo.dataDir = 2108 getDataPathForPackage(packageName, 0).getPath(); 2109 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2110 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2111 } 2112 return generatePackageInfo(pkg, flags, userId); 2113 } 2114 return null; 2115 } 2116 2117 @Override 2118 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2119 if (!sUserManager.exists(userId)) return null; 2120 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2121 // writer 2122 synchronized (mPackages) { 2123 PackageParser.Package p = mPackages.get(packageName); 2124 if (DEBUG_PACKAGE_INFO) Log.v( 2125 TAG, "getApplicationInfo " + packageName 2126 + ": " + p); 2127 if (p != null) { 2128 PackageSetting ps = mSettings.mPackages.get(packageName); 2129 if (ps == null) return null; 2130 // Note: isEnabledLP() does not apply here - always return info 2131 return PackageParser.generateApplicationInfo( 2132 p, flags, ps.readUserState(userId), userId); 2133 } 2134 if ("android".equals(packageName)||"system".equals(packageName)) { 2135 return mAndroidApplication; 2136 } 2137 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2138 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2139 } 2140 } 2141 return null; 2142 } 2143 2144 2145 @Override 2146 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2147 mContext.enforceCallingOrSelfPermission( 2148 android.Manifest.permission.CLEAR_APP_CACHE, null); 2149 // Queue up an async operation since clearing cache may take a little while. 2150 mHandler.post(new Runnable() { 2151 public void run() { 2152 mHandler.removeCallbacks(this); 2153 int retCode = -1; 2154 synchronized (mInstallLock) { 2155 retCode = mInstaller.freeCache(freeStorageSize); 2156 if (retCode < 0) { 2157 Slog.w(TAG, "Couldn't clear application caches"); 2158 } 2159 } 2160 if (observer != null) { 2161 try { 2162 observer.onRemoveCompleted(null, (retCode >= 0)); 2163 } catch (RemoteException e) { 2164 Slog.w(TAG, "RemoveException when invoking call back"); 2165 } 2166 } 2167 } 2168 }); 2169 } 2170 2171 @Override 2172 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2173 mContext.enforceCallingOrSelfPermission( 2174 android.Manifest.permission.CLEAR_APP_CACHE, null); 2175 // Queue up an async operation since clearing cache may take a little while. 2176 mHandler.post(new Runnable() { 2177 public void run() { 2178 mHandler.removeCallbacks(this); 2179 int retCode = -1; 2180 synchronized (mInstallLock) { 2181 retCode = mInstaller.freeCache(freeStorageSize); 2182 if (retCode < 0) { 2183 Slog.w(TAG, "Couldn't clear application caches"); 2184 } 2185 } 2186 if(pi != null) { 2187 try { 2188 // Callback via pending intent 2189 int code = (retCode >= 0) ? 1 : 0; 2190 pi.sendIntent(null, code, null, 2191 null, null); 2192 } catch (SendIntentException e1) { 2193 Slog.i(TAG, "Failed to send pending intent"); 2194 } 2195 } 2196 } 2197 }); 2198 } 2199 2200 void freeStorage(long freeStorageSize) throws IOException { 2201 synchronized (mInstallLock) { 2202 if (mInstaller.freeCache(freeStorageSize) < 0) { 2203 throw new IOException("Failed to free enough space"); 2204 } 2205 } 2206 } 2207 2208 @Override 2209 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2210 if (!sUserManager.exists(userId)) return null; 2211 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2212 synchronized (mPackages) { 2213 PackageParser.Activity a = mActivities.mActivities.get(component); 2214 2215 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2216 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2217 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2218 if (ps == null) return null; 2219 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2220 userId); 2221 } 2222 if (mResolveComponentName.equals(component)) { 2223 return mResolveActivity; 2224 } 2225 } 2226 return null; 2227 } 2228 2229 @Override 2230 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2231 String resolvedType) { 2232 synchronized (mPackages) { 2233 PackageParser.Activity a = mActivities.mActivities.get(component); 2234 if (a == null) { 2235 return false; 2236 } 2237 for (int i=0; i<a.intents.size(); i++) { 2238 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2239 intent.getData(), intent.getCategories(), TAG) >= 0) { 2240 return true; 2241 } 2242 } 2243 return false; 2244 } 2245 } 2246 2247 @Override 2248 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2249 if (!sUserManager.exists(userId)) return null; 2250 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2251 synchronized (mPackages) { 2252 PackageParser.Activity a = mReceivers.mActivities.get(component); 2253 if (DEBUG_PACKAGE_INFO) Log.v( 2254 TAG, "getReceiverInfo " + component + ": " + a); 2255 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2256 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2257 if (ps == null) return null; 2258 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2259 userId); 2260 } 2261 } 2262 return null; 2263 } 2264 2265 @Override 2266 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2267 if (!sUserManager.exists(userId)) return null; 2268 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2269 synchronized (mPackages) { 2270 PackageParser.Service s = mServices.mServices.get(component); 2271 if (DEBUG_PACKAGE_INFO) Log.v( 2272 TAG, "getServiceInfo " + component + ": " + s); 2273 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2274 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2275 if (ps == null) return null; 2276 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2277 userId); 2278 } 2279 } 2280 return null; 2281 } 2282 2283 @Override 2284 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2285 if (!sUserManager.exists(userId)) return null; 2286 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2287 synchronized (mPackages) { 2288 PackageParser.Provider p = mProviders.mProviders.get(component); 2289 if (DEBUG_PACKAGE_INFO) Log.v( 2290 TAG, "getProviderInfo " + component + ": " + p); 2291 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2292 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2293 if (ps == null) return null; 2294 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2295 userId); 2296 } 2297 } 2298 return null; 2299 } 2300 2301 @Override 2302 public String[] getSystemSharedLibraryNames() { 2303 Set<String> libSet; 2304 synchronized (mPackages) { 2305 libSet = mSharedLibraries.keySet(); 2306 int size = libSet.size(); 2307 if (size > 0) { 2308 String[] libs = new String[size]; 2309 libSet.toArray(libs); 2310 return libs; 2311 } 2312 } 2313 return null; 2314 } 2315 2316 @Override 2317 public FeatureInfo[] getSystemAvailableFeatures() { 2318 Collection<FeatureInfo> featSet; 2319 synchronized (mPackages) { 2320 featSet = mAvailableFeatures.values(); 2321 int size = featSet.size(); 2322 if (size > 0) { 2323 FeatureInfo[] features = new FeatureInfo[size+1]; 2324 featSet.toArray(features); 2325 FeatureInfo fi = new FeatureInfo(); 2326 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2327 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2328 features[size] = fi; 2329 return features; 2330 } 2331 } 2332 return null; 2333 } 2334 2335 @Override 2336 public boolean hasSystemFeature(String name) { 2337 synchronized (mPackages) { 2338 return mAvailableFeatures.containsKey(name); 2339 } 2340 } 2341 2342 private void checkValidCaller(int uid, int userId) { 2343 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2344 return; 2345 2346 throw new SecurityException("Caller uid=" + uid 2347 + " is not privileged to communicate with user=" + userId); 2348 } 2349 2350 @Override 2351 public int checkPermission(String permName, String pkgName) { 2352 synchronized (mPackages) { 2353 PackageParser.Package p = mPackages.get(pkgName); 2354 if (p != null && p.mExtras != null) { 2355 PackageSetting ps = (PackageSetting)p.mExtras; 2356 if (ps.sharedUser != null) { 2357 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2358 return PackageManager.PERMISSION_GRANTED; 2359 } 2360 } else if (ps.grantedPermissions.contains(permName)) { 2361 return PackageManager.PERMISSION_GRANTED; 2362 } 2363 } 2364 } 2365 return PackageManager.PERMISSION_DENIED; 2366 } 2367 2368 @Override 2369 public int checkUidPermission(String permName, int uid) { 2370 synchronized (mPackages) { 2371 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2372 if (obj != null) { 2373 GrantedPermissions gp = (GrantedPermissions)obj; 2374 if (gp.grantedPermissions.contains(permName)) { 2375 return PackageManager.PERMISSION_GRANTED; 2376 } 2377 } else { 2378 HashSet<String> perms = mSystemPermissions.get(uid); 2379 if (perms != null && perms.contains(permName)) { 2380 return PackageManager.PERMISSION_GRANTED; 2381 } 2382 } 2383 } 2384 return PackageManager.PERMISSION_DENIED; 2385 } 2386 2387 /** 2388 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2389 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2390 * @param message the message to log on security exception 2391 */ 2392 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2393 String message) { 2394 if (userId < 0) { 2395 throw new IllegalArgumentException("Invalid userId " + userId); 2396 } 2397 if (userId == UserHandle.getUserId(callingUid)) return; 2398 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2399 if (requireFullPermission) { 2400 mContext.enforceCallingOrSelfPermission( 2401 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2402 } else { 2403 try { 2404 mContext.enforceCallingOrSelfPermission( 2405 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2406 } catch (SecurityException se) { 2407 mContext.enforceCallingOrSelfPermission( 2408 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2409 } 2410 } 2411 } 2412 } 2413 2414 private BasePermission findPermissionTreeLP(String permName) { 2415 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2416 if (permName.startsWith(bp.name) && 2417 permName.length() > bp.name.length() && 2418 permName.charAt(bp.name.length()) == '.') { 2419 return bp; 2420 } 2421 } 2422 return null; 2423 } 2424 2425 private BasePermission checkPermissionTreeLP(String permName) { 2426 if (permName != null) { 2427 BasePermission bp = findPermissionTreeLP(permName); 2428 if (bp != null) { 2429 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2430 return bp; 2431 } 2432 throw new SecurityException("Calling uid " 2433 + Binder.getCallingUid() 2434 + " is not allowed to add to permission tree " 2435 + bp.name + " owned by uid " + bp.uid); 2436 } 2437 } 2438 throw new SecurityException("No permission tree found for " + permName); 2439 } 2440 2441 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2442 if (s1 == null) { 2443 return s2 == null; 2444 } 2445 if (s2 == null) { 2446 return false; 2447 } 2448 if (s1.getClass() != s2.getClass()) { 2449 return false; 2450 } 2451 return s1.equals(s2); 2452 } 2453 2454 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2455 if (pi1.icon != pi2.icon) return false; 2456 if (pi1.logo != pi2.logo) return false; 2457 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2458 if (!compareStrings(pi1.name, pi2.name)) return false; 2459 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2460 // We'll take care of setting this one. 2461 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2462 // These are not currently stored in settings. 2463 //if (!compareStrings(pi1.group, pi2.group)) return false; 2464 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2465 //if (pi1.labelRes != pi2.labelRes) return false; 2466 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2467 return true; 2468 } 2469 2470 int permissionInfoFootprint(PermissionInfo info) { 2471 int size = info.name.length(); 2472 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2473 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2474 return size; 2475 } 2476 2477 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2478 int size = 0; 2479 for (BasePermission perm : mSettings.mPermissions.values()) { 2480 if (perm.uid == tree.uid) { 2481 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2482 } 2483 } 2484 return size; 2485 } 2486 2487 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2488 // We calculate the max size of permissions defined by this uid and throw 2489 // if that plus the size of 'info' would exceed our stated maximum. 2490 if (tree.uid != Process.SYSTEM_UID) { 2491 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2492 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2493 throw new SecurityException("Permission tree size cap exceeded"); 2494 } 2495 } 2496 } 2497 2498 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2499 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2500 throw new SecurityException("Label must be specified in permission"); 2501 } 2502 BasePermission tree = checkPermissionTreeLP(info.name); 2503 BasePermission bp = mSettings.mPermissions.get(info.name); 2504 boolean added = bp == null; 2505 boolean changed = true; 2506 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2507 if (added) { 2508 enforcePermissionCapLocked(info, tree); 2509 bp = new BasePermission(info.name, tree.sourcePackage, 2510 BasePermission.TYPE_DYNAMIC); 2511 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2512 throw new SecurityException( 2513 "Not allowed to modify non-dynamic permission " 2514 + info.name); 2515 } else { 2516 if (bp.protectionLevel == fixedLevel 2517 && bp.perm.owner.equals(tree.perm.owner) 2518 && bp.uid == tree.uid 2519 && comparePermissionInfos(bp.perm.info, info)) { 2520 changed = false; 2521 } 2522 } 2523 bp.protectionLevel = fixedLevel; 2524 info = new PermissionInfo(info); 2525 info.protectionLevel = fixedLevel; 2526 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2527 bp.perm.info.packageName = tree.perm.info.packageName; 2528 bp.uid = tree.uid; 2529 if (added) { 2530 mSettings.mPermissions.put(info.name, bp); 2531 } 2532 if (changed) { 2533 if (!async) { 2534 mSettings.writeLPr(); 2535 } else { 2536 scheduleWriteSettingsLocked(); 2537 } 2538 } 2539 return added; 2540 } 2541 2542 @Override 2543 public boolean addPermission(PermissionInfo info) { 2544 synchronized (mPackages) { 2545 return addPermissionLocked(info, false); 2546 } 2547 } 2548 2549 @Override 2550 public boolean addPermissionAsync(PermissionInfo info) { 2551 synchronized (mPackages) { 2552 return addPermissionLocked(info, true); 2553 } 2554 } 2555 2556 @Override 2557 public void removePermission(String name) { 2558 synchronized (mPackages) { 2559 checkPermissionTreeLP(name); 2560 BasePermission bp = mSettings.mPermissions.get(name); 2561 if (bp != null) { 2562 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2563 throw new SecurityException( 2564 "Not allowed to modify non-dynamic permission " 2565 + name); 2566 } 2567 mSettings.mPermissions.remove(name); 2568 mSettings.writeLPr(); 2569 } 2570 } 2571 } 2572 2573 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2574 int index = pkg.requestedPermissions.indexOf(bp.name); 2575 if (index == -1) { 2576 throw new SecurityException("Package " + pkg.packageName 2577 + " has not requested permission " + bp.name); 2578 } 2579 boolean isNormal = 2580 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2581 == PermissionInfo.PROTECTION_NORMAL); 2582 boolean isDangerous = 2583 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2584 == PermissionInfo.PROTECTION_DANGEROUS); 2585 boolean isDevelopment = 2586 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2587 2588 if (!isNormal && !isDangerous && !isDevelopment) { 2589 throw new SecurityException("Permission " + bp.name 2590 + " is not a changeable permission type"); 2591 } 2592 2593 if (isNormal || isDangerous) { 2594 if (pkg.requestedPermissionsRequired.get(index)) { 2595 throw new SecurityException("Can't change " + bp.name 2596 + ". It is required by the application"); 2597 } 2598 } 2599 } 2600 2601 @Override 2602 public void grantPermission(String packageName, String permissionName) { 2603 mContext.enforceCallingOrSelfPermission( 2604 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2605 synchronized (mPackages) { 2606 final PackageParser.Package pkg = mPackages.get(packageName); 2607 if (pkg == null) { 2608 throw new IllegalArgumentException("Unknown package: " + packageName); 2609 } 2610 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2611 if (bp == null) { 2612 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2613 } 2614 2615 checkGrantRevokePermissions(pkg, bp); 2616 2617 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2618 if (ps == null) { 2619 return; 2620 } 2621 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2622 if (gp.grantedPermissions.add(permissionName)) { 2623 if (ps.haveGids) { 2624 gp.gids = appendInts(gp.gids, bp.gids); 2625 } 2626 mSettings.writeLPr(); 2627 } 2628 } 2629 } 2630 2631 @Override 2632 public void revokePermission(String packageName, String permissionName) { 2633 int changedAppId = -1; 2634 2635 synchronized (mPackages) { 2636 final PackageParser.Package pkg = mPackages.get(packageName); 2637 if (pkg == null) { 2638 throw new IllegalArgumentException("Unknown package: " + packageName); 2639 } 2640 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2641 mContext.enforceCallingOrSelfPermission( 2642 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2643 } 2644 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2645 if (bp == null) { 2646 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2647 } 2648 2649 checkGrantRevokePermissions(pkg, bp); 2650 2651 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2652 if (ps == null) { 2653 return; 2654 } 2655 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2656 if (gp.grantedPermissions.remove(permissionName)) { 2657 gp.grantedPermissions.remove(permissionName); 2658 if (ps.haveGids) { 2659 gp.gids = removeInts(gp.gids, bp.gids); 2660 } 2661 mSettings.writeLPr(); 2662 changedAppId = ps.appId; 2663 } 2664 } 2665 2666 if (changedAppId >= 0) { 2667 // We changed the perm on someone, kill its processes. 2668 IActivityManager am = ActivityManagerNative.getDefault(); 2669 if (am != null) { 2670 final int callingUserId = UserHandle.getCallingUserId(); 2671 final long ident = Binder.clearCallingIdentity(); 2672 try { 2673 //XXX we should only revoke for the calling user's app permissions, 2674 // but for now we impact all users. 2675 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2676 // "revoke " + permissionName); 2677 int[] users = sUserManager.getUserIds(); 2678 for (int user : users) { 2679 am.killUid(UserHandle.getUid(user, changedAppId), 2680 "revoke " + permissionName); 2681 } 2682 } catch (RemoteException e) { 2683 } finally { 2684 Binder.restoreCallingIdentity(ident); 2685 } 2686 } 2687 } 2688 } 2689 2690 @Override 2691 public boolean isProtectedBroadcast(String actionName) { 2692 synchronized (mPackages) { 2693 return mProtectedBroadcasts.contains(actionName); 2694 } 2695 } 2696 2697 @Override 2698 public int checkSignatures(String pkg1, String pkg2) { 2699 synchronized (mPackages) { 2700 final PackageParser.Package p1 = mPackages.get(pkg1); 2701 final PackageParser.Package p2 = mPackages.get(pkg2); 2702 if (p1 == null || p1.mExtras == null 2703 || p2 == null || p2.mExtras == null) { 2704 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2705 } 2706 return compareSignatures(p1.mSignatures, p2.mSignatures); 2707 } 2708 } 2709 2710 @Override 2711 public int checkUidSignatures(int uid1, int uid2) { 2712 // Map to base uids. 2713 uid1 = UserHandle.getAppId(uid1); 2714 uid2 = UserHandle.getAppId(uid2); 2715 // reader 2716 synchronized (mPackages) { 2717 Signature[] s1; 2718 Signature[] s2; 2719 Object obj = mSettings.getUserIdLPr(uid1); 2720 if (obj != null) { 2721 if (obj instanceof SharedUserSetting) { 2722 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2723 } else if (obj instanceof PackageSetting) { 2724 s1 = ((PackageSetting)obj).signatures.mSignatures; 2725 } else { 2726 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2727 } 2728 } else { 2729 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2730 } 2731 obj = mSettings.getUserIdLPr(uid2); 2732 if (obj != null) { 2733 if (obj instanceof SharedUserSetting) { 2734 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2735 } else if (obj instanceof PackageSetting) { 2736 s2 = ((PackageSetting)obj).signatures.mSignatures; 2737 } else { 2738 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2739 } 2740 } else { 2741 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2742 } 2743 return compareSignatures(s1, s2); 2744 } 2745 } 2746 2747 /** 2748 * Compares two sets of signatures. Returns: 2749 * <br /> 2750 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2751 * <br /> 2752 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2753 * <br /> 2754 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2755 * <br /> 2756 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2757 * <br /> 2758 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2759 */ 2760 static int compareSignatures(Signature[] s1, Signature[] s2) { 2761 if (s1 == null) { 2762 return s2 == null 2763 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2764 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2765 } 2766 2767 if (s2 == null) { 2768 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2769 } 2770 2771 if (s1.length != s2.length) { 2772 return PackageManager.SIGNATURE_NO_MATCH; 2773 } 2774 2775 // Since both signature sets are of size 1, we can compare without HashSets. 2776 if (s1.length == 1) { 2777 return s1[0].equals(s2[0]) ? 2778 PackageManager.SIGNATURE_MATCH : 2779 PackageManager.SIGNATURE_NO_MATCH; 2780 } 2781 2782 HashSet<Signature> set1 = new HashSet<Signature>(); 2783 for (Signature sig : s1) { 2784 set1.add(sig); 2785 } 2786 HashSet<Signature> set2 = new HashSet<Signature>(); 2787 for (Signature sig : s2) { 2788 set2.add(sig); 2789 } 2790 // Make sure s2 contains all signatures in s1. 2791 if (set1.equals(set2)) { 2792 return PackageManager.SIGNATURE_MATCH; 2793 } 2794 return PackageManager.SIGNATURE_NO_MATCH; 2795 } 2796 2797 /** 2798 * If the database version for this type of package (internal storage or 2799 * external storage) is less than the version where package signatures 2800 * were updated, return true. 2801 */ 2802 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2803 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2804 DatabaseVersion.SIGNATURE_END_ENTITY)) 2805 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2806 DatabaseVersion.SIGNATURE_END_ENTITY)); 2807 } 2808 2809 /** 2810 * Used for backward compatibility to make sure any packages with 2811 * certificate chains get upgraded to the new style. {@code existingSigs} 2812 * will be in the old format (since they were stored on disk from before the 2813 * system upgrade) and {@code scannedSigs} will be in the newer format. 2814 */ 2815 private int compareSignaturesCompat(PackageSignatures existingSigs, 2816 PackageParser.Package scannedPkg) { 2817 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2818 return PackageManager.SIGNATURE_NO_MATCH; 2819 } 2820 2821 HashSet<Signature> existingSet = new HashSet<Signature>(); 2822 for (Signature sig : existingSigs.mSignatures) { 2823 existingSet.add(sig); 2824 } 2825 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2826 for (Signature sig : scannedPkg.mSignatures) { 2827 try { 2828 Signature[] chainSignatures = sig.getChainSignatures(); 2829 for (Signature chainSig : chainSignatures) { 2830 scannedCompatSet.add(chainSig); 2831 } 2832 } catch (CertificateEncodingException e) { 2833 scannedCompatSet.add(sig); 2834 } 2835 } 2836 /* 2837 * Make sure the expanded scanned set contains all signatures in the 2838 * existing one. 2839 */ 2840 if (scannedCompatSet.equals(existingSet)) { 2841 // Migrate the old signatures to the new scheme. 2842 existingSigs.assignSignatures(scannedPkg.mSignatures); 2843 // The new KeySets will be re-added later in the scanning process. 2844 synchronized (mPackages) { 2845 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2846 } 2847 return PackageManager.SIGNATURE_MATCH; 2848 } 2849 return PackageManager.SIGNATURE_NO_MATCH; 2850 } 2851 2852 @Override 2853 public String[] getPackagesForUid(int uid) { 2854 uid = UserHandle.getAppId(uid); 2855 // reader 2856 synchronized (mPackages) { 2857 Object obj = mSettings.getUserIdLPr(uid); 2858 if (obj instanceof SharedUserSetting) { 2859 final SharedUserSetting sus = (SharedUserSetting) obj; 2860 final int N = sus.packages.size(); 2861 final String[] res = new String[N]; 2862 final Iterator<PackageSetting> it = sus.packages.iterator(); 2863 int i = 0; 2864 while (it.hasNext()) { 2865 res[i++] = it.next().name; 2866 } 2867 return res; 2868 } else if (obj instanceof PackageSetting) { 2869 final PackageSetting ps = (PackageSetting) obj; 2870 return new String[] { ps.name }; 2871 } 2872 } 2873 return null; 2874 } 2875 2876 @Override 2877 public String getNameForUid(int uid) { 2878 // reader 2879 synchronized (mPackages) { 2880 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2881 if (obj instanceof SharedUserSetting) { 2882 final SharedUserSetting sus = (SharedUserSetting) obj; 2883 return sus.name + ":" + sus.userId; 2884 } else if (obj instanceof PackageSetting) { 2885 final PackageSetting ps = (PackageSetting) obj; 2886 return ps.name; 2887 } 2888 } 2889 return null; 2890 } 2891 2892 @Override 2893 public int getUidForSharedUser(String sharedUserName) { 2894 if(sharedUserName == null) { 2895 return -1; 2896 } 2897 // reader 2898 synchronized (mPackages) { 2899 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2900 if (suid == null) { 2901 return -1; 2902 } 2903 return suid.userId; 2904 } 2905 } 2906 2907 @Override 2908 public int getFlagsForUid(int uid) { 2909 synchronized (mPackages) { 2910 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2911 if (obj instanceof SharedUserSetting) { 2912 final SharedUserSetting sus = (SharedUserSetting) obj; 2913 return sus.pkgFlags; 2914 } else if (obj instanceof PackageSetting) { 2915 final PackageSetting ps = (PackageSetting) obj; 2916 return ps.pkgFlags; 2917 } 2918 } 2919 return 0; 2920 } 2921 2922 @Override 2923 public String[] getAppOpPermissionPackages(String permissionName) { 2924 synchronized (mPackages) { 2925 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 2926 if (pkgs == null) { 2927 return null; 2928 } 2929 return pkgs.toArray(new String[pkgs.size()]); 2930 } 2931 } 2932 2933 @Override 2934 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2935 int flags, int userId) { 2936 if (!sUserManager.exists(userId)) return null; 2937 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2938 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2939 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2940 } 2941 2942 @Override 2943 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2944 IntentFilter filter, int match, ComponentName activity) { 2945 final int userId = UserHandle.getCallingUserId(); 2946 if (DEBUG_PREFERRED) { 2947 Log.v(TAG, "setLastChosenActivity intent=" + intent 2948 + " resolvedType=" + resolvedType 2949 + " flags=" + flags 2950 + " filter=" + filter 2951 + " match=" + match 2952 + " activity=" + activity); 2953 filter.dump(new PrintStreamPrinter(System.out), " "); 2954 } 2955 intent.setComponent(null); 2956 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2957 // Find any earlier preferred or last chosen entries and nuke them 2958 findPreferredActivity(intent, resolvedType, 2959 flags, query, 0, false, true, false, userId); 2960 // Add the new activity as the last chosen for this filter 2961 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2962 } 2963 2964 @Override 2965 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2966 final int userId = UserHandle.getCallingUserId(); 2967 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2968 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2969 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2970 false, false, false, userId); 2971 } 2972 2973 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2974 int flags, List<ResolveInfo> query, int userId) { 2975 if (query != null) { 2976 final int N = query.size(); 2977 if (N == 1) { 2978 return query.get(0); 2979 } else if (N > 1) { 2980 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2981 // If there is more than one activity with the same priority, 2982 // then let the user decide between them. 2983 ResolveInfo r0 = query.get(0); 2984 ResolveInfo r1 = query.get(1); 2985 if (DEBUG_INTENT_MATCHING || debug) { 2986 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2987 + r1.activityInfo.name + "=" + r1.priority); 2988 } 2989 // If the first activity has a higher priority, or a different 2990 // default, then it is always desireable to pick it. 2991 if (r0.priority != r1.priority 2992 || r0.preferredOrder != r1.preferredOrder 2993 || r0.isDefault != r1.isDefault) { 2994 return query.get(0); 2995 } 2996 // If we have saved a preference for a preferred activity for 2997 // this Intent, use that. 2998 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2999 flags, query, r0.priority, true, false, debug, userId); 3000 if (ri != null) { 3001 return ri; 3002 } 3003 if (userId != 0) { 3004 ri = new ResolveInfo(mResolveInfo); 3005 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3006 ri.activityInfo.applicationInfo = new ApplicationInfo( 3007 ri.activityInfo.applicationInfo); 3008 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3009 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3010 return ri; 3011 } 3012 return mResolveInfo; 3013 } 3014 } 3015 return null; 3016 } 3017 3018 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3019 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3020 final int N = query.size(); 3021 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3022 .get(userId); 3023 // Get the list of persistent preferred activities that handle the intent 3024 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3025 List<PersistentPreferredActivity> pprefs = ppir != null 3026 ? ppir.queryIntent(intent, resolvedType, 3027 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3028 : null; 3029 if (pprefs != null && pprefs.size() > 0) { 3030 final int M = pprefs.size(); 3031 for (int i=0; i<M; i++) { 3032 final PersistentPreferredActivity ppa = pprefs.get(i); 3033 if (DEBUG_PREFERRED || debug) { 3034 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3035 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3036 + "\n component=" + ppa.mComponent); 3037 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3038 } 3039 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3040 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3041 if (DEBUG_PREFERRED || debug) { 3042 Slog.v(TAG, "Found persistent preferred activity:"); 3043 if (ai != null) { 3044 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3045 } else { 3046 Slog.v(TAG, " null"); 3047 } 3048 } 3049 if (ai == null) { 3050 // This previously registered persistent preferred activity 3051 // component is no longer known. Ignore it and do NOT remove it. 3052 continue; 3053 } 3054 for (int j=0; j<N; j++) { 3055 final ResolveInfo ri = query.get(j); 3056 if (!ri.activityInfo.applicationInfo.packageName 3057 .equals(ai.applicationInfo.packageName)) { 3058 continue; 3059 } 3060 if (!ri.activityInfo.name.equals(ai.name)) { 3061 continue; 3062 } 3063 // Found a persistent preference that can handle the intent. 3064 if (DEBUG_PREFERRED || debug) { 3065 Slog.v(TAG, "Returning persistent preferred activity: " + 3066 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3067 } 3068 return ri; 3069 } 3070 } 3071 } 3072 return null; 3073 } 3074 3075 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3076 List<ResolveInfo> query, int priority, boolean always, 3077 boolean removeMatches, boolean debug, int userId) { 3078 if (!sUserManager.exists(userId)) return null; 3079 // writer 3080 synchronized (mPackages) { 3081 if (intent.getSelector() != null) { 3082 intent = intent.getSelector(); 3083 } 3084 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3085 3086 // Try to find a matching persistent preferred activity. 3087 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3088 debug, userId); 3089 3090 // If a persistent preferred activity matched, use it. 3091 if (pri != null) { 3092 return pri; 3093 } 3094 3095 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3096 // Get the list of preferred activities that handle the intent 3097 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3098 List<PreferredActivity> prefs = pir != null 3099 ? pir.queryIntent(intent, resolvedType, 3100 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3101 : null; 3102 if (prefs != null && prefs.size() > 0) { 3103 // First figure out how good the original match set is. 3104 // We will only allow preferred activities that came 3105 // from the same match quality. 3106 int match = 0; 3107 3108 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3109 3110 final int N = query.size(); 3111 for (int j=0; j<N; j++) { 3112 final ResolveInfo ri = query.get(j); 3113 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3114 + ": 0x" + Integer.toHexString(match)); 3115 if (ri.match > match) { 3116 match = ri.match; 3117 } 3118 } 3119 3120 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3121 + Integer.toHexString(match)); 3122 3123 match &= IntentFilter.MATCH_CATEGORY_MASK; 3124 final int M = prefs.size(); 3125 for (int i=0; i<M; i++) { 3126 final PreferredActivity pa = prefs.get(i); 3127 if (DEBUG_PREFERRED || debug) { 3128 Slog.v(TAG, "Checking PreferredActivity ds=" 3129 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3130 + "\n component=" + pa.mPref.mComponent); 3131 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3132 } 3133 if (pa.mPref.mMatch != match) { 3134 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3135 + Integer.toHexString(pa.mPref.mMatch)); 3136 continue; 3137 } 3138 // If it's not an "always" type preferred activity and that's what we're 3139 // looking for, skip it. 3140 if (always && !pa.mPref.mAlways) { 3141 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3142 continue; 3143 } 3144 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3145 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3146 if (DEBUG_PREFERRED || debug) { 3147 Slog.v(TAG, "Found preferred activity:"); 3148 if (ai != null) { 3149 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3150 } else { 3151 Slog.v(TAG, " null"); 3152 } 3153 } 3154 if (ai == null) { 3155 // This previously registered preferred activity 3156 // component is no longer known. Most likely an update 3157 // to the app was installed and in the new version this 3158 // component no longer exists. Clean it up by removing 3159 // it from the preferred activities list, and skip it. 3160 Slog.w(TAG, "Removing dangling preferred activity: " 3161 + pa.mPref.mComponent); 3162 pir.removeFilter(pa); 3163 continue; 3164 } 3165 for (int j=0; j<N; j++) { 3166 final ResolveInfo ri = query.get(j); 3167 if (!ri.activityInfo.applicationInfo.packageName 3168 .equals(ai.applicationInfo.packageName)) { 3169 continue; 3170 } 3171 if (!ri.activityInfo.name.equals(ai.name)) { 3172 continue; 3173 } 3174 3175 if (removeMatches) { 3176 pir.removeFilter(pa); 3177 if (DEBUG_PREFERRED) { 3178 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3179 } 3180 break; 3181 } 3182 3183 // Okay we found a previously set preferred or last chosen app. 3184 // If the result set is different from when this 3185 // was created, we need to clear it and re-ask the 3186 // user their preference, if we're looking for an "always" type entry. 3187 if (always && !pa.mPref.sameSet(query, priority)) { 3188 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3189 + intent + " type " + resolvedType); 3190 if (DEBUG_PREFERRED) { 3191 Slog.v(TAG, "Removing preferred activity since set changed " 3192 + pa.mPref.mComponent); 3193 } 3194 pir.removeFilter(pa); 3195 // Re-add the filter as a "last chosen" entry (!always) 3196 PreferredActivity lastChosen = new PreferredActivity( 3197 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3198 pir.addFilter(lastChosen); 3199 mSettings.writePackageRestrictionsLPr(userId); 3200 return null; 3201 } 3202 3203 // Yay! Either the set matched or we're looking for the last chosen 3204 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3205 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3206 mSettings.writePackageRestrictionsLPr(userId); 3207 return ri; 3208 } 3209 } 3210 } 3211 mSettings.writePackageRestrictionsLPr(userId); 3212 } 3213 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3214 return null; 3215 } 3216 3217 /* 3218 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3219 */ 3220 @Override 3221 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3222 int targetUserId) { 3223 mContext.enforceCallingOrSelfPermission( 3224 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3225 List<CrossProfileIntentFilter> matches = 3226 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3227 if (matches != null) { 3228 int size = matches.size(); 3229 for (int i = 0; i < size; i++) { 3230 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3231 } 3232 } 3233 3234 ArrayList<String> packageNames = null; 3235 SparseArray<ArrayList<String>> fromSource = 3236 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3237 if (fromSource != null) { 3238 packageNames = fromSource.get(targetUserId); 3239 } 3240 if (packageNames.contains(intent.getPackage())) { 3241 return true; 3242 } 3243 // We need the package name, so we try to resolve with the loosest flags possible 3244 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3245 intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3246 int count = resolveInfos.size(); 3247 for (int i = 0; i < count; i++) { 3248 ResolveInfo resolveInfo = resolveInfos.get(i); 3249 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3250 return true; 3251 } 3252 } 3253 return false; 3254 } 3255 3256 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3257 String resolvedType, int userId) { 3258 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3259 if (resolver != null) { 3260 return resolver.queryIntent(intent, resolvedType, false, userId); 3261 } 3262 return null; 3263 } 3264 3265 @Override 3266 public List<ResolveInfo> queryIntentActivities(Intent intent, 3267 String resolvedType, int flags, int userId) { 3268 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3269 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3270 ComponentName comp = intent.getComponent(); 3271 if (comp == null) { 3272 if (intent.getSelector() != null) { 3273 intent = intent.getSelector(); 3274 comp = intent.getComponent(); 3275 } 3276 } 3277 3278 if (comp != null) { 3279 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3280 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3281 if (ai != null) { 3282 final ResolveInfo ri = new ResolveInfo(); 3283 ri.activityInfo = ai; 3284 list.add(ri); 3285 } 3286 return list; 3287 } 3288 3289 // reader 3290 synchronized (mPackages) { 3291 final String pkgName = intent.getPackage(); 3292 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3293 if (pkgName == null) { 3294 ResolveInfo resolveInfo = null; 3295 if (queryCrossProfile) { 3296 // Check if the intent needs to be forwarded to another user for this package 3297 ArrayList<ResolveInfo> crossProfileResult = 3298 queryIntentActivitiesCrossProfilePackage( 3299 intent, resolvedType, flags, userId); 3300 if (!crossProfileResult.isEmpty()) { 3301 // Skip the current profile 3302 return crossProfileResult; 3303 } 3304 List<CrossProfileIntentFilter> matchingFilters = 3305 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3306 // Check for results that need to skip the current profile. 3307 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3308 resolvedType, flags, userId); 3309 if (resolveInfo != null) { 3310 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3311 result.add(resolveInfo); 3312 return result; 3313 } 3314 // Check for cross profile results. 3315 resolveInfo = queryCrossProfileIntents( 3316 matchingFilters, intent, resolvedType, flags, userId); 3317 } 3318 // Check for results in the current profile. 3319 List<ResolveInfo> result = mActivities.queryIntent( 3320 intent, resolvedType, flags, userId); 3321 if (resolveInfo != null) { 3322 result.add(resolveInfo); 3323 } 3324 return result; 3325 } 3326 final PackageParser.Package pkg = mPackages.get(pkgName); 3327 if (pkg != null) { 3328 if (queryCrossProfile) { 3329 ArrayList<ResolveInfo> crossProfileResult = 3330 queryIntentActivitiesCrossProfilePackage( 3331 intent, resolvedType, flags, userId, pkg, pkgName); 3332 if (!crossProfileResult.isEmpty()) { 3333 // Skip the current profile 3334 return crossProfileResult; 3335 } 3336 } 3337 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3338 pkg.activities, userId); 3339 } 3340 return new ArrayList<ResolveInfo>(); 3341 } 3342 } 3343 3344 private ResolveInfo querySkipCurrentProfileIntents( 3345 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3346 int flags, int sourceUserId) { 3347 if (matchingFilters != null) { 3348 int size = matchingFilters.size(); 3349 for (int i = 0; i < size; i ++) { 3350 CrossProfileIntentFilter filter = matchingFilters.get(i); 3351 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3352 // Checking if there are activities in the target user that can handle the 3353 // intent. 3354 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3355 flags, sourceUserId); 3356 if (resolveInfo != null) { 3357 return resolveInfo; 3358 } 3359 } 3360 } 3361 } 3362 return null; 3363 } 3364 3365 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3366 Intent intent, String resolvedType, int flags, int userId) { 3367 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3368 SparseArray<ArrayList<String>> sourceForwardingInfo = 3369 mSettings.mCrossProfilePackageInfo.get(userId); 3370 if (sourceForwardingInfo != null) { 3371 int NI = sourceForwardingInfo.size(); 3372 for (int i = 0; i < NI; i++) { 3373 int targetUserId = sourceForwardingInfo.keyAt(i); 3374 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3375 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3376 intent, resolvedType, flags, targetUserId); 3377 int NJ = resolveInfos.size(); 3378 for (int j = 0; j < NJ; j++) { 3379 ResolveInfo resolveInfo = resolveInfos.get(j); 3380 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3381 matchingResolveInfos.add(createForwardingResolveInfo( 3382 resolveInfo.filter, userId, targetUserId)); 3383 } 3384 } 3385 } 3386 } 3387 return matchingResolveInfos; 3388 } 3389 3390 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3391 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3392 String packageName) { 3393 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3394 SparseArray<ArrayList<String>> sourceForwardingInfo = 3395 mSettings.mCrossProfilePackageInfo.get(userId); 3396 if (sourceForwardingInfo != null) { 3397 int NI = sourceForwardingInfo.size(); 3398 for (int i = 0; i < NI; i++) { 3399 int targetUserId = sourceForwardingInfo.keyAt(i); 3400 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3401 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3402 intent, resolvedType, flags, pkg.activities, targetUserId); 3403 int NJ = resolveInfos.size(); 3404 for (int j = 0; j < NJ; j++) { 3405 ResolveInfo resolveInfo = resolveInfos.get(j); 3406 matchingResolveInfos.add(createForwardingResolveInfo( 3407 resolveInfo.filter, userId, targetUserId)); 3408 } 3409 } 3410 } 3411 } 3412 return matchingResolveInfos; 3413 } 3414 3415 // Return matching ResolveInfo if any for skip current profile intent filters. 3416 private ResolveInfo queryCrossProfileIntents( 3417 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3418 int flags, int sourceUserId) { 3419 if (matchingFilters != null) { 3420 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3421 // match the same intent. For performance reasons, it is better not to 3422 // run queryIntent twice for the same userId 3423 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3424 int size = matchingFilters.size(); 3425 for (int i = 0; i < size; i++) { 3426 CrossProfileIntentFilter filter = matchingFilters.get(i); 3427 int targetUserId = filter.getTargetUserId(); 3428 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3429 && !alreadyTriedUserIds.get(targetUserId)) { 3430 // Checking if there are activities in the target user that can handle the 3431 // intent. 3432 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3433 flags, sourceUserId); 3434 if (resolveInfo != null) return resolveInfo; 3435 alreadyTriedUserIds.put(targetUserId, true); 3436 } 3437 } 3438 } 3439 return null; 3440 } 3441 3442 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3443 String resolvedType, int flags, int sourceUserId) { 3444 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3445 resolvedType, flags, filter.getTargetUserId()); 3446 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3447 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3448 } 3449 return null; 3450 } 3451 3452 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3453 int sourceUserId, int targetUserId) { 3454 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3455 String className; 3456 if (targetUserId == UserHandle.USER_OWNER) { 3457 className = FORWARD_INTENT_TO_USER_OWNER; 3458 } else { 3459 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3460 } 3461 ComponentName forwardingActivityComponentName = new ComponentName( 3462 mAndroidApplication.packageName, className); 3463 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3464 sourceUserId); 3465 if (targetUserId == UserHandle.USER_OWNER) { 3466 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3467 forwardingResolveInfo.noResourceId = true; 3468 } 3469 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3470 forwardingResolveInfo.priority = 0; 3471 forwardingResolveInfo.preferredOrder = 0; 3472 forwardingResolveInfo.match = 0; 3473 forwardingResolveInfo.isDefault = true; 3474 forwardingResolveInfo.filter = filter; 3475 forwardingResolveInfo.targetUserId = targetUserId; 3476 return forwardingResolveInfo; 3477 } 3478 3479 @Override 3480 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3481 Intent[] specifics, String[] specificTypes, Intent intent, 3482 String resolvedType, int flags, int userId) { 3483 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3484 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3485 "query intent activity options"); 3486 final String resultsAction = intent.getAction(); 3487 3488 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3489 | PackageManager.GET_RESOLVED_FILTER, userId); 3490 3491 if (DEBUG_INTENT_MATCHING) { 3492 Log.v(TAG, "Query " + intent + ": " + results); 3493 } 3494 3495 int specificsPos = 0; 3496 int N; 3497 3498 // todo: note that the algorithm used here is O(N^2). This 3499 // isn't a problem in our current environment, but if we start running 3500 // into situations where we have more than 5 or 10 matches then this 3501 // should probably be changed to something smarter... 3502 3503 // First we go through and resolve each of the specific items 3504 // that were supplied, taking care of removing any corresponding 3505 // duplicate items in the generic resolve list. 3506 if (specifics != null) { 3507 for (int i=0; i<specifics.length; i++) { 3508 final Intent sintent = specifics[i]; 3509 if (sintent == null) { 3510 continue; 3511 } 3512 3513 if (DEBUG_INTENT_MATCHING) { 3514 Log.v(TAG, "Specific #" + i + ": " + sintent); 3515 } 3516 3517 String action = sintent.getAction(); 3518 if (resultsAction != null && resultsAction.equals(action)) { 3519 // If this action was explicitly requested, then don't 3520 // remove things that have it. 3521 action = null; 3522 } 3523 3524 ResolveInfo ri = null; 3525 ActivityInfo ai = null; 3526 3527 ComponentName comp = sintent.getComponent(); 3528 if (comp == null) { 3529 ri = resolveIntent( 3530 sintent, 3531 specificTypes != null ? specificTypes[i] : null, 3532 flags, userId); 3533 if (ri == null) { 3534 continue; 3535 } 3536 if (ri == mResolveInfo) { 3537 // ACK! Must do something better with this. 3538 } 3539 ai = ri.activityInfo; 3540 comp = new ComponentName(ai.applicationInfo.packageName, 3541 ai.name); 3542 } else { 3543 ai = getActivityInfo(comp, flags, userId); 3544 if (ai == null) { 3545 continue; 3546 } 3547 } 3548 3549 // Look for any generic query activities that are duplicates 3550 // of this specific one, and remove them from the results. 3551 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3552 N = results.size(); 3553 int j; 3554 for (j=specificsPos; j<N; j++) { 3555 ResolveInfo sri = results.get(j); 3556 if ((sri.activityInfo.name.equals(comp.getClassName()) 3557 && sri.activityInfo.applicationInfo.packageName.equals( 3558 comp.getPackageName())) 3559 || (action != null && sri.filter.matchAction(action))) { 3560 results.remove(j); 3561 if (DEBUG_INTENT_MATCHING) Log.v( 3562 TAG, "Removing duplicate item from " + j 3563 + " due to specific " + specificsPos); 3564 if (ri == null) { 3565 ri = sri; 3566 } 3567 j--; 3568 N--; 3569 } 3570 } 3571 3572 // Add this specific item to its proper place. 3573 if (ri == null) { 3574 ri = new ResolveInfo(); 3575 ri.activityInfo = ai; 3576 } 3577 results.add(specificsPos, ri); 3578 ri.specificIndex = i; 3579 specificsPos++; 3580 } 3581 } 3582 3583 // Now we go through the remaining generic results and remove any 3584 // duplicate actions that are found here. 3585 N = results.size(); 3586 for (int i=specificsPos; i<N-1; i++) { 3587 final ResolveInfo rii = results.get(i); 3588 if (rii.filter == null) { 3589 continue; 3590 } 3591 3592 // Iterate over all of the actions of this result's intent 3593 // filter... typically this should be just one. 3594 final Iterator<String> it = rii.filter.actionsIterator(); 3595 if (it == null) { 3596 continue; 3597 } 3598 while (it.hasNext()) { 3599 final String action = it.next(); 3600 if (resultsAction != null && resultsAction.equals(action)) { 3601 // If this action was explicitly requested, then don't 3602 // remove things that have it. 3603 continue; 3604 } 3605 for (int j=i+1; j<N; j++) { 3606 final ResolveInfo rij = results.get(j); 3607 if (rij.filter != null && rij.filter.hasAction(action)) { 3608 results.remove(j); 3609 if (DEBUG_INTENT_MATCHING) Log.v( 3610 TAG, "Removing duplicate item from " + j 3611 + " due to action " + action + " at " + i); 3612 j--; 3613 N--; 3614 } 3615 } 3616 } 3617 3618 // If the caller didn't request filter information, drop it now 3619 // so we don't have to marshall/unmarshall it. 3620 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3621 rii.filter = null; 3622 } 3623 } 3624 3625 // Filter out the caller activity if so requested. 3626 if (caller != null) { 3627 N = results.size(); 3628 for (int i=0; i<N; i++) { 3629 ActivityInfo ainfo = results.get(i).activityInfo; 3630 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3631 && caller.getClassName().equals(ainfo.name)) { 3632 results.remove(i); 3633 break; 3634 } 3635 } 3636 } 3637 3638 // If the caller didn't request filter information, 3639 // drop them now so we don't have to 3640 // marshall/unmarshall it. 3641 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3642 N = results.size(); 3643 for (int i=0; i<N; i++) { 3644 results.get(i).filter = null; 3645 } 3646 } 3647 3648 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3649 return results; 3650 } 3651 3652 @Override 3653 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3654 int userId) { 3655 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3656 ComponentName comp = intent.getComponent(); 3657 if (comp == null) { 3658 if (intent.getSelector() != null) { 3659 intent = intent.getSelector(); 3660 comp = intent.getComponent(); 3661 } 3662 } 3663 if (comp != null) { 3664 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3665 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3666 if (ai != null) { 3667 ResolveInfo ri = new ResolveInfo(); 3668 ri.activityInfo = ai; 3669 list.add(ri); 3670 } 3671 return list; 3672 } 3673 3674 // reader 3675 synchronized (mPackages) { 3676 String pkgName = intent.getPackage(); 3677 if (pkgName == null) { 3678 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3679 } 3680 final PackageParser.Package pkg = mPackages.get(pkgName); 3681 if (pkg != null) { 3682 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3683 userId); 3684 } 3685 return null; 3686 } 3687 } 3688 3689 @Override 3690 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3691 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3692 if (!sUserManager.exists(userId)) return null; 3693 if (query != null) { 3694 if (query.size() >= 1) { 3695 // If there is more than one service with the same priority, 3696 // just arbitrarily pick the first one. 3697 return query.get(0); 3698 } 3699 } 3700 return null; 3701 } 3702 3703 @Override 3704 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3705 int userId) { 3706 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3707 ComponentName comp = intent.getComponent(); 3708 if (comp == null) { 3709 if (intent.getSelector() != null) { 3710 intent = intent.getSelector(); 3711 comp = intent.getComponent(); 3712 } 3713 } 3714 if (comp != null) { 3715 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3716 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3717 if (si != null) { 3718 final ResolveInfo ri = new ResolveInfo(); 3719 ri.serviceInfo = si; 3720 list.add(ri); 3721 } 3722 return list; 3723 } 3724 3725 // reader 3726 synchronized (mPackages) { 3727 String pkgName = intent.getPackage(); 3728 if (pkgName == null) { 3729 return mServices.queryIntent(intent, resolvedType, flags, userId); 3730 } 3731 final PackageParser.Package pkg = mPackages.get(pkgName); 3732 if (pkg != null) { 3733 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3734 userId); 3735 } 3736 return null; 3737 } 3738 } 3739 3740 @Override 3741 public List<ResolveInfo> queryIntentContentProviders( 3742 Intent intent, String resolvedType, int flags, int userId) { 3743 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3744 ComponentName comp = intent.getComponent(); 3745 if (comp == null) { 3746 if (intent.getSelector() != null) { 3747 intent = intent.getSelector(); 3748 comp = intent.getComponent(); 3749 } 3750 } 3751 if (comp != null) { 3752 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3753 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3754 if (pi != null) { 3755 final ResolveInfo ri = new ResolveInfo(); 3756 ri.providerInfo = pi; 3757 list.add(ri); 3758 } 3759 return list; 3760 } 3761 3762 // reader 3763 synchronized (mPackages) { 3764 String pkgName = intent.getPackage(); 3765 if (pkgName == null) { 3766 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3767 } 3768 final PackageParser.Package pkg = mPackages.get(pkgName); 3769 if (pkg != null) { 3770 return mProviders.queryIntentForPackage( 3771 intent, resolvedType, flags, pkg.providers, userId); 3772 } 3773 return null; 3774 } 3775 } 3776 3777 @Override 3778 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3779 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3780 3781 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3782 3783 // writer 3784 synchronized (mPackages) { 3785 ArrayList<PackageInfo> list; 3786 if (listUninstalled) { 3787 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3788 for (PackageSetting ps : mSettings.mPackages.values()) { 3789 PackageInfo pi; 3790 if (ps.pkg != null) { 3791 pi = generatePackageInfo(ps.pkg, flags, userId); 3792 } else { 3793 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3794 } 3795 if (pi != null) { 3796 list.add(pi); 3797 } 3798 } 3799 } else { 3800 list = new ArrayList<PackageInfo>(mPackages.size()); 3801 for (PackageParser.Package p : mPackages.values()) { 3802 PackageInfo pi = generatePackageInfo(p, flags, userId); 3803 if (pi != null) { 3804 list.add(pi); 3805 } 3806 } 3807 } 3808 3809 return new ParceledListSlice<PackageInfo>(list); 3810 } 3811 } 3812 3813 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3814 String[] permissions, boolean[] tmp, int flags, int userId) { 3815 int numMatch = 0; 3816 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3817 for (int i=0; i<permissions.length; i++) { 3818 if (gp.grantedPermissions.contains(permissions[i])) { 3819 tmp[i] = true; 3820 numMatch++; 3821 } else { 3822 tmp[i] = false; 3823 } 3824 } 3825 if (numMatch == 0) { 3826 return; 3827 } 3828 PackageInfo pi; 3829 if (ps.pkg != null) { 3830 pi = generatePackageInfo(ps.pkg, flags, userId); 3831 } else { 3832 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3833 } 3834 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3835 if (numMatch == permissions.length) { 3836 pi.requestedPermissions = permissions; 3837 } else { 3838 pi.requestedPermissions = new String[numMatch]; 3839 numMatch = 0; 3840 for (int i=0; i<permissions.length; i++) { 3841 if (tmp[i]) { 3842 pi.requestedPermissions[numMatch] = permissions[i]; 3843 numMatch++; 3844 } 3845 } 3846 } 3847 } 3848 list.add(pi); 3849 } 3850 3851 @Override 3852 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3853 String[] permissions, int flags, int userId) { 3854 if (!sUserManager.exists(userId)) return null; 3855 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3856 3857 // writer 3858 synchronized (mPackages) { 3859 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3860 boolean[] tmpBools = new boolean[permissions.length]; 3861 if (listUninstalled) { 3862 for (PackageSetting ps : mSettings.mPackages.values()) { 3863 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3864 } 3865 } else { 3866 for (PackageParser.Package pkg : mPackages.values()) { 3867 PackageSetting ps = (PackageSetting)pkg.mExtras; 3868 if (ps != null) { 3869 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3870 userId); 3871 } 3872 } 3873 } 3874 3875 return new ParceledListSlice<PackageInfo>(list); 3876 } 3877 } 3878 3879 @Override 3880 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3881 if (!sUserManager.exists(userId)) return null; 3882 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3883 3884 // writer 3885 synchronized (mPackages) { 3886 ArrayList<ApplicationInfo> list; 3887 if (listUninstalled) { 3888 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3889 for (PackageSetting ps : mSettings.mPackages.values()) { 3890 ApplicationInfo ai; 3891 if (ps.pkg != null) { 3892 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3893 ps.readUserState(userId), userId); 3894 } else { 3895 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3896 } 3897 if (ai != null) { 3898 list.add(ai); 3899 } 3900 } 3901 } else { 3902 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3903 for (PackageParser.Package p : mPackages.values()) { 3904 if (p.mExtras != null) { 3905 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3906 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3907 if (ai != null) { 3908 list.add(ai); 3909 } 3910 } 3911 } 3912 } 3913 3914 return new ParceledListSlice<ApplicationInfo>(list); 3915 } 3916 } 3917 3918 public List<ApplicationInfo> getPersistentApplications(int flags) { 3919 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3920 3921 // reader 3922 synchronized (mPackages) { 3923 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3924 final int userId = UserHandle.getCallingUserId(); 3925 while (i.hasNext()) { 3926 final PackageParser.Package p = i.next(); 3927 if (p.applicationInfo != null 3928 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3929 && (!mSafeMode || isSystemApp(p))) { 3930 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3931 if (ps != null) { 3932 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3933 ps.readUserState(userId), userId); 3934 if (ai != null) { 3935 finalList.add(ai); 3936 } 3937 } 3938 } 3939 } 3940 } 3941 3942 return finalList; 3943 } 3944 3945 @Override 3946 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3947 if (!sUserManager.exists(userId)) return null; 3948 // reader 3949 synchronized (mPackages) { 3950 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3951 PackageSetting ps = provider != null 3952 ? mSettings.mPackages.get(provider.owner.packageName) 3953 : null; 3954 return ps != null 3955 && mSettings.isEnabledLPr(provider.info, flags, userId) 3956 && (!mSafeMode || (provider.info.applicationInfo.flags 3957 &ApplicationInfo.FLAG_SYSTEM) != 0) 3958 ? PackageParser.generateProviderInfo(provider, flags, 3959 ps.readUserState(userId), userId) 3960 : null; 3961 } 3962 } 3963 3964 /** 3965 * @deprecated 3966 */ 3967 @Deprecated 3968 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3969 // reader 3970 synchronized (mPackages) { 3971 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3972 .entrySet().iterator(); 3973 final int userId = UserHandle.getCallingUserId(); 3974 while (i.hasNext()) { 3975 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3976 PackageParser.Provider p = entry.getValue(); 3977 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3978 3979 if (ps != null && p.syncable 3980 && (!mSafeMode || (p.info.applicationInfo.flags 3981 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3982 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3983 ps.readUserState(userId), userId); 3984 if (info != null) { 3985 outNames.add(entry.getKey()); 3986 outInfo.add(info); 3987 } 3988 } 3989 } 3990 } 3991 } 3992 3993 @Override 3994 public List<ProviderInfo> queryContentProviders(String processName, 3995 int uid, int flags) { 3996 ArrayList<ProviderInfo> finalList = null; 3997 // reader 3998 synchronized (mPackages) { 3999 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4000 final int userId = processName != null ? 4001 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4002 while (i.hasNext()) { 4003 final PackageParser.Provider p = i.next(); 4004 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4005 if (ps != null && p.info.authority != null 4006 && (processName == null 4007 || (p.info.processName.equals(processName) 4008 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4009 && mSettings.isEnabledLPr(p.info, flags, userId) 4010 && (!mSafeMode 4011 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4012 if (finalList == null) { 4013 finalList = new ArrayList<ProviderInfo>(3); 4014 } 4015 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4016 ps.readUserState(userId), userId); 4017 if (info != null) { 4018 finalList.add(info); 4019 } 4020 } 4021 } 4022 } 4023 4024 if (finalList != null) { 4025 Collections.sort(finalList, mProviderInitOrderSorter); 4026 } 4027 4028 return finalList; 4029 } 4030 4031 @Override 4032 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4033 int flags) { 4034 // reader 4035 synchronized (mPackages) { 4036 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4037 return PackageParser.generateInstrumentationInfo(i, flags); 4038 } 4039 } 4040 4041 @Override 4042 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4043 int flags) { 4044 ArrayList<InstrumentationInfo> finalList = 4045 new ArrayList<InstrumentationInfo>(); 4046 4047 // reader 4048 synchronized (mPackages) { 4049 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4050 while (i.hasNext()) { 4051 final PackageParser.Instrumentation p = i.next(); 4052 if (targetPackage == null 4053 || targetPackage.equals(p.info.targetPackage)) { 4054 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4055 flags); 4056 if (ii != null) { 4057 finalList.add(ii); 4058 } 4059 } 4060 } 4061 } 4062 4063 return finalList; 4064 } 4065 4066 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4067 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4068 if (overlays == null) { 4069 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4070 return; 4071 } 4072 for (PackageParser.Package opkg : overlays.values()) { 4073 // Not much to do if idmap fails: we already logged the error 4074 // and we certainly don't want to abort installation of pkg simply 4075 // because an overlay didn't fit properly. For these reasons, 4076 // ignore the return value of createIdmapForPackagePairLI. 4077 createIdmapForPackagePairLI(pkg, opkg); 4078 } 4079 } 4080 4081 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4082 PackageParser.Package opkg) { 4083 if (!opkg.mTrustedOverlay) { 4084 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4085 opkg.baseCodePath + ": overlay not trusted"); 4086 return false; 4087 } 4088 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4089 if (overlaySet == null) { 4090 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4091 opkg.baseCodePath + " but target package has no known overlays"); 4092 return false; 4093 } 4094 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4095 // TODO: generate idmap for split APKs 4096 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4097 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4098 + opkg.baseCodePath); 4099 return false; 4100 } 4101 PackageParser.Package[] overlayArray = 4102 overlaySet.values().toArray(new PackageParser.Package[0]); 4103 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4104 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4105 return p1.mOverlayPriority - p2.mOverlayPriority; 4106 } 4107 }; 4108 Arrays.sort(overlayArray, cmp); 4109 4110 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4111 int i = 0; 4112 for (PackageParser.Package p : overlayArray) { 4113 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4114 } 4115 return true; 4116 } 4117 4118 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4119 final File[] files = dir.listFiles(); 4120 if (ArrayUtils.isEmpty(files)) { 4121 Log.d(TAG, "No files in app dir " + dir); 4122 return; 4123 } 4124 4125 if (DEBUG_PACKAGE_SCANNING) { 4126 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4127 + " flags=0x" + Integer.toHexString(flags)); 4128 } 4129 4130 for (File file : files) { 4131 final boolean isPackage = isApkFile(file) || file.isDirectory(); 4132 if (!isPackage) { 4133 // Ignore entries which are not apk's 4134 continue; 4135 } 4136 try { 4137 scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, 4138 null, null); 4139 } catch (PackageManagerException e) { 4140 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4141 4142 // Don't mess around with apps in system partition. 4143 if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4144 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4145 // Delete the apk 4146 Slog.w(TAG, "Cleaning up failed install of " + file); 4147 file.delete(); 4148 } 4149 } 4150 } 4151 } 4152 4153 private static File getSettingsProblemFile() { 4154 File dataDir = Environment.getDataDirectory(); 4155 File systemDir = new File(dataDir, "system"); 4156 File fname = new File(systemDir, "uiderrors.txt"); 4157 return fname; 4158 } 4159 4160 static void reportSettingsProblem(int priority, String msg) { 4161 try { 4162 File fname = getSettingsProblemFile(); 4163 FileOutputStream out = new FileOutputStream(fname, true); 4164 PrintWriter pw = new FastPrintWriter(out); 4165 SimpleDateFormat formatter = new SimpleDateFormat(); 4166 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4167 pw.println(dateString + ": " + msg); 4168 pw.close(); 4169 FileUtils.setPermissions( 4170 fname.toString(), 4171 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4172 -1, -1); 4173 } catch (java.io.IOException e) { 4174 } 4175 Slog.println(priority, TAG, msg); 4176 } 4177 4178 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4179 PackageParser.Package pkg, File srcFile, int parseFlags) 4180 throws PackageManagerException { 4181 if (ps != null 4182 && ps.codePath.equals(srcFile) 4183 && ps.timeStamp == srcFile.lastModified() 4184 && !isCompatSignatureUpdateNeeded(pkg)) { 4185 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4186 if (ps.signatures.mSignatures != null 4187 && ps.signatures.mSignatures.length != 0 4188 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4189 // Optimization: reuse the existing cached certificates 4190 // if the package appears to be unchanged. 4191 pkg.mSignatures = ps.signatures.mSignatures; 4192 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4193 synchronized (mPackages) { 4194 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4195 } 4196 return; 4197 } 4198 4199 Slog.w(TAG, "PackageSetting for " + ps.name 4200 + " is missing signatures. Collecting certs again to recover them."); 4201 } else { 4202 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4203 } 4204 4205 try { 4206 pp.collectCertificates(pkg, parseFlags); 4207 pp.collectManifestDigest(pkg); 4208 } catch (PackageParserException e) { 4209 throw new PackageManagerException(e.error, "Failed to collect certificates for " 4210 + pkg.packageName + ": " + e.getMessage()); 4211 } 4212 } 4213 4214 /* 4215 * Scan a package and return the newly parsed package. 4216 * Returns null in case of errors and the error code is stored in mLastScanError 4217 */ 4218 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode, 4219 long currentTime, UserHandle user, String abiOverride) throws PackageManagerException { 4220 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4221 parseFlags |= mDefParseFlags; 4222 PackageParser pp = new PackageParser(); 4223 pp.setSeparateProcesses(mSeparateProcesses); 4224 pp.setOnlyCoreApps(mOnlyCore); 4225 pp.setDisplayMetrics(mMetrics); 4226 4227 if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) { 4228 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4229 } 4230 4231 final PackageParser.Package pkg; 4232 try { 4233 pkg = pp.parsePackage(scanFile, parseFlags); 4234 } catch (PackageParserException e) { 4235 throw new PackageManagerException(e.error, 4236 "Failed to scan " + scanFile + ": " + e.getMessage()); 4237 } 4238 4239 PackageSetting ps = null; 4240 PackageSetting updatedPkg; 4241 // reader 4242 synchronized (mPackages) { 4243 // Look to see if we already know about this package. 4244 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4245 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4246 // This package has been renamed to its original name. Let's 4247 // use that. 4248 ps = mSettings.peekPackageLPr(oldName); 4249 } 4250 // If there was no original package, see one for the real package name. 4251 if (ps == null) { 4252 ps = mSettings.peekPackageLPr(pkg.packageName); 4253 } 4254 // Check to see if this package could be hiding/updating a system 4255 // package. Must look for it either under the original or real 4256 // package name depending on our state. 4257 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4258 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4259 } 4260 boolean updatedPkgBetter = false; 4261 // First check if this is a system package that may involve an update 4262 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4263 if (ps != null && !ps.codePath.equals(scanFile)) { 4264 // The path has changed from what was last scanned... check the 4265 // version of the new path against what we have stored to determine 4266 // what to do. 4267 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4268 if (pkg.mVersionCode < ps.versionCode) { 4269 // The system package has been updated and the code path does not match 4270 // Ignore entry. Skip it. 4271 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4272 + " ignored: updated version " + ps.versionCode 4273 + " better than this " + pkg.mVersionCode); 4274 if (!updatedPkg.codePath.equals(scanFile)) { 4275 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4276 + ps.name + " changing from " + updatedPkg.codePathString 4277 + " to " + scanFile); 4278 updatedPkg.codePath = scanFile; 4279 updatedPkg.codePathString = scanFile.toString(); 4280 // This is the point at which we know that the system-disk APK 4281 // for this package has moved during a reboot (e.g. due to an OTA), 4282 // so we need to reevaluate it for privilege policy. 4283 if (locationIsPrivileged(scanFile)) { 4284 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4285 } 4286 } 4287 updatedPkg.pkg = pkg; 4288 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4289 } else { 4290 // The current app on the system partition is better than 4291 // what we have updated to on the data partition; switch 4292 // back to the system partition version. 4293 // At this point, its safely assumed that package installation for 4294 // apps in system partition will go through. If not there won't be a working 4295 // version of the app 4296 // writer 4297 synchronized (mPackages) { 4298 // Just remove the loaded entries from package lists. 4299 mPackages.remove(ps.name); 4300 } 4301 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4302 + "reverting from " + ps.codePathString 4303 + ": new version " + pkg.mVersionCode 4304 + " better than installed " + ps.versionCode); 4305 4306 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4307 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4308 getAppDexInstructionSets(ps), isMultiArch(ps)); 4309 synchronized (mInstallLock) { 4310 args.cleanUpResourcesLI(); 4311 } 4312 synchronized (mPackages) { 4313 mSettings.enableSystemPackageLPw(ps.name); 4314 } 4315 updatedPkgBetter = true; 4316 } 4317 } 4318 } 4319 4320 if (updatedPkg != null) { 4321 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4322 // initially 4323 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4324 4325 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4326 // flag set initially 4327 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4328 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4329 } 4330 } 4331 4332 // Verify certificates against what was last scanned 4333 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4334 4335 /* 4336 * A new system app appeared, but we already had a non-system one of the 4337 * same name installed earlier. 4338 */ 4339 boolean shouldHideSystemApp = false; 4340 if (updatedPkg == null && ps != null 4341 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4342 /* 4343 * Check to make sure the signatures match first. If they don't, 4344 * wipe the installed application and its data. 4345 */ 4346 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4347 != PackageManager.SIGNATURE_MATCH) { 4348 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4349 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4350 ps = null; 4351 } else { 4352 /* 4353 * If the newly-added system app is an older version than the 4354 * already installed version, hide it. It will be scanned later 4355 * and re-added like an update. 4356 */ 4357 if (pkg.mVersionCode < ps.versionCode) { 4358 shouldHideSystemApp = true; 4359 } else { 4360 /* 4361 * The newly found system app is a newer version that the 4362 * one previously installed. Simply remove the 4363 * already-installed application and replace it with our own 4364 * while keeping the application data. 4365 */ 4366 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4367 + ps.codePathString + ": new version " + pkg.mVersionCode 4368 + " better than installed " + ps.versionCode); 4369 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4370 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4371 getAppDexInstructionSets(ps), isMultiArch(ps)); 4372 synchronized (mInstallLock) { 4373 args.cleanUpResourcesLI(); 4374 } 4375 } 4376 } 4377 } 4378 4379 // The apk is forward locked (not public) if its code and resources 4380 // are kept in different files. (except for app in either system or 4381 // vendor path). 4382 // TODO grab this value from PackageSettings 4383 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4384 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4385 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4386 } 4387 } 4388 4389 // TODO: extend to support forward-locked splits 4390 String resourcePath = null; 4391 String baseResourcePath = null; 4392 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4393 if (ps != null && ps.resourcePathString != null) { 4394 resourcePath = ps.resourcePathString; 4395 baseResourcePath = ps.resourcePathString; 4396 } else { 4397 // Should not happen at all. Just log an error. 4398 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4399 } 4400 } else { 4401 resourcePath = pkg.codePath; 4402 baseResourcePath = pkg.baseCodePath; 4403 } 4404 4405 // Set application objects path explicitly. 4406 pkg.applicationInfo.setCodePath(pkg.codePath); 4407 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4408 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4409 pkg.applicationInfo.setResourcePath(resourcePath); 4410 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4411 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4412 4413 // Note that we invoke the following method only if we are about to unpack an application 4414 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4415 | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride); 4416 4417 /* 4418 * If the system app should be overridden by a previously installed 4419 * data, hide the system app now and let the /data/app scan pick it up 4420 * again. 4421 */ 4422 if (shouldHideSystemApp) { 4423 synchronized (mPackages) { 4424 /* 4425 * We have to grant systems permissions before we hide, because 4426 * grantPermissions will assume the package update is trying to 4427 * expand its permissions. 4428 */ 4429 grantPermissionsLPw(pkg, true); 4430 mSettings.disableSystemPackageLPw(pkg.packageName); 4431 } 4432 } 4433 4434 return scannedPkg; 4435 } 4436 4437 private static String fixProcessName(String defProcessName, 4438 String processName, int uid) { 4439 if (processName == null) { 4440 return defProcessName; 4441 } 4442 return processName; 4443 } 4444 4445 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4446 throws PackageManagerException { 4447 if (pkgSetting.signatures.mSignatures != null) { 4448 // Already existing package. Make sure signatures match 4449 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4450 == PackageManager.SIGNATURE_MATCH; 4451 if (!match) { 4452 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4453 == PackageManager.SIGNATURE_MATCH; 4454 } 4455 if (!match) { 4456 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4457 + pkg.packageName + " signatures do not match the " 4458 + "previously installed version; ignoring!"); 4459 } 4460 } 4461 4462 // Check for shared user signatures 4463 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4464 // Already existing package. Make sure signatures match 4465 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4466 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4467 if (!match) { 4468 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4469 == PackageManager.SIGNATURE_MATCH; 4470 } 4471 if (!match) { 4472 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4473 "Package " + pkg.packageName 4474 + " has no signatures that match those in shared user " 4475 + pkgSetting.sharedUser.name + "; ignoring!"); 4476 } 4477 } 4478 } 4479 4480 /** 4481 * Enforces that only the system UID or root's UID can call a method exposed 4482 * via Binder. 4483 * 4484 * @param message used as message if SecurityException is thrown 4485 * @throws SecurityException if the caller is not system or root 4486 */ 4487 private static final void enforceSystemOrRoot(String message) { 4488 final int uid = Binder.getCallingUid(); 4489 if (uid != Process.SYSTEM_UID && uid != 0) { 4490 throw new SecurityException(message); 4491 } 4492 } 4493 4494 @Override 4495 public void performBootDexOpt() { 4496 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4497 4498 final HashSet<PackageParser.Package> pkgs; 4499 synchronized (mPackages) { 4500 pkgs = mDeferredDexOpt; 4501 mDeferredDexOpt = null; 4502 } 4503 4504 if (pkgs != null) { 4505 // Filter out packages that aren't recently used. 4506 // 4507 // The exception is first boot of a non-eng device, which 4508 // should do a full dexopt. 4509 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4510 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4511 // TODO: add a property to control this? 4512 long dexOptLRUThresholdInMinutes; 4513 if (eng) { 4514 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4515 } else { 4516 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4517 } 4518 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4519 4520 int total = pkgs.size(); 4521 int skipped = 0; 4522 long now = System.currentTimeMillis(); 4523 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4524 PackageParser.Package pkg = i.next(); 4525 long then = pkg.mLastPackageUsageTimeInMills; 4526 if (then + dexOptLRUThresholdInMills < now) { 4527 if (DEBUG_DEXOPT) { 4528 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4529 ((then == 0) ? "never" : new Date(then))); 4530 } 4531 i.remove(); 4532 skipped++; 4533 } 4534 } 4535 if (DEBUG_DEXOPT) { 4536 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4537 } 4538 } 4539 4540 int i = 0; 4541 for (PackageParser.Package pkg : pkgs) { 4542 i++; 4543 if (DEBUG_DEXOPT) { 4544 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4545 + ": " + pkg.packageName); 4546 } 4547 if (!isFirstBoot()) { 4548 try { 4549 ActivityManagerNative.getDefault().showBootMessage( 4550 mContext.getResources().getString( 4551 R.string.android_upgrading_apk, 4552 i, pkgs.size()), true); 4553 } catch (RemoteException e) { 4554 } 4555 } 4556 PackageParser.Package p = pkg; 4557 synchronized (mInstallLock) { 4558 performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */, 4559 true /* include dependencies */); 4560 } 4561 } 4562 } 4563 } 4564 4565 @Override 4566 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4567 return performDexOpt(packageName, instructionSet, true); 4568 } 4569 4570 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4571 if (info.primaryCpuAbi == null) { 4572 return getPreferredInstructionSet(); 4573 } 4574 4575 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4576 } 4577 4578 public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) { 4579 PackageParser.Package p; 4580 final String targetInstructionSet; 4581 synchronized (mPackages) { 4582 p = mPackages.get(packageName); 4583 if (p == null) { 4584 return false; 4585 } 4586 if (updateUsage) { 4587 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4588 } 4589 mPackageUsage.write(false); 4590 4591 targetInstructionSet = instructionSet != null ? instructionSet : 4592 getPrimaryInstructionSet(p.applicationInfo); 4593 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4594 return false; 4595 } 4596 } 4597 4598 synchronized (mInstallLock) { 4599 final String[] instructionSets = new String[] { targetInstructionSet }; 4600 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4601 true /* include dependencies */) == DEX_OPT_PERFORMED; 4602 } 4603 } 4604 4605 public HashSet<String> getPackagesThatNeedDexOpt() { 4606 HashSet<String> pkgs = null; 4607 synchronized (mPackages) { 4608 for (PackageParser.Package p : mPackages.values()) { 4609 if (DEBUG_DEXOPT) { 4610 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4611 } 4612 if (!p.mDexOptPerformed.isEmpty()) { 4613 continue; 4614 } 4615 if (pkgs == null) { 4616 pkgs = new HashSet<String>(); 4617 } 4618 pkgs.add(p.packageName); 4619 } 4620 } 4621 return pkgs; 4622 } 4623 4624 public void shutdown() { 4625 mPackageUsage.write(true); 4626 } 4627 4628 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4629 boolean forceDex, boolean defer, HashSet<String> done) { 4630 for (int i=0; i<libs.size(); i++) { 4631 PackageParser.Package libPkg; 4632 String libName; 4633 synchronized (mPackages) { 4634 libName = libs.get(i); 4635 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4636 if (lib != null && lib.apk != null) { 4637 libPkg = mPackages.get(lib.apk); 4638 } else { 4639 libPkg = null; 4640 } 4641 } 4642 if (libPkg != null && !done.contains(libName)) { 4643 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4644 } 4645 } 4646 } 4647 4648 static final int DEX_OPT_SKIPPED = 0; 4649 static final int DEX_OPT_PERFORMED = 1; 4650 static final int DEX_OPT_DEFERRED = 2; 4651 static final int DEX_OPT_FAILED = -1; 4652 4653 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4654 boolean forceDex, boolean defer, HashSet<String> done) { 4655 final String[] instructionSets = targetInstructionSets != null ? 4656 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4657 4658 if (done != null) { 4659 done.add(pkg.packageName); 4660 if (pkg.usesLibraries != null) { 4661 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4662 } 4663 if (pkg.usesOptionalLibraries != null) { 4664 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4665 } 4666 } 4667 4668 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4669 return DEX_OPT_SKIPPED; 4670 } 4671 4672 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4673 boolean performedDexOpt = false; 4674 // There are three basic cases here: 4675 // 1.) we need to dexopt, either because we are forced or it is needed 4676 // 2.) we are defering a needed dexopt 4677 // 3.) we are skipping an unneeded dexopt 4678 for (String path : paths) { 4679 for (String instructionSet : instructionSets) { 4680 if (!forceDex && pkg.mDexOptPerformed.contains(instructionSet)) { 4681 continue; 4682 } 4683 4684 try { 4685 final boolean isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4686 pkg.packageName, instructionSet, defer); 4687 if (forceDex || (!defer && isDexOptNeeded)) { 4688 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4689 + pkg.applicationInfo.packageName + " isa=" + instructionSet); 4690 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4691 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4692 pkg.packageName, instructionSet); 4693 4694 if (ret < 0) { 4695 // Don't bother running dexopt again if we failed, it will probably 4696 // just result in an error again. Also, don't bother dexopting for other 4697 // paths & ISAs. 4698 return DEX_OPT_FAILED; 4699 } else { 4700 performedDexOpt = true; 4701 pkg.mDexOptPerformed.add(instructionSet); 4702 } 4703 } 4704 4705 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4706 // paths and instruction sets. We'll deal with them all together when we process 4707 // our list of deferred dexopts. 4708 if (defer && isDexOptNeeded) { 4709 if (mDeferredDexOpt == null) { 4710 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4711 } 4712 mDeferredDexOpt.add(pkg); 4713 return DEX_OPT_DEFERRED; 4714 } 4715 } catch (FileNotFoundException e) { 4716 Slog.w(TAG, "Apk not found for dexopt: " + path); 4717 return DEX_OPT_FAILED; 4718 } catch (IOException e) { 4719 Slog.w(TAG, "IOException reading apk: " + path, e); 4720 return DEX_OPT_FAILED; 4721 } catch (StaleDexCacheError e) { 4722 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4723 return DEX_OPT_FAILED; 4724 } catch (Exception e) { 4725 Slog.w(TAG, "Exception when doing dexopt : ", e); 4726 return DEX_OPT_FAILED; 4727 } 4728 } 4729 } 4730 4731 // If we've gotten here, we're sure that no error occurred and that we haven't 4732 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4733 // we've skipped all of them because they are up to date. In both cases this 4734 // package doesn't need dexopt any longer. 4735 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4736 } 4737 4738 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4739 if (info.primaryCpuAbi != null) { 4740 if (info.secondaryCpuAbi != null) { 4741 return new String[] { 4742 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4743 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4744 } else { 4745 return new String[] { 4746 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4747 } 4748 } 4749 4750 return new String[] { getPreferredInstructionSet() }; 4751 } 4752 4753 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4754 if (ps.primaryCpuAbiString != null) { 4755 if (ps.secondaryCpuAbiString != null) { 4756 return new String[] { 4757 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4758 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4759 } else { 4760 return new String[] { 4761 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4762 } 4763 } 4764 4765 return new String[] { getPreferredInstructionSet() }; 4766 } 4767 4768 private static String getPreferredInstructionSet() { 4769 if (sPreferredInstructionSet == null) { 4770 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4771 } 4772 4773 return sPreferredInstructionSet; 4774 } 4775 4776 private static List<String> getAllInstructionSets() { 4777 final String[] allAbis = Build.SUPPORTED_ABIS; 4778 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4779 4780 for (String abi : allAbis) { 4781 final String instructionSet = VMRuntime.getInstructionSet(abi); 4782 if (!allInstructionSets.contains(instructionSet)) { 4783 allInstructionSets.add(instructionSet); 4784 } 4785 } 4786 4787 return allInstructionSets; 4788 } 4789 4790 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4791 boolean forceDex, boolean defer, boolean inclDependencies) { 4792 HashSet<String> done; 4793 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4794 done = new HashSet<String>(); 4795 done.add(pkg.packageName); 4796 } else { 4797 done = null; 4798 } 4799 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4800 } 4801 4802 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4803 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4804 Slog.w(TAG, "Unable to update from " + oldPkg.name 4805 + " to " + newPkg.packageName 4806 + ": old package not in system partition"); 4807 return false; 4808 } else if (mPackages.get(oldPkg.name) != null) { 4809 Slog.w(TAG, "Unable to update from " + oldPkg.name 4810 + " to " + newPkg.packageName 4811 + ": old package still exists"); 4812 return false; 4813 } 4814 return true; 4815 } 4816 4817 File getDataPathForUser(int userId) { 4818 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4819 } 4820 4821 private File getDataPathForPackage(String packageName, int userId) { 4822 /* 4823 * Until we fully support multiple users, return the directory we 4824 * previously would have. The PackageManagerTests will need to be 4825 * revised when this is changed back.. 4826 */ 4827 if (userId == 0) { 4828 return new File(mAppDataDir, packageName); 4829 } else { 4830 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4831 + File.separator + packageName); 4832 } 4833 } 4834 4835 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4836 int[] users = sUserManager.getUserIds(); 4837 int res = mInstaller.install(packageName, uid, uid, seinfo); 4838 if (res < 0) { 4839 return res; 4840 } 4841 for (int user : users) { 4842 if (user != 0) { 4843 res = mInstaller.createUserData(packageName, 4844 UserHandle.getUid(user, uid), user, seinfo); 4845 if (res < 0) { 4846 return res; 4847 } 4848 } 4849 } 4850 return res; 4851 } 4852 4853 private int removeDataDirsLI(String packageName) { 4854 int[] users = sUserManager.getUserIds(); 4855 int res = 0; 4856 for (int user : users) { 4857 int resInner = mInstaller.remove(packageName, user); 4858 if (resInner < 0) { 4859 res = resInner; 4860 } 4861 } 4862 4863 return res; 4864 } 4865 4866 private int deleteCodeCacheDirsLI(String packageName) { 4867 int[] users = sUserManager.getUserIds(); 4868 int res = 0; 4869 for (int user : users) { 4870 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4871 if (resInner < 0) { 4872 res = resInner; 4873 } 4874 } 4875 return res; 4876 } 4877 4878 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4879 PackageParser.Package changingLib) { 4880 if (file.path != null) { 4881 usesLibraryFiles.add(file.path); 4882 return; 4883 } 4884 PackageParser.Package p = mPackages.get(file.apk); 4885 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4886 // If we are doing this while in the middle of updating a library apk, 4887 // then we need to make sure to use that new apk for determining the 4888 // dependencies here. (We haven't yet finished committing the new apk 4889 // to the package manager state.) 4890 if (p == null || p.packageName.equals(changingLib.packageName)) { 4891 p = changingLib; 4892 } 4893 } 4894 if (p != null) { 4895 usesLibraryFiles.addAll(p.getAllCodePaths()); 4896 } 4897 } 4898 4899 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4900 PackageParser.Package changingLib) throws PackageManagerException { 4901 // We might be upgrading from a version of the platform that did not 4902 // provide per-package native library directories for system apps. 4903 // Fix that up here. 4904 if (isSystemApp(pkg)) { 4905 PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName); 4906 if (!isUpdatedSystemApp(pkg)) { 4907 setBundledAppAbisAndRoots(pkg, ps); 4908 } 4909 } 4910 4911 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4912 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4913 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4914 for (int i=0; i<N; i++) { 4915 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4916 if (file == null) { 4917 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4918 "Package " + pkg.packageName + " requires unavailable shared library " 4919 + pkg.usesLibraries.get(i) + "; failing!"); 4920 } 4921 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4922 } 4923 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4924 for (int i=0; i<N; i++) { 4925 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4926 if (file == null) { 4927 Slog.w(TAG, "Package " + pkg.packageName 4928 + " desires unavailable shared library " 4929 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4930 } else { 4931 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4932 } 4933 } 4934 N = usesLibraryFiles.size(); 4935 if (N > 0) { 4936 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4937 } else { 4938 pkg.usesLibraryFiles = null; 4939 } 4940 } 4941 } 4942 4943 private static boolean hasString(List<String> list, List<String> which) { 4944 if (list == null) { 4945 return false; 4946 } 4947 for (int i=list.size()-1; i>=0; i--) { 4948 for (int j=which.size()-1; j>=0; j--) { 4949 if (which.get(j).equals(list.get(i))) { 4950 return true; 4951 } 4952 } 4953 } 4954 return false; 4955 } 4956 4957 private void updateAllSharedLibrariesLPw() { 4958 for (PackageParser.Package pkg : mPackages.values()) { 4959 try { 4960 updateSharedLibrariesLPw(pkg, null); 4961 } catch (PackageManagerException e) { 4962 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4963 } 4964 } 4965 } 4966 4967 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4968 PackageParser.Package changingPkg) { 4969 ArrayList<PackageParser.Package> res = null; 4970 for (PackageParser.Package pkg : mPackages.values()) { 4971 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4972 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4973 if (res == null) { 4974 res = new ArrayList<PackageParser.Package>(); 4975 } 4976 res.add(pkg); 4977 try { 4978 updateSharedLibrariesLPw(pkg, changingPkg); 4979 } catch (PackageManagerException e) { 4980 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4981 } 4982 } 4983 } 4984 return res; 4985 } 4986 4987 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 4988 int scanMode, long currentTime, UserHandle user, String abiOverride) 4989 throws PackageManagerException { 4990 final File scanFile = new File(pkg.codePath); 4991 if (pkg.applicationInfo.getCodePath() == null || 4992 pkg.applicationInfo.getResourcePath() == null) { 4993 // Bail out. The resource and code paths haven't been set. 4994 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 4995 "Code and resource paths haven't been set correctly"); 4996 } 4997 4998 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4999 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5000 } 5001 5002 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5003 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5004 } 5005 5006 if (mCustomResolverComponentName != null && 5007 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5008 setUpCustomResolverActivity(pkg); 5009 } 5010 5011 if (pkg.packageName.equals("android")) { 5012 synchronized (mPackages) { 5013 if (mAndroidApplication != null) { 5014 Slog.w(TAG, "*************************************************"); 5015 Slog.w(TAG, "Core android package being redefined. Skipping."); 5016 Slog.w(TAG, " file=" + scanFile); 5017 Slog.w(TAG, "*************************************************"); 5018 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5019 "Core android package being redefined. Skipping."); 5020 } 5021 5022 // Set up information for our fall-back user intent resolution activity. 5023 mPlatformPackage = pkg; 5024 pkg.mVersionCode = mSdkVersion; 5025 mAndroidApplication = pkg.applicationInfo; 5026 5027 if (!mResolverReplaced) { 5028 mResolveActivity.applicationInfo = mAndroidApplication; 5029 mResolveActivity.name = ResolverActivity.class.getName(); 5030 mResolveActivity.packageName = mAndroidApplication.packageName; 5031 mResolveActivity.processName = "system:ui"; 5032 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5033 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5034 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5035 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5036 mResolveActivity.exported = true; 5037 mResolveActivity.enabled = true; 5038 mResolveInfo.activityInfo = mResolveActivity; 5039 mResolveInfo.priority = 0; 5040 mResolveInfo.preferredOrder = 0; 5041 mResolveInfo.match = 0; 5042 mResolveComponentName = new ComponentName( 5043 mAndroidApplication.packageName, mResolveActivity.name); 5044 } 5045 } 5046 } 5047 5048 if (DEBUG_PACKAGE_SCANNING) { 5049 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5050 Log.d(TAG, "Scanning package " + pkg.packageName); 5051 } 5052 5053 if (mPackages.containsKey(pkg.packageName) 5054 || mSharedLibraries.containsKey(pkg.packageName)) { 5055 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5056 "Application package " + pkg.packageName 5057 + " already installed. Skipping duplicate."); 5058 } 5059 5060 // Initialize package source and resource directories 5061 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5062 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5063 5064 SharedUserSetting suid = null; 5065 PackageSetting pkgSetting = null; 5066 5067 if (!isSystemApp(pkg)) { 5068 // Only system apps can use these features. 5069 pkg.mOriginalPackages = null; 5070 pkg.mRealPackage = null; 5071 pkg.mAdoptPermissions = null; 5072 } 5073 5074 // writer 5075 synchronized (mPackages) { 5076 if (pkg.mSharedUserId != null) { 5077 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5078 if (suid == null) { 5079 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5080 "Creating application package " + pkg.packageName 5081 + " for shared user failed"); 5082 } 5083 if (DEBUG_PACKAGE_SCANNING) { 5084 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5085 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5086 + "): packages=" + suid.packages); 5087 } 5088 } 5089 5090 // Check if we are renaming from an original package name. 5091 PackageSetting origPackage = null; 5092 String realName = null; 5093 if (pkg.mOriginalPackages != null) { 5094 // This package may need to be renamed to a previously 5095 // installed name. Let's check on that... 5096 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5097 if (pkg.mOriginalPackages.contains(renamed)) { 5098 // This package had originally been installed as the 5099 // original name, and we have already taken care of 5100 // transitioning to the new one. Just update the new 5101 // one to continue using the old name. 5102 realName = pkg.mRealPackage; 5103 if (!pkg.packageName.equals(renamed)) { 5104 // Callers into this function may have already taken 5105 // care of renaming the package; only do it here if 5106 // it is not already done. 5107 pkg.setPackageName(renamed); 5108 } 5109 5110 } else { 5111 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5112 if ((origPackage = mSettings.peekPackageLPr( 5113 pkg.mOriginalPackages.get(i))) != null) { 5114 // We do have the package already installed under its 5115 // original name... should we use it? 5116 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5117 // New package is not compatible with original. 5118 origPackage = null; 5119 continue; 5120 } else if (origPackage.sharedUser != null) { 5121 // Make sure uid is compatible between packages. 5122 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5123 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5124 + " to " + pkg.packageName + ": old uid " 5125 + origPackage.sharedUser.name 5126 + " differs from " + pkg.mSharedUserId); 5127 origPackage = null; 5128 continue; 5129 } 5130 } else { 5131 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5132 + pkg.packageName + " to old name " + origPackage.name); 5133 } 5134 break; 5135 } 5136 } 5137 } 5138 } 5139 5140 if (mTransferedPackages.contains(pkg.packageName)) { 5141 Slog.w(TAG, "Package " + pkg.packageName 5142 + " was transferred to another, but its .apk remains"); 5143 } 5144 5145 // Just create the setting, don't add it yet. For already existing packages 5146 // the PkgSetting exists already and doesn't have to be created. 5147 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5148 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5149 pkg.applicationInfo.primaryCpuAbi, 5150 pkg.applicationInfo.secondaryCpuAbi, 5151 pkg.applicationInfo.flags, user, false); 5152 if (pkgSetting == null) { 5153 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5154 "Creating application package " + pkg.packageName + " failed"); 5155 } 5156 5157 if (pkgSetting.origPackage != null) { 5158 // If we are first transitioning from an original package, 5159 // fix up the new package's name now. We need to do this after 5160 // looking up the package under its new name, so getPackageLP 5161 // can take care of fiddling things correctly. 5162 pkg.setPackageName(origPackage.name); 5163 5164 // File a report about this. 5165 String msg = "New package " + pkgSetting.realName 5166 + " renamed to replace old package " + pkgSetting.name; 5167 reportSettingsProblem(Log.WARN, msg); 5168 5169 // Make a note of it. 5170 mTransferedPackages.add(origPackage.name); 5171 5172 // No longer need to retain this. 5173 pkgSetting.origPackage = null; 5174 } 5175 5176 if (realName != null) { 5177 // Make a note of it. 5178 mTransferedPackages.add(pkg.packageName); 5179 } 5180 5181 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5182 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5183 } 5184 5185 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5186 // Check all shared libraries and map to their actual file path. 5187 // We only do this here for apps not on a system dir, because those 5188 // are the only ones that can fail an install due to this. We 5189 // will take care of the system apps by updating all of their 5190 // library paths after the scan is done. 5191 updateSharedLibrariesLPw(pkg, null); 5192 } 5193 5194 if (mFoundPolicyFile) { 5195 SELinuxMMAC.assignSeinfoValue(pkg); 5196 } 5197 5198 pkg.applicationInfo.uid = pkgSetting.appId; 5199 pkg.mExtras = pkgSetting; 5200 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5201 try { 5202 verifySignaturesLP(pkgSetting, pkg); 5203 } catch (PackageManagerException e) { 5204 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5205 throw e; 5206 } 5207 // The signature has changed, but this package is in the system 5208 // image... let's recover! 5209 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5210 // However... if this package is part of a shared user, but it 5211 // doesn't match the signature of the shared user, let's fail. 5212 // What this means is that you can't change the signatures 5213 // associated with an overall shared user, which doesn't seem all 5214 // that unreasonable. 5215 if (pkgSetting.sharedUser != null) { 5216 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5217 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5218 throw new PackageManagerException( 5219 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5220 "Signature mismatch for shared user : " 5221 + pkgSetting.sharedUser); 5222 } 5223 } 5224 // File a report about this. 5225 String msg = "System package " + pkg.packageName 5226 + " signature changed; retaining data."; 5227 reportSettingsProblem(Log.WARN, msg); 5228 } 5229 } else { 5230 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5231 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5232 + pkg.packageName + " upgrade keys do not match the " 5233 + "previously installed version"); 5234 } else { 5235 // signatures may have changed as result of upgrade 5236 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5237 } 5238 } 5239 // Verify that this new package doesn't have any content providers 5240 // that conflict with existing packages. Only do this if the 5241 // package isn't already installed, since we don't want to break 5242 // things that are installed. 5243 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5244 final int N = pkg.providers.size(); 5245 int i; 5246 for (i=0; i<N; i++) { 5247 PackageParser.Provider p = pkg.providers.get(i); 5248 if (p.info.authority != null) { 5249 String names[] = p.info.authority.split(";"); 5250 for (int j = 0; j < names.length; j++) { 5251 if (mProvidersByAuthority.containsKey(names[j])) { 5252 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5253 final String otherPackageName = 5254 ((other != null && other.getComponentName() != null) ? 5255 other.getComponentName().getPackageName() : "?"); 5256 throw new PackageManagerException( 5257 INSTALL_FAILED_CONFLICTING_PROVIDER, 5258 "Can't install because provider name " + names[j] 5259 + " (in package " + pkg.applicationInfo.packageName 5260 + ") is already used by " + otherPackageName); 5261 } 5262 } 5263 } 5264 } 5265 } 5266 5267 if (pkg.mAdoptPermissions != null) { 5268 // This package wants to adopt ownership of permissions from 5269 // another package. 5270 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5271 final String origName = pkg.mAdoptPermissions.get(i); 5272 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5273 if (orig != null) { 5274 if (verifyPackageUpdateLPr(orig, pkg)) { 5275 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5276 + pkg.packageName); 5277 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5278 } 5279 } 5280 } 5281 } 5282 } 5283 5284 final String pkgName = pkg.packageName; 5285 5286 final long scanFileTime = scanFile.lastModified(); 5287 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5288 pkg.applicationInfo.processName = fixProcessName( 5289 pkg.applicationInfo.packageName, 5290 pkg.applicationInfo.processName, 5291 pkg.applicationInfo.uid); 5292 5293 File dataPath; 5294 if (mPlatformPackage == pkg) { 5295 // The system package is special. 5296 dataPath = new File (Environment.getDataDirectory(), "system"); 5297 pkg.applicationInfo.dataDir = dataPath.getPath(); 5298 } else { 5299 // This is a normal package, need to make its data directory. 5300 dataPath = getDataPathForPackage(pkg.packageName, 0); 5301 5302 boolean uidError = false; 5303 5304 if (dataPath.exists()) { 5305 int currentUid = 0; 5306 try { 5307 StructStat stat = Os.stat(dataPath.getPath()); 5308 currentUid = stat.st_uid; 5309 } catch (ErrnoException e) { 5310 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5311 } 5312 5313 // If we have mismatched owners for the data path, we have a problem. 5314 if (currentUid != pkg.applicationInfo.uid) { 5315 boolean recovered = false; 5316 if (currentUid == 0) { 5317 // The directory somehow became owned by root. Wow. 5318 // This is probably because the system was stopped while 5319 // installd was in the middle of messing with its libs 5320 // directory. Ask installd to fix that. 5321 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5322 pkg.applicationInfo.uid); 5323 if (ret >= 0) { 5324 recovered = true; 5325 String msg = "Package " + pkg.packageName 5326 + " unexpectedly changed to uid 0; recovered to " + 5327 + pkg.applicationInfo.uid; 5328 reportSettingsProblem(Log.WARN, msg); 5329 } 5330 } 5331 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5332 || (scanMode&SCAN_BOOTING) != 0)) { 5333 // If this is a system app, we can at least delete its 5334 // current data so the application will still work. 5335 int ret = removeDataDirsLI(pkgName); 5336 if (ret >= 0) { 5337 // TODO: Kill the processes first 5338 // Old data gone! 5339 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5340 ? "System package " : "Third party package "; 5341 String msg = prefix + pkg.packageName 5342 + " has changed from uid: " 5343 + currentUid + " to " 5344 + pkg.applicationInfo.uid + "; old data erased"; 5345 reportSettingsProblem(Log.WARN, msg); 5346 recovered = true; 5347 5348 // And now re-install the app. 5349 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5350 pkg.applicationInfo.seinfo); 5351 if (ret == -1) { 5352 // Ack should not happen! 5353 msg = prefix + pkg.packageName 5354 + " could not have data directory re-created after delete."; 5355 reportSettingsProblem(Log.WARN, msg); 5356 throw new PackageManagerException( 5357 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5358 } 5359 } 5360 if (!recovered) { 5361 mHasSystemUidErrors = true; 5362 } 5363 } else if (!recovered) { 5364 // If we allow this install to proceed, we will be broken. 5365 // Abort, abort! 5366 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5367 "scanPackageLI"); 5368 } 5369 if (!recovered) { 5370 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5371 + pkg.applicationInfo.uid + "/fs_" 5372 + currentUid; 5373 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5374 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5375 String msg = "Package " + pkg.packageName 5376 + " has mismatched uid: " 5377 + currentUid + " on disk, " 5378 + pkg.applicationInfo.uid + " in settings"; 5379 // writer 5380 synchronized (mPackages) { 5381 mSettings.mReadMessages.append(msg); 5382 mSettings.mReadMessages.append('\n'); 5383 uidError = true; 5384 if (!pkgSetting.uidError) { 5385 reportSettingsProblem(Log.ERROR, msg); 5386 } 5387 } 5388 } 5389 } 5390 pkg.applicationInfo.dataDir = dataPath.getPath(); 5391 if (mShouldRestoreconData) { 5392 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5393 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5394 pkg.applicationInfo.uid); 5395 } 5396 } else { 5397 if (DEBUG_PACKAGE_SCANNING) { 5398 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5399 Log.v(TAG, "Want this data dir: " + dataPath); 5400 } 5401 //invoke installer to do the actual installation 5402 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5403 pkg.applicationInfo.seinfo); 5404 if (ret < 0) { 5405 // Error from installer 5406 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5407 "Unable to create data dirs [errorCode=" + ret + "]"); 5408 } 5409 5410 if (dataPath.exists()) { 5411 pkg.applicationInfo.dataDir = dataPath.getPath(); 5412 } else { 5413 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5414 pkg.applicationInfo.dataDir = null; 5415 } 5416 } 5417 5418 pkgSetting.uidError = uidError; 5419 } 5420 5421 final String path = scanFile.getPath(); 5422 final String codePath = pkg.applicationInfo.getCodePath(); 5423 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5424 // For the case where we had previously uninstalled an update, get rid 5425 // of any native binaries we might have unpackaged. Note that this assumes 5426 // that system app updates were not installed via ASEC. 5427 // 5428 // TODO(multiArch): Is this cleanup really necessary ? 5429 NativeLibraryHelper.removeNativeBinariesFromDirLI( 5430 new File(codePath, LIB_DIR_NAME), false /* delete dirs */); 5431 setBundledAppAbisAndRoots(pkg, pkgSetting); 5432 setNativeLibraryPaths(pkg); 5433 } else { 5434 // TODO: We can probably be smarter about this stuff. For installed apps, 5435 // we can calculate this information at install time once and for all. For 5436 // system apps, we can probably assume that this information doesn't change 5437 // after the first boot scan. As things stand, we do lots of unnecessary work. 5438 5439 // Give ourselves some initial paths; we'll come back for another 5440 // pass once we've determined ABI below. 5441 setNativeLibraryPaths(pkg); 5442 5443 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5444 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5445 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5446 5447 NativeLibraryHelper.Handle handle = null; 5448 try { 5449 handle = NativeLibraryHelper.Handle.create(scanFile); 5450 // TODO(multiArch): This can be null for apps that didn't go through the 5451 // usual installation process. We can calculate it again, like we 5452 // do during install time. 5453 // 5454 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5455 // unnecessary. 5456 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5457 5458 // Null out the abis so that they can be recalculated. 5459 pkg.applicationInfo.primaryCpuAbi = null; 5460 pkg.applicationInfo.secondaryCpuAbi = null; 5461 if (isMultiArch(pkg.applicationInfo)) { 5462 // Warn if we've set an abiOverride for multi-lib packages.. 5463 // By definition, we need to copy both 32 and 64 bit libraries for 5464 // such packages. 5465 if (abiOverride != null) { 5466 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5467 } 5468 5469 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5470 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5471 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5472 if (isAsec) { 5473 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5474 } else { 5475 abi32 = copyNativeLibrariesForInternalApp(handle, 5476 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs); 5477 } 5478 } 5479 5480 maybeThrowExceptionForMultiArchCopy( 5481 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5482 5483 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5484 if (isAsec) { 5485 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5486 } else { 5487 abi64 = copyNativeLibrariesForInternalApp(handle, 5488 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs); 5489 } 5490 } 5491 5492 maybeThrowExceptionForMultiArchCopy( 5493 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5494 5495 if (abi64 >= 0) { 5496 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5497 } 5498 5499 if (abi32 >= 0) { 5500 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5501 if (abi64 >= 0) { 5502 pkg.applicationInfo.secondaryCpuAbi = abi; 5503 } else { 5504 pkg.applicationInfo.primaryCpuAbi = abi; 5505 } 5506 } 5507 } else { 5508 String[] abiList = (abiOverride != null) ? 5509 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 5510 5511 // Enable gross and lame hacks for apps that are built with old 5512 // SDK tools. We must scan their APKs for renderscript bitcode and 5513 // not launch them if it's present. Don't bother checking on devices 5514 // that don't have 64 bit support. 5515 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null && 5516 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5517 abiList = Build.SUPPORTED_32_BIT_ABIS; 5518 } 5519 5520 final int copyRet; 5521 if (isAsec) { 5522 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5523 } else { 5524 copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryRoot, abiList, 5525 useIsaSpecificSubdirs); 5526 } 5527 5528 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5529 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5530 "Error unpackaging native libs for app, errorCode=" + copyRet); 5531 } 5532 5533 if (copyRet >= 0) { 5534 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5535 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && abiOverride != null) { 5536 pkg.applicationInfo.primaryCpuAbi = abiOverride; 5537 } 5538 } 5539 } catch (IOException ioe) { 5540 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5541 } finally { 5542 IoUtils.closeQuietly(handle); 5543 } 5544 5545 // Now that we've calculated the ABIs and determined if it's an internal app, 5546 // we will go ahead and populate the nativeLibraryPath. 5547 setNativeLibraryPaths(pkg); 5548 5549 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5550 final int[] userIds = sUserManager.getUserIds(); 5551 synchronized (mInstallLock) { 5552 // Create a native library symlink only if we have native libraries 5553 // and if the native libraries are 32 bit libraries. We do not provide 5554 // this symlink for 64 bit libraries. 5555 if (pkg.applicationInfo.primaryCpuAbi != null && 5556 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5557 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5558 for (int userId : userIds) { 5559 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5560 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5561 "Failed linking native library dir (user=" + userId + ")"); 5562 } 5563 } 5564 } 5565 } 5566 5567 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5568 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5569 } 5570 5571 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5572 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5573 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5574 5575 // Push the derived path down into PackageSettings so we know what to 5576 // clean up at uninstall time. 5577 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5578 5579 if (DEBUG_ABI_SELECTION) { 5580 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5581 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5582 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5583 } 5584 5585 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5586 // We don't do this here during boot because we can do it all 5587 // at once after scanning all existing packages. 5588 // 5589 // We also do this *before* we perform dexopt on this package, so that 5590 // we can avoid redundant dexopts, and also to make sure we've got the 5591 // code and package path correct. 5592 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5593 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0); 5594 } 5595 5596 if ((scanMode&SCAN_NO_DEX) == 0) { 5597 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5598 == DEX_OPT_FAILED) { 5599 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5600 removeDataDirsLI(pkg.packageName); 5601 } 5602 5603 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5604 } 5605 } 5606 5607 if (mFactoryTest && pkg.requestedPermissions.contains( 5608 android.Manifest.permission.FACTORY_TEST)) { 5609 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5610 } 5611 5612 ArrayList<PackageParser.Package> clientLibPkgs = null; 5613 5614 // writer 5615 synchronized (mPackages) { 5616 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5617 // Only system apps can add new shared libraries. 5618 if (pkg.libraryNames != null) { 5619 for (int i=0; i<pkg.libraryNames.size(); i++) { 5620 String name = pkg.libraryNames.get(i); 5621 boolean allowed = false; 5622 if (isUpdatedSystemApp(pkg)) { 5623 // New library entries can only be added through the 5624 // system image. This is important to get rid of a lot 5625 // of nasty edge cases: for example if we allowed a non- 5626 // system update of the app to add a library, then uninstalling 5627 // the update would make the library go away, and assumptions 5628 // we made such as through app install filtering would now 5629 // have allowed apps on the device which aren't compatible 5630 // with it. Better to just have the restriction here, be 5631 // conservative, and create many fewer cases that can negatively 5632 // impact the user experience. 5633 final PackageSetting sysPs = mSettings 5634 .getDisabledSystemPkgLPr(pkg.packageName); 5635 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5636 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5637 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5638 allowed = true; 5639 allowed = true; 5640 break; 5641 } 5642 } 5643 } 5644 } else { 5645 allowed = true; 5646 } 5647 if (allowed) { 5648 if (!mSharedLibraries.containsKey(name)) { 5649 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5650 } else if (!name.equals(pkg.packageName)) { 5651 Slog.w(TAG, "Package " + pkg.packageName + " library " 5652 + name + " already exists; skipping"); 5653 } 5654 } else { 5655 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5656 + name + " that is not declared on system image; skipping"); 5657 } 5658 } 5659 if ((scanMode&SCAN_BOOTING) == 0) { 5660 // If we are not booting, we need to update any applications 5661 // that are clients of our shared library. If we are booting, 5662 // this will all be done once the scan is complete. 5663 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5664 } 5665 } 5666 } 5667 } 5668 5669 // We also need to dexopt any apps that are dependent on this library. Note that 5670 // if these fail, we should abort the install since installing the library will 5671 // result in some apps being broken. 5672 if (clientLibPkgs != null) { 5673 if ((scanMode&SCAN_NO_DEX) == 0) { 5674 for (int i=0; i<clientLibPkgs.size(); i++) { 5675 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5676 if (performDexOptLI(clientPkg, null /* instruction sets */, 5677 forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5678 == DEX_OPT_FAILED) { 5679 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5680 removeDataDirsLI(pkg.packageName); 5681 } 5682 5683 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5684 "scanPackageLI failed to dexopt clientLibPkgs"); 5685 } 5686 } 5687 } 5688 } 5689 5690 // Request the ActivityManager to kill the process(only for existing packages) 5691 // so that we do not end up in a confused state while the user is still using the older 5692 // version of the application while the new one gets installed. 5693 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5694 // If the package lives in an asec, tell everyone that the container is going 5695 // away so they can clean up any references to its resources (which would prevent 5696 // vold from being able to unmount the asec) 5697 if (isForwardLocked(pkg) || isExternal(pkg)) { 5698 if (DEBUG_INSTALL) { 5699 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5700 } 5701 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5702 final ArrayList<String> pkgList = new ArrayList<String>(1); 5703 pkgList.add(pkg.applicationInfo.packageName); 5704 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5705 } 5706 5707 // Post the request that it be killed now that the going-away broadcast is en route 5708 killApplication(pkg.applicationInfo.packageName, 5709 pkg.applicationInfo.uid, "update pkg"); 5710 } 5711 5712 // Also need to kill any apps that are dependent on the library. 5713 if (clientLibPkgs != null) { 5714 for (int i=0; i<clientLibPkgs.size(); i++) { 5715 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5716 killApplication(clientPkg.applicationInfo.packageName, 5717 clientPkg.applicationInfo.uid, "update lib"); 5718 } 5719 } 5720 5721 // writer 5722 synchronized (mPackages) { 5723 // We don't expect installation to fail beyond this point, 5724 if ((scanMode&SCAN_MONITOR) != 0) { 5725 mAppDirs.put(pkg.codePath, pkg); 5726 } 5727 // Add the new setting to mSettings 5728 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5729 // Add the new setting to mPackages 5730 mPackages.put(pkg.applicationInfo.packageName, pkg); 5731 // Make sure we don't accidentally delete its data. 5732 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5733 while (iter.hasNext()) { 5734 PackageCleanItem item = iter.next(); 5735 if (pkgName.equals(item.packageName)) { 5736 iter.remove(); 5737 } 5738 } 5739 5740 // Take care of first install / last update times. 5741 if (currentTime != 0) { 5742 if (pkgSetting.firstInstallTime == 0) { 5743 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5744 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5745 pkgSetting.lastUpdateTime = currentTime; 5746 } 5747 } else if (pkgSetting.firstInstallTime == 0) { 5748 // We need *something*. Take time time stamp of the file. 5749 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5750 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5751 if (scanFileTime != pkgSetting.timeStamp) { 5752 // A package on the system image has changed; consider this 5753 // to be an update. 5754 pkgSetting.lastUpdateTime = scanFileTime; 5755 } 5756 } 5757 5758 // Add the package's KeySets to the global KeySetManagerService 5759 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5760 try { 5761 // Old KeySetData no longer valid. 5762 ksms.removeAppKeySetDataLPw(pkg.packageName); 5763 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5764 if (pkg.mKeySetMapping != null) { 5765 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5766 pkg.mKeySetMapping.entrySet()) { 5767 if (entry.getValue() != null) { 5768 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5769 entry.getValue(), entry.getKey()); 5770 } 5771 } 5772 if (pkg.mUpgradeKeySets != null) { 5773 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5774 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5775 } 5776 } 5777 } 5778 } catch (NullPointerException e) { 5779 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5780 } catch (IllegalArgumentException e) { 5781 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5782 } 5783 5784 int N = pkg.providers.size(); 5785 StringBuilder r = null; 5786 int i; 5787 for (i=0; i<N; i++) { 5788 PackageParser.Provider p = pkg.providers.get(i); 5789 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5790 p.info.processName, pkg.applicationInfo.uid); 5791 mProviders.addProvider(p); 5792 p.syncable = p.info.isSyncable; 5793 if (p.info.authority != null) { 5794 String names[] = p.info.authority.split(";"); 5795 p.info.authority = null; 5796 for (int j = 0; j < names.length; j++) { 5797 if (j == 1 && p.syncable) { 5798 // We only want the first authority for a provider to possibly be 5799 // syncable, so if we already added this provider using a different 5800 // authority clear the syncable flag. We copy the provider before 5801 // changing it because the mProviders object contains a reference 5802 // to a provider that we don't want to change. 5803 // Only do this for the second authority since the resulting provider 5804 // object can be the same for all future authorities for this provider. 5805 p = new PackageParser.Provider(p); 5806 p.syncable = false; 5807 } 5808 if (!mProvidersByAuthority.containsKey(names[j])) { 5809 mProvidersByAuthority.put(names[j], p); 5810 if (p.info.authority == null) { 5811 p.info.authority = names[j]; 5812 } else { 5813 p.info.authority = p.info.authority + ";" + names[j]; 5814 } 5815 if (DEBUG_PACKAGE_SCANNING) { 5816 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5817 Log.d(TAG, "Registered content provider: " + names[j] 5818 + ", className = " + p.info.name + ", isSyncable = " 5819 + p.info.isSyncable); 5820 } 5821 } else { 5822 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5823 Slog.w(TAG, "Skipping provider name " + names[j] + 5824 " (in package " + pkg.applicationInfo.packageName + 5825 "): name already used by " 5826 + ((other != null && other.getComponentName() != null) 5827 ? other.getComponentName().getPackageName() : "?")); 5828 } 5829 } 5830 } 5831 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5832 if (r == null) { 5833 r = new StringBuilder(256); 5834 } else { 5835 r.append(' '); 5836 } 5837 r.append(p.info.name); 5838 } 5839 } 5840 if (r != null) { 5841 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5842 } 5843 5844 N = pkg.services.size(); 5845 r = null; 5846 for (i=0; i<N; i++) { 5847 PackageParser.Service s = pkg.services.get(i); 5848 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5849 s.info.processName, pkg.applicationInfo.uid); 5850 mServices.addService(s); 5851 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5852 if (r == null) { 5853 r = new StringBuilder(256); 5854 } else { 5855 r.append(' '); 5856 } 5857 r.append(s.info.name); 5858 } 5859 } 5860 if (r != null) { 5861 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5862 } 5863 5864 N = pkg.receivers.size(); 5865 r = null; 5866 for (i=0; i<N; i++) { 5867 PackageParser.Activity a = pkg.receivers.get(i); 5868 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5869 a.info.processName, pkg.applicationInfo.uid); 5870 mReceivers.addActivity(a, "receiver"); 5871 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5872 if (r == null) { 5873 r = new StringBuilder(256); 5874 } else { 5875 r.append(' '); 5876 } 5877 r.append(a.info.name); 5878 } 5879 } 5880 if (r != null) { 5881 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5882 } 5883 5884 N = pkg.activities.size(); 5885 r = null; 5886 for (i=0; i<N; i++) { 5887 PackageParser.Activity a = pkg.activities.get(i); 5888 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5889 a.info.processName, pkg.applicationInfo.uid); 5890 mActivities.addActivity(a, "activity"); 5891 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5892 if (r == null) { 5893 r = new StringBuilder(256); 5894 } else { 5895 r.append(' '); 5896 } 5897 r.append(a.info.name); 5898 } 5899 } 5900 if (r != null) { 5901 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5902 } 5903 5904 N = pkg.permissionGroups.size(); 5905 r = null; 5906 for (i=0; i<N; i++) { 5907 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5908 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5909 if (cur == null) { 5910 mPermissionGroups.put(pg.info.name, pg); 5911 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5912 if (r == null) { 5913 r = new StringBuilder(256); 5914 } else { 5915 r.append(' '); 5916 } 5917 r.append(pg.info.name); 5918 } 5919 } else { 5920 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5921 + pg.info.packageName + " ignored: original from " 5922 + cur.info.packageName); 5923 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5924 if (r == null) { 5925 r = new StringBuilder(256); 5926 } else { 5927 r.append(' '); 5928 } 5929 r.append("DUP:"); 5930 r.append(pg.info.name); 5931 } 5932 } 5933 } 5934 if (r != null) { 5935 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5936 } 5937 5938 N = pkg.permissions.size(); 5939 r = null; 5940 for (i=0; i<N; i++) { 5941 PackageParser.Permission p = pkg.permissions.get(i); 5942 HashMap<String, BasePermission> permissionMap = 5943 p.tree ? mSettings.mPermissionTrees 5944 : mSettings.mPermissions; 5945 p.group = mPermissionGroups.get(p.info.group); 5946 if (p.info.group == null || p.group != null) { 5947 BasePermission bp = permissionMap.get(p.info.name); 5948 if (bp == null) { 5949 bp = new BasePermission(p.info.name, p.info.packageName, 5950 BasePermission.TYPE_NORMAL); 5951 permissionMap.put(p.info.name, bp); 5952 } 5953 if (bp.perm == null) { 5954 if (bp.sourcePackage != null 5955 && !bp.sourcePackage.equals(p.info.packageName)) { 5956 // If this is a permission that was formerly defined by a non-system 5957 // app, but is now defined by a system app (following an upgrade), 5958 // discard the previous declaration and consider the system's to be 5959 // canonical. 5960 if (isSystemApp(p.owner)) { 5961 String msg = "New decl " + p.owner + " of permission " 5962 + p.info.name + " is system"; 5963 reportSettingsProblem(Log.WARN, msg); 5964 bp.sourcePackage = null; 5965 } 5966 } 5967 if (bp.sourcePackage == null 5968 || bp.sourcePackage.equals(p.info.packageName)) { 5969 BasePermission tree = findPermissionTreeLP(p.info.name); 5970 if (tree == null 5971 || tree.sourcePackage.equals(p.info.packageName)) { 5972 bp.packageSetting = pkgSetting; 5973 bp.perm = p; 5974 bp.uid = pkg.applicationInfo.uid; 5975 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5976 if (r == null) { 5977 r = new StringBuilder(256); 5978 } else { 5979 r.append(' '); 5980 } 5981 r.append(p.info.name); 5982 } 5983 } else { 5984 Slog.w(TAG, "Permission " + p.info.name + " from package " 5985 + p.info.packageName + " ignored: base tree " 5986 + tree.name + " is from package " 5987 + tree.sourcePackage); 5988 } 5989 } else { 5990 Slog.w(TAG, "Permission " + p.info.name + " from package " 5991 + p.info.packageName + " ignored: original from " 5992 + bp.sourcePackage); 5993 } 5994 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5995 if (r == null) { 5996 r = new StringBuilder(256); 5997 } else { 5998 r.append(' '); 5999 } 6000 r.append("DUP:"); 6001 r.append(p.info.name); 6002 } 6003 if (bp.perm == p) { 6004 bp.protectionLevel = p.info.protectionLevel; 6005 } 6006 } else { 6007 Slog.w(TAG, "Permission " + p.info.name + " from package " 6008 + p.info.packageName + " ignored: no group " 6009 + p.group); 6010 } 6011 } 6012 if (r != null) { 6013 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6014 } 6015 6016 N = pkg.instrumentation.size(); 6017 r = null; 6018 for (i=0; i<N; i++) { 6019 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6020 a.info.packageName = pkg.applicationInfo.packageName; 6021 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6022 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6023 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6024 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6025 a.info.dataDir = pkg.applicationInfo.dataDir; 6026 6027 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6028 // need other information about the application, like the ABI and what not ? 6029 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6030 mInstrumentation.put(a.getComponentName(), a); 6031 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6032 if (r == null) { 6033 r = new StringBuilder(256); 6034 } else { 6035 r.append(' '); 6036 } 6037 r.append(a.info.name); 6038 } 6039 } 6040 if (r != null) { 6041 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6042 } 6043 6044 if (pkg.protectedBroadcasts != null) { 6045 N = pkg.protectedBroadcasts.size(); 6046 for (i=0; i<N; i++) { 6047 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6048 } 6049 } 6050 6051 pkgSetting.setTimeStamp(scanFileTime); 6052 6053 // Create idmap files for pairs of (packages, overlay packages). 6054 // Note: "android", ie framework-res.apk, is handled by native layers. 6055 if (pkg.mOverlayTarget != null) { 6056 // This is an overlay package. 6057 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6058 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6059 mOverlays.put(pkg.mOverlayTarget, 6060 new HashMap<String, PackageParser.Package>()); 6061 } 6062 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6063 map.put(pkg.packageName, pkg); 6064 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6065 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6066 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6067 "scanPackageLI failed to createIdmap"); 6068 } 6069 } 6070 } else if (mOverlays.containsKey(pkg.packageName) && 6071 !pkg.packageName.equals("android")) { 6072 // This is a regular package, with one or more known overlay packages. 6073 createIdmapsForPackageLI(pkg); 6074 } 6075 } 6076 6077 return pkg; 6078 } 6079 6080 /** 6081 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6082 * i.e, so that all packages can be run inside a single process if required. 6083 * 6084 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6085 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6086 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6087 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6088 * updating a package that belongs to a shared user. 6089 * 6090 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6091 * adds unnecessary complexity. 6092 */ 6093 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6094 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6095 String requiredInstructionSet = null; 6096 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6097 requiredInstructionSet = VMRuntime.getInstructionSet( 6098 scannedPackage.applicationInfo.primaryCpuAbi); 6099 } 6100 6101 PackageSetting requirer = null; 6102 for (PackageSetting ps : packagesForUser) { 6103 // If packagesForUser contains scannedPackage, we skip it. This will happen 6104 // when scannedPackage is an update of an existing package. Without this check, 6105 // we will never be able to change the ABI of any package belonging to a shared 6106 // user, even if it's compatible with other packages. 6107 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6108 if (ps.primaryCpuAbiString == null) { 6109 continue; 6110 } 6111 6112 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6113 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6114 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6115 // this but there's not much we can do. 6116 String errorMessage = "Instruction set mismatch, " 6117 + ((requirer == null) ? "[caller]" : requirer) 6118 + " requires " + requiredInstructionSet + " whereas " + ps 6119 + " requires " + instructionSet; 6120 Slog.w(TAG, errorMessage); 6121 } 6122 6123 if (requiredInstructionSet == null) { 6124 requiredInstructionSet = instructionSet; 6125 requirer = ps; 6126 } 6127 } 6128 } 6129 6130 if (requiredInstructionSet != null) { 6131 String adjustedAbi; 6132 if (requirer != null) { 6133 // requirer != null implies that either scannedPackage was null or that scannedPackage 6134 // did not require an ABI, in which case we have to adjust scannedPackage to match 6135 // the ABI of the set (which is the same as requirer's ABI) 6136 adjustedAbi = requirer.primaryCpuAbiString; 6137 if (scannedPackage != null) { 6138 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6139 } 6140 } else { 6141 // requirer == null implies that we're updating all ABIs in the set to 6142 // match scannedPackage. 6143 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6144 } 6145 6146 for (PackageSetting ps : packagesForUser) { 6147 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6148 if (ps.primaryCpuAbiString != null) { 6149 continue; 6150 } 6151 6152 ps.primaryCpuAbiString = adjustedAbi; 6153 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6154 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6155 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6156 6157 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6158 deferDexOpt, true) == DEX_OPT_FAILED) { 6159 ps.primaryCpuAbiString = null; 6160 ps.pkg.applicationInfo.primaryCpuAbi = null; 6161 return; 6162 } else { 6163 mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet()); 6164 } 6165 } 6166 } 6167 } 6168 } 6169 } 6170 6171 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6172 synchronized (mPackages) { 6173 mResolverReplaced = true; 6174 // Set up information for custom user intent resolution activity. 6175 mResolveActivity.applicationInfo = pkg.applicationInfo; 6176 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6177 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6178 mResolveActivity.processName = null; 6179 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6180 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6181 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6182 mResolveActivity.theme = 0; 6183 mResolveActivity.exported = true; 6184 mResolveActivity.enabled = true; 6185 mResolveInfo.activityInfo = mResolveActivity; 6186 mResolveInfo.priority = 0; 6187 mResolveInfo.preferredOrder = 0; 6188 mResolveInfo.match = 0; 6189 mResolveComponentName = mCustomResolverComponentName; 6190 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6191 mResolveComponentName); 6192 } 6193 } 6194 6195 private static String calculateApkRoot(final String codePathString) { 6196 final File codePath = new File(codePathString); 6197 final File codeRoot; 6198 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6199 codeRoot = Environment.getRootDirectory(); 6200 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6201 codeRoot = Environment.getOemDirectory(); 6202 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6203 codeRoot = Environment.getVendorDirectory(); 6204 } else { 6205 // Unrecognized code path; take its top real segment as the apk root: 6206 // e.g. /something/app/blah.apk => /something 6207 try { 6208 File f = codePath.getCanonicalFile(); 6209 File parent = f.getParentFile(); // non-null because codePath is a file 6210 File tmp; 6211 while ((tmp = parent.getParentFile()) != null) { 6212 f = parent; 6213 parent = tmp; 6214 } 6215 codeRoot = f; 6216 Slog.w(TAG, "Unrecognized code path " 6217 + codePath + " - using " + codeRoot); 6218 } catch (IOException e) { 6219 // Can't canonicalize the code path -- shenanigans? 6220 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6221 return Environment.getRootDirectory().getPath(); 6222 } 6223 } 6224 return codeRoot.getPath(); 6225 } 6226 6227 /** 6228 * Derive and set the location of native libraries for the given package, 6229 * which varies depending on where and how the package was installed. 6230 */ 6231 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6232 final ApplicationInfo info = pkg.applicationInfo; 6233 final String codePath = pkg.codePath; 6234 final File codeFile = new File(codePath); 6235 // If "/system/lib64/apkname" exists, assume that is the per-package 6236 // native library directory to use; otherwise use "/system/lib/apkname". 6237 final String apkRoot = calculateApkRoot(info.sourceDir); 6238 6239 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6240 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6241 6242 6243 info.nativeLibraryRootDir = null; 6244 info.nativeLibraryRootRequiresIsa = false; 6245 info.nativeLibraryDir = null; 6246 info.secondaryNativeLibraryDir = null; 6247 6248 if (isApkFile(codeFile)) { 6249 // Monolithic install 6250 if (bundledApp) { 6251 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6252 getPrimaryInstructionSet(info)); 6253 6254 // This is a bundled system app so choose the path based on the ABI. 6255 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6256 // is just the default path. 6257 final String apkName = deriveCodePathName(codePath); 6258 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6259 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6260 apkName).getAbsolutePath(); 6261 6262 if (info.secondaryCpuAbi != null) { 6263 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6264 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6265 secondaryLibDir, apkName).getAbsolutePath(); 6266 } 6267 } else if (asecApp) { 6268 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6269 .getAbsolutePath(); 6270 } else { 6271 final String apkName = deriveCodePathName(codePath); 6272 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6273 .getAbsolutePath(); 6274 } 6275 6276 info.nativeLibraryRootRequiresIsa = false; 6277 info.nativeLibraryDir = info.nativeLibraryRootDir; 6278 } else { 6279 // Cluster install 6280 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6281 info.nativeLibraryRootRequiresIsa = true; 6282 6283 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6284 getPrimaryInstructionSet(info)).getAbsolutePath(); 6285 6286 if (info.secondaryCpuAbi != null) { 6287 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6288 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6289 } 6290 } 6291 } 6292 6293 /** 6294 * Calculate the abis and roots for a bundled app. These can uniquely 6295 * be determined from the contents of the system partition, i.e whether 6296 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6297 * of this information, and instead assume that the system was built 6298 * sensibly. 6299 */ 6300 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6301 PackageSetting pkgSetting) { 6302 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6303 6304 // If "/system/lib64/apkname" exists, assume that is the per-package 6305 // native library directory to use; otherwise use "/system/lib/apkname". 6306 final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6307 setBundledAppAbi(pkg, apkRoot, apkName); 6308 // pkgSetting might be null during rescan following uninstall of updates 6309 // to a bundled app, so accommodate that possibility. The settings in 6310 // that case will be established later from the parsed package. 6311 // 6312 // If the settings aren't null, sync them up with what we've just derived. 6313 // note that apkRoot isn't stored in the package settings. 6314 if (pkgSetting != null) { 6315 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6316 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6317 } 6318 } 6319 6320 /** 6321 * Deduces the ABI of a bundled app and sets the relevant fields on the 6322 * parsed pkg object. 6323 * 6324 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6325 * under which system libraries are installed. 6326 * @param apkName the name of the installed package. 6327 */ 6328 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6329 final File codeFile = new File(pkg.codePath); 6330 6331 final boolean has64BitLibs; 6332 final boolean has32BitLibs; 6333 if (isApkFile(codeFile)) { 6334 // Monolithic install 6335 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6336 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6337 } else { 6338 // Cluster install 6339 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6340 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6341 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6342 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6343 has64BitLibs = (new File(rootDir, isa)).exists(); 6344 } else { 6345 has64BitLibs = false; 6346 } 6347 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6348 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6349 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6350 has32BitLibs = (new File(rootDir, isa)).exists(); 6351 } else { 6352 has32BitLibs = false; 6353 } 6354 } 6355 6356 if (has64BitLibs && !has32BitLibs) { 6357 // The package has 64 bit libs, but not 32 bit libs. Its primary 6358 // ABI should be 64 bit. We can safely assume here that the bundled 6359 // native libraries correspond to the most preferred ABI in the list. 6360 6361 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6362 pkg.applicationInfo.secondaryCpuAbi = null; 6363 } else if (has32BitLibs && !has64BitLibs) { 6364 // The package has 32 bit libs but not 64 bit libs. Its primary 6365 // ABI should be 32 bit. 6366 6367 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6368 pkg.applicationInfo.secondaryCpuAbi = null; 6369 } else if (has32BitLibs && has64BitLibs) { 6370 // The application has both 64 and 32 bit bundled libraries. We check 6371 // here that the app declares multiArch support, and warn if it doesn't. 6372 // 6373 // We will be lenient here and record both ABIs. The primary will be the 6374 // ABI that's higher on the list, i.e, a device that's configured to prefer 6375 // 64 bit apps will see a 64 bit primary ABI, 6376 6377 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6378 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6379 } 6380 6381 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6382 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6383 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6384 } else { 6385 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6386 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6387 } 6388 } else { 6389 pkg.applicationInfo.primaryCpuAbi = null; 6390 pkg.applicationInfo.secondaryCpuAbi = null; 6391 } 6392 } 6393 6394 private static void createNativeLibrarySubdir(File path) throws IOException { 6395 if (!path.isDirectory()) { 6396 path.delete(); 6397 6398 if (!path.mkdir()) { 6399 throw new IOException("Cannot create " + path.getPath()); 6400 } 6401 6402 try { 6403 Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6404 } catch (ErrnoException e) { 6405 throw new IOException("Cannot chmod native library directory " 6406 + path.getPath(), e); 6407 } 6408 } else if (!SELinux.restorecon(path)) { 6409 throw new IOException("Cannot set SELinux context for " + path.getPath()); 6410 } 6411 } 6412 6413 private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle, 6414 final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException { 6415 createNativeLibrarySubdir(nativeLibraryRoot); 6416 6417 /* 6418 * If this is an internal application or our nativeLibraryPath points to 6419 * the app-lib directory, unpack the libraries if necessary. 6420 */ 6421 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6422 if (abi >= 0) { 6423 /* 6424 * If we have a matching instruction set, construct a subdir under the native 6425 * library root that corresponds to this instruction set. 6426 */ 6427 final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]); 6428 final File subDir; 6429 if (useIsaSubdir) { 6430 final File isaSubdir = new File(nativeLibraryRoot, instructionSet); 6431 createNativeLibrarySubdir(isaSubdir); 6432 subDir = isaSubdir; 6433 } else { 6434 subDir = nativeLibraryRoot; 6435 } 6436 6437 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, subDir, abiList[abi]); 6438 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6439 return copyRet; 6440 } 6441 } 6442 6443 return abi; 6444 } 6445 6446 private void killApplication(String pkgName, int appId, String reason) { 6447 // Request the ActivityManager to kill the process(only for existing packages) 6448 // so that we do not end up in a confused state while the user is still using the older 6449 // version of the application while the new one gets installed. 6450 IActivityManager am = ActivityManagerNative.getDefault(); 6451 if (am != null) { 6452 try { 6453 am.killApplicationWithAppId(pkgName, appId, reason); 6454 } catch (RemoteException e) { 6455 } 6456 } 6457 } 6458 6459 void removePackageLI(PackageSetting ps, boolean chatty) { 6460 if (DEBUG_INSTALL) { 6461 if (chatty) 6462 Log.d(TAG, "Removing package " + ps.name); 6463 } 6464 6465 // writer 6466 synchronized (mPackages) { 6467 mPackages.remove(ps.name); 6468 if (ps.codePathString != null) { 6469 mAppDirs.remove(ps.codePathString); 6470 } 6471 6472 final PackageParser.Package pkg = ps.pkg; 6473 if (pkg != null) { 6474 cleanPackageDataStructuresLILPw(pkg, chatty); 6475 } 6476 } 6477 } 6478 6479 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6480 if (DEBUG_INSTALL) { 6481 if (chatty) 6482 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6483 } 6484 6485 // writer 6486 synchronized (mPackages) { 6487 mPackages.remove(pkg.applicationInfo.packageName); 6488 if (pkg.codePath != null) { 6489 mAppDirs.remove(pkg.codePath); 6490 } 6491 cleanPackageDataStructuresLILPw(pkg, chatty); 6492 } 6493 } 6494 6495 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6496 int N = pkg.providers.size(); 6497 StringBuilder r = null; 6498 int i; 6499 for (i=0; i<N; i++) { 6500 PackageParser.Provider p = pkg.providers.get(i); 6501 mProviders.removeProvider(p); 6502 if (p.info.authority == null) { 6503 6504 /* There was another ContentProvider with this authority when 6505 * this app was installed so this authority is null, 6506 * Ignore it as we don't have to unregister the provider. 6507 */ 6508 continue; 6509 } 6510 String names[] = p.info.authority.split(";"); 6511 for (int j = 0; j < names.length; j++) { 6512 if (mProvidersByAuthority.get(names[j]) == p) { 6513 mProvidersByAuthority.remove(names[j]); 6514 if (DEBUG_REMOVE) { 6515 if (chatty) 6516 Log.d(TAG, "Unregistered content provider: " + names[j] 6517 + ", className = " + p.info.name + ", isSyncable = " 6518 + p.info.isSyncable); 6519 } 6520 } 6521 } 6522 if (DEBUG_REMOVE && chatty) { 6523 if (r == null) { 6524 r = new StringBuilder(256); 6525 } else { 6526 r.append(' '); 6527 } 6528 r.append(p.info.name); 6529 } 6530 } 6531 if (r != null) { 6532 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6533 } 6534 6535 N = pkg.services.size(); 6536 r = null; 6537 for (i=0; i<N; i++) { 6538 PackageParser.Service s = pkg.services.get(i); 6539 mServices.removeService(s); 6540 if (chatty) { 6541 if (r == null) { 6542 r = new StringBuilder(256); 6543 } else { 6544 r.append(' '); 6545 } 6546 r.append(s.info.name); 6547 } 6548 } 6549 if (r != null) { 6550 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6551 } 6552 6553 N = pkg.receivers.size(); 6554 r = null; 6555 for (i=0; i<N; i++) { 6556 PackageParser.Activity a = pkg.receivers.get(i); 6557 mReceivers.removeActivity(a, "receiver"); 6558 if (DEBUG_REMOVE && chatty) { 6559 if (r == null) { 6560 r = new StringBuilder(256); 6561 } else { 6562 r.append(' '); 6563 } 6564 r.append(a.info.name); 6565 } 6566 } 6567 if (r != null) { 6568 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6569 } 6570 6571 N = pkg.activities.size(); 6572 r = null; 6573 for (i=0; i<N; i++) { 6574 PackageParser.Activity a = pkg.activities.get(i); 6575 mActivities.removeActivity(a, "activity"); 6576 if (DEBUG_REMOVE && chatty) { 6577 if (r == null) { 6578 r = new StringBuilder(256); 6579 } else { 6580 r.append(' '); 6581 } 6582 r.append(a.info.name); 6583 } 6584 } 6585 if (r != null) { 6586 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6587 } 6588 6589 N = pkg.permissions.size(); 6590 r = null; 6591 for (i=0; i<N; i++) { 6592 PackageParser.Permission p = pkg.permissions.get(i); 6593 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6594 if (bp == null) { 6595 bp = mSettings.mPermissionTrees.get(p.info.name); 6596 } 6597 if (bp != null && bp.perm == p) { 6598 bp.perm = null; 6599 if (DEBUG_REMOVE && chatty) { 6600 if (r == null) { 6601 r = new StringBuilder(256); 6602 } else { 6603 r.append(' '); 6604 } 6605 r.append(p.info.name); 6606 } 6607 } 6608 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6609 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6610 if (appOpPerms != null) { 6611 appOpPerms.remove(pkg.packageName); 6612 } 6613 } 6614 } 6615 if (r != null) { 6616 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6617 } 6618 6619 N = pkg.requestedPermissions.size(); 6620 r = null; 6621 for (i=0; i<N; i++) { 6622 String perm = pkg.requestedPermissions.get(i); 6623 BasePermission bp = mSettings.mPermissions.get(perm); 6624 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6625 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6626 if (appOpPerms != null) { 6627 appOpPerms.remove(pkg.packageName); 6628 if (appOpPerms.isEmpty()) { 6629 mAppOpPermissionPackages.remove(perm); 6630 } 6631 } 6632 } 6633 } 6634 if (r != null) { 6635 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6636 } 6637 6638 N = pkg.instrumentation.size(); 6639 r = null; 6640 for (i=0; i<N; i++) { 6641 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6642 mInstrumentation.remove(a.getComponentName()); 6643 if (DEBUG_REMOVE && chatty) { 6644 if (r == null) { 6645 r = new StringBuilder(256); 6646 } else { 6647 r.append(' '); 6648 } 6649 r.append(a.info.name); 6650 } 6651 } 6652 if (r != null) { 6653 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6654 } 6655 6656 r = null; 6657 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6658 // Only system apps can hold shared libraries. 6659 if (pkg.libraryNames != null) { 6660 for (i=0; i<pkg.libraryNames.size(); i++) { 6661 String name = pkg.libraryNames.get(i); 6662 SharedLibraryEntry cur = mSharedLibraries.get(name); 6663 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6664 mSharedLibraries.remove(name); 6665 if (DEBUG_REMOVE && chatty) { 6666 if (r == null) { 6667 r = new StringBuilder(256); 6668 } else { 6669 r.append(' '); 6670 } 6671 r.append(name); 6672 } 6673 } 6674 } 6675 } 6676 } 6677 if (r != null) { 6678 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6679 } 6680 } 6681 6682 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6683 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6684 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6685 return true; 6686 } 6687 } 6688 return false; 6689 } 6690 6691 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6692 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6693 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6694 6695 private void updatePermissionsLPw(String changingPkg, 6696 PackageParser.Package pkgInfo, int flags) { 6697 // Make sure there are no dangling permission trees. 6698 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6699 while (it.hasNext()) { 6700 final BasePermission bp = it.next(); 6701 if (bp.packageSetting == null) { 6702 // We may not yet have parsed the package, so just see if 6703 // we still know about its settings. 6704 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6705 } 6706 if (bp.packageSetting == null) { 6707 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6708 + " from package " + bp.sourcePackage); 6709 it.remove(); 6710 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6711 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6712 Slog.i(TAG, "Removing old permission tree: " + bp.name 6713 + " from package " + bp.sourcePackage); 6714 flags |= UPDATE_PERMISSIONS_ALL; 6715 it.remove(); 6716 } 6717 } 6718 } 6719 6720 // Make sure all dynamic permissions have been assigned to a package, 6721 // and make sure there are no dangling permissions. 6722 it = mSettings.mPermissions.values().iterator(); 6723 while (it.hasNext()) { 6724 final BasePermission bp = it.next(); 6725 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6726 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6727 + bp.name + " pkg=" + bp.sourcePackage 6728 + " info=" + bp.pendingInfo); 6729 if (bp.packageSetting == null && bp.pendingInfo != null) { 6730 final BasePermission tree = findPermissionTreeLP(bp.name); 6731 if (tree != null && tree.perm != null) { 6732 bp.packageSetting = tree.packageSetting; 6733 bp.perm = new PackageParser.Permission(tree.perm.owner, 6734 new PermissionInfo(bp.pendingInfo)); 6735 bp.perm.info.packageName = tree.perm.info.packageName; 6736 bp.perm.info.name = bp.name; 6737 bp.uid = tree.uid; 6738 } 6739 } 6740 } 6741 if (bp.packageSetting == null) { 6742 // We may not yet have parsed the package, so just see if 6743 // we still know about its settings. 6744 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6745 } 6746 if (bp.packageSetting == null) { 6747 Slog.w(TAG, "Removing dangling permission: " + bp.name 6748 + " from package " + bp.sourcePackage); 6749 it.remove(); 6750 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6751 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6752 Slog.i(TAG, "Removing old permission: " + bp.name 6753 + " from package " + bp.sourcePackage); 6754 flags |= UPDATE_PERMISSIONS_ALL; 6755 it.remove(); 6756 } 6757 } 6758 } 6759 6760 // Now update the permissions for all packages, in particular 6761 // replace the granted permissions of the system packages. 6762 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6763 for (PackageParser.Package pkg : mPackages.values()) { 6764 if (pkg != pkgInfo) { 6765 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6766 } 6767 } 6768 } 6769 6770 if (pkgInfo != null) { 6771 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6772 } 6773 } 6774 6775 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6776 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6777 if (ps == null) { 6778 return; 6779 } 6780 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6781 HashSet<String> origPermissions = gp.grantedPermissions; 6782 boolean changedPermission = false; 6783 6784 if (replace) { 6785 ps.permissionsFixed = false; 6786 if (gp == ps) { 6787 origPermissions = new HashSet<String>(gp.grantedPermissions); 6788 gp.grantedPermissions.clear(); 6789 gp.gids = mGlobalGids; 6790 } 6791 } 6792 6793 if (gp.gids == null) { 6794 gp.gids = mGlobalGids; 6795 } 6796 6797 final int N = pkg.requestedPermissions.size(); 6798 for (int i=0; i<N; i++) { 6799 final String name = pkg.requestedPermissions.get(i); 6800 final boolean required = pkg.requestedPermissionsRequired.get(i); 6801 final BasePermission bp = mSettings.mPermissions.get(name); 6802 if (DEBUG_INSTALL) { 6803 if (gp != ps) { 6804 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6805 } 6806 } 6807 6808 if (bp == null || bp.packageSetting == null) { 6809 Slog.w(TAG, "Unknown permission " + name 6810 + " in package " + pkg.packageName); 6811 continue; 6812 } 6813 6814 final String perm = bp.name; 6815 boolean allowed; 6816 boolean allowedSig = false; 6817 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6818 // Keep track of app op permissions. 6819 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6820 if (pkgs == null) { 6821 pkgs = new ArraySet<>(); 6822 mAppOpPermissionPackages.put(bp.name, pkgs); 6823 } 6824 pkgs.add(pkg.packageName); 6825 } 6826 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6827 if (level == PermissionInfo.PROTECTION_NORMAL 6828 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6829 // We grant a normal or dangerous permission if any of the following 6830 // are true: 6831 // 1) The permission is required 6832 // 2) The permission is optional, but was granted in the past 6833 // 3) The permission is optional, but was requested by an 6834 // app in /system (not /data) 6835 // 6836 // Otherwise, reject the permission. 6837 allowed = (required || origPermissions.contains(perm) 6838 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6839 } else if (bp.packageSetting == null) { 6840 // This permission is invalid; skip it. 6841 allowed = false; 6842 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6843 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6844 if (allowed) { 6845 allowedSig = true; 6846 } 6847 } else { 6848 allowed = false; 6849 } 6850 if (DEBUG_INSTALL) { 6851 if (gp != ps) { 6852 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6853 } 6854 } 6855 if (allowed) { 6856 if (!isSystemApp(ps) && ps.permissionsFixed) { 6857 // If this is an existing, non-system package, then 6858 // we can't add any new permissions to it. 6859 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6860 // Except... if this is a permission that was added 6861 // to the platform (note: need to only do this when 6862 // updating the platform). 6863 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6864 } 6865 } 6866 if (allowed) { 6867 if (!gp.grantedPermissions.contains(perm)) { 6868 changedPermission = true; 6869 gp.grantedPermissions.add(perm); 6870 gp.gids = appendInts(gp.gids, bp.gids); 6871 } else if (!ps.haveGids) { 6872 gp.gids = appendInts(gp.gids, bp.gids); 6873 } 6874 } else { 6875 Slog.w(TAG, "Not granting permission " + perm 6876 + " to package " + pkg.packageName 6877 + " because it was previously installed without"); 6878 } 6879 } else { 6880 if (gp.grantedPermissions.remove(perm)) { 6881 changedPermission = true; 6882 gp.gids = removeInts(gp.gids, bp.gids); 6883 Slog.i(TAG, "Un-granting permission " + perm 6884 + " from package " + pkg.packageName 6885 + " (protectionLevel=" + bp.protectionLevel 6886 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6887 + ")"); 6888 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6889 // Don't print warning for app op permissions, since it is fine for them 6890 // not to be granted, there is a UI for the user to decide. 6891 Slog.w(TAG, "Not granting permission " + perm 6892 + " to package " + pkg.packageName 6893 + " (protectionLevel=" + bp.protectionLevel 6894 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6895 + ")"); 6896 } 6897 } 6898 } 6899 6900 if ((changedPermission || replace) && !ps.permissionsFixed && 6901 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6902 // This is the first that we have heard about this package, so the 6903 // permissions we have now selected are fixed until explicitly 6904 // changed. 6905 ps.permissionsFixed = true; 6906 } 6907 ps.haveGids = true; 6908 } 6909 6910 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6911 boolean allowed = false; 6912 final int NP = PackageParser.NEW_PERMISSIONS.length; 6913 for (int ip=0; ip<NP; ip++) { 6914 final PackageParser.NewPermissionInfo npi 6915 = PackageParser.NEW_PERMISSIONS[ip]; 6916 if (npi.name.equals(perm) 6917 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6918 allowed = true; 6919 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6920 + pkg.packageName); 6921 break; 6922 } 6923 } 6924 return allowed; 6925 } 6926 6927 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6928 BasePermission bp, HashSet<String> origPermissions) { 6929 boolean allowed; 6930 allowed = (compareSignatures( 6931 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6932 == PackageManager.SIGNATURE_MATCH) 6933 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6934 == PackageManager.SIGNATURE_MATCH); 6935 if (!allowed && (bp.protectionLevel 6936 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6937 if (isSystemApp(pkg)) { 6938 // For updated system applications, a system permission 6939 // is granted only if it had been defined by the original application. 6940 if (isUpdatedSystemApp(pkg)) { 6941 final PackageSetting sysPs = mSettings 6942 .getDisabledSystemPkgLPr(pkg.packageName); 6943 final GrantedPermissions origGp = sysPs.sharedUser != null 6944 ? sysPs.sharedUser : sysPs; 6945 6946 if (origGp.grantedPermissions.contains(perm)) { 6947 // If the original was granted this permission, we take 6948 // that grant decision as read and propagate it to the 6949 // update. 6950 allowed = true; 6951 } else { 6952 // The system apk may have been updated with an older 6953 // version of the one on the data partition, but which 6954 // granted a new system permission that it didn't have 6955 // before. In this case we do want to allow the app to 6956 // now get the new permission if the ancestral apk is 6957 // privileged to get it. 6958 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6959 for (int j=0; 6960 j<sysPs.pkg.requestedPermissions.size(); j++) { 6961 if (perm.equals( 6962 sysPs.pkg.requestedPermissions.get(j))) { 6963 allowed = true; 6964 break; 6965 } 6966 } 6967 } 6968 } 6969 } else { 6970 allowed = isPrivilegedApp(pkg); 6971 } 6972 } 6973 } 6974 if (!allowed && (bp.protectionLevel 6975 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6976 // For development permissions, a development permission 6977 // is granted only if it was already granted. 6978 allowed = origPermissions.contains(perm); 6979 } 6980 return allowed; 6981 } 6982 6983 final class ActivityIntentResolver 6984 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6985 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6986 boolean defaultOnly, int userId) { 6987 if (!sUserManager.exists(userId)) return null; 6988 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6989 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6990 } 6991 6992 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6993 int userId) { 6994 if (!sUserManager.exists(userId)) return null; 6995 mFlags = flags; 6996 return super.queryIntent(intent, resolvedType, 6997 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6998 } 6999 7000 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7001 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7002 if (!sUserManager.exists(userId)) return null; 7003 if (packageActivities == null) { 7004 return null; 7005 } 7006 mFlags = flags; 7007 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7008 final int N = packageActivities.size(); 7009 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7010 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7011 7012 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7013 for (int i = 0; i < N; ++i) { 7014 intentFilters = packageActivities.get(i).intents; 7015 if (intentFilters != null && intentFilters.size() > 0) { 7016 PackageParser.ActivityIntentInfo[] array = 7017 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7018 intentFilters.toArray(array); 7019 listCut.add(array); 7020 } 7021 } 7022 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7023 } 7024 7025 public final void addActivity(PackageParser.Activity a, String type) { 7026 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7027 mActivities.put(a.getComponentName(), a); 7028 if (DEBUG_SHOW_INFO) 7029 Log.v( 7030 TAG, " " + type + " " + 7031 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7032 if (DEBUG_SHOW_INFO) 7033 Log.v(TAG, " Class=" + a.info.name); 7034 final int NI = a.intents.size(); 7035 for (int j=0; j<NI; j++) { 7036 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7037 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7038 intent.setPriority(0); 7039 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7040 + a.className + " with priority > 0, forcing to 0"); 7041 } 7042 if (DEBUG_SHOW_INFO) { 7043 Log.v(TAG, " IntentFilter:"); 7044 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7045 } 7046 if (!intent.debugCheck()) { 7047 Log.w(TAG, "==> For Activity " + a.info.name); 7048 } 7049 addFilter(intent); 7050 } 7051 } 7052 7053 public final void removeActivity(PackageParser.Activity a, String type) { 7054 mActivities.remove(a.getComponentName()); 7055 if (DEBUG_SHOW_INFO) { 7056 Log.v(TAG, " " + type + " " 7057 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7058 : a.info.name) + ":"); 7059 Log.v(TAG, " Class=" + a.info.name); 7060 } 7061 final int NI = a.intents.size(); 7062 for (int j=0; j<NI; j++) { 7063 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7064 if (DEBUG_SHOW_INFO) { 7065 Log.v(TAG, " IntentFilter:"); 7066 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7067 } 7068 removeFilter(intent); 7069 } 7070 } 7071 7072 @Override 7073 protected boolean allowFilterResult( 7074 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7075 ActivityInfo filterAi = filter.activity.info; 7076 for (int i=dest.size()-1; i>=0; i--) { 7077 ActivityInfo destAi = dest.get(i).activityInfo; 7078 if (destAi.name == filterAi.name 7079 && destAi.packageName == filterAi.packageName) { 7080 return false; 7081 } 7082 } 7083 return true; 7084 } 7085 7086 @Override 7087 protected ActivityIntentInfo[] newArray(int size) { 7088 return new ActivityIntentInfo[size]; 7089 } 7090 7091 @Override 7092 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7093 if (!sUserManager.exists(userId)) return true; 7094 PackageParser.Package p = filter.activity.owner; 7095 if (p != null) { 7096 PackageSetting ps = (PackageSetting)p.mExtras; 7097 if (ps != null) { 7098 // System apps are never considered stopped for purposes of 7099 // filtering, because there may be no way for the user to 7100 // actually re-launch them. 7101 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7102 && ps.getStopped(userId); 7103 } 7104 } 7105 return false; 7106 } 7107 7108 @Override 7109 protected boolean isPackageForFilter(String packageName, 7110 PackageParser.ActivityIntentInfo info) { 7111 return packageName.equals(info.activity.owner.packageName); 7112 } 7113 7114 @Override 7115 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7116 int match, int userId) { 7117 if (!sUserManager.exists(userId)) return null; 7118 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7119 return null; 7120 } 7121 final PackageParser.Activity activity = info.activity; 7122 if (mSafeMode && (activity.info.applicationInfo.flags 7123 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7124 return null; 7125 } 7126 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7127 if (ps == null) { 7128 return null; 7129 } 7130 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7131 ps.readUserState(userId), userId); 7132 if (ai == null) { 7133 return null; 7134 } 7135 final ResolveInfo res = new ResolveInfo(); 7136 res.activityInfo = ai; 7137 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7138 res.filter = info; 7139 } 7140 res.priority = info.getPriority(); 7141 res.preferredOrder = activity.owner.mPreferredOrder; 7142 //System.out.println("Result: " + res.activityInfo.className + 7143 // " = " + res.priority); 7144 res.match = match; 7145 res.isDefault = info.hasDefault; 7146 res.labelRes = info.labelRes; 7147 res.nonLocalizedLabel = info.nonLocalizedLabel; 7148 if (userNeedsBadging(userId)) { 7149 res.noResourceId = true; 7150 } else { 7151 res.icon = info.icon; 7152 } 7153 res.system = isSystemApp(res.activityInfo.applicationInfo); 7154 return res; 7155 } 7156 7157 @Override 7158 protected void sortResults(List<ResolveInfo> results) { 7159 Collections.sort(results, mResolvePrioritySorter); 7160 } 7161 7162 @Override 7163 protected void dumpFilter(PrintWriter out, String prefix, 7164 PackageParser.ActivityIntentInfo filter) { 7165 out.print(prefix); out.print( 7166 Integer.toHexString(System.identityHashCode(filter.activity))); 7167 out.print(' '); 7168 filter.activity.printComponentShortName(out); 7169 out.print(" filter "); 7170 out.println(Integer.toHexString(System.identityHashCode(filter))); 7171 } 7172 7173// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7174// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7175// final List<ResolveInfo> retList = Lists.newArrayList(); 7176// while (i.hasNext()) { 7177// final ResolveInfo resolveInfo = i.next(); 7178// if (isEnabledLP(resolveInfo.activityInfo)) { 7179// retList.add(resolveInfo); 7180// } 7181// } 7182// return retList; 7183// } 7184 7185 // Keys are String (activity class name), values are Activity. 7186 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7187 = new HashMap<ComponentName, PackageParser.Activity>(); 7188 private int mFlags; 7189 } 7190 7191 private final class ServiceIntentResolver 7192 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7193 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7194 boolean defaultOnly, int userId) { 7195 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7196 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7197 } 7198 7199 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7200 int userId) { 7201 if (!sUserManager.exists(userId)) return null; 7202 mFlags = flags; 7203 return super.queryIntent(intent, resolvedType, 7204 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7205 } 7206 7207 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7208 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7209 if (!sUserManager.exists(userId)) return null; 7210 if (packageServices == null) { 7211 return null; 7212 } 7213 mFlags = flags; 7214 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7215 final int N = packageServices.size(); 7216 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7217 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7218 7219 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7220 for (int i = 0; i < N; ++i) { 7221 intentFilters = packageServices.get(i).intents; 7222 if (intentFilters != null && intentFilters.size() > 0) { 7223 PackageParser.ServiceIntentInfo[] array = 7224 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7225 intentFilters.toArray(array); 7226 listCut.add(array); 7227 } 7228 } 7229 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7230 } 7231 7232 public final void addService(PackageParser.Service s) { 7233 mServices.put(s.getComponentName(), s); 7234 if (DEBUG_SHOW_INFO) { 7235 Log.v(TAG, " " 7236 + (s.info.nonLocalizedLabel != null 7237 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7238 Log.v(TAG, " Class=" + s.info.name); 7239 } 7240 final int NI = s.intents.size(); 7241 int j; 7242 for (j=0; j<NI; j++) { 7243 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7244 if (DEBUG_SHOW_INFO) { 7245 Log.v(TAG, " IntentFilter:"); 7246 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7247 } 7248 if (!intent.debugCheck()) { 7249 Log.w(TAG, "==> For Service " + s.info.name); 7250 } 7251 addFilter(intent); 7252 } 7253 } 7254 7255 public final void removeService(PackageParser.Service s) { 7256 mServices.remove(s.getComponentName()); 7257 if (DEBUG_SHOW_INFO) { 7258 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7259 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7260 Log.v(TAG, " Class=" + s.info.name); 7261 } 7262 final int NI = s.intents.size(); 7263 int j; 7264 for (j=0; j<NI; j++) { 7265 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7266 if (DEBUG_SHOW_INFO) { 7267 Log.v(TAG, " IntentFilter:"); 7268 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7269 } 7270 removeFilter(intent); 7271 } 7272 } 7273 7274 @Override 7275 protected boolean allowFilterResult( 7276 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7277 ServiceInfo filterSi = filter.service.info; 7278 for (int i=dest.size()-1; i>=0; i--) { 7279 ServiceInfo destAi = dest.get(i).serviceInfo; 7280 if (destAi.name == filterSi.name 7281 && destAi.packageName == filterSi.packageName) { 7282 return false; 7283 } 7284 } 7285 return true; 7286 } 7287 7288 @Override 7289 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7290 return new PackageParser.ServiceIntentInfo[size]; 7291 } 7292 7293 @Override 7294 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7295 if (!sUserManager.exists(userId)) return true; 7296 PackageParser.Package p = filter.service.owner; 7297 if (p != null) { 7298 PackageSetting ps = (PackageSetting)p.mExtras; 7299 if (ps != null) { 7300 // System apps are never considered stopped for purposes of 7301 // filtering, because there may be no way for the user to 7302 // actually re-launch them. 7303 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7304 && ps.getStopped(userId); 7305 } 7306 } 7307 return false; 7308 } 7309 7310 @Override 7311 protected boolean isPackageForFilter(String packageName, 7312 PackageParser.ServiceIntentInfo info) { 7313 return packageName.equals(info.service.owner.packageName); 7314 } 7315 7316 @Override 7317 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7318 int match, int userId) { 7319 if (!sUserManager.exists(userId)) return null; 7320 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7321 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7322 return null; 7323 } 7324 final PackageParser.Service service = info.service; 7325 if (mSafeMode && (service.info.applicationInfo.flags 7326 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7327 return null; 7328 } 7329 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7330 if (ps == null) { 7331 return null; 7332 } 7333 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7334 ps.readUserState(userId), userId); 7335 if (si == null) { 7336 return null; 7337 } 7338 final ResolveInfo res = new ResolveInfo(); 7339 res.serviceInfo = si; 7340 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7341 res.filter = filter; 7342 } 7343 res.priority = info.getPriority(); 7344 res.preferredOrder = service.owner.mPreferredOrder; 7345 //System.out.println("Result: " + res.activityInfo.className + 7346 // " = " + res.priority); 7347 res.match = match; 7348 res.isDefault = info.hasDefault; 7349 res.labelRes = info.labelRes; 7350 res.nonLocalizedLabel = info.nonLocalizedLabel; 7351 res.icon = info.icon; 7352 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7353 return res; 7354 } 7355 7356 @Override 7357 protected void sortResults(List<ResolveInfo> results) { 7358 Collections.sort(results, mResolvePrioritySorter); 7359 } 7360 7361 @Override 7362 protected void dumpFilter(PrintWriter out, String prefix, 7363 PackageParser.ServiceIntentInfo filter) { 7364 out.print(prefix); out.print( 7365 Integer.toHexString(System.identityHashCode(filter.service))); 7366 out.print(' '); 7367 filter.service.printComponentShortName(out); 7368 out.print(" filter "); 7369 out.println(Integer.toHexString(System.identityHashCode(filter))); 7370 } 7371 7372// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7373// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7374// final List<ResolveInfo> retList = Lists.newArrayList(); 7375// while (i.hasNext()) { 7376// final ResolveInfo resolveInfo = (ResolveInfo) i; 7377// if (isEnabledLP(resolveInfo.serviceInfo)) { 7378// retList.add(resolveInfo); 7379// } 7380// } 7381// return retList; 7382// } 7383 7384 // Keys are String (activity class name), values are Activity. 7385 private final HashMap<ComponentName, PackageParser.Service> mServices 7386 = new HashMap<ComponentName, PackageParser.Service>(); 7387 private int mFlags; 7388 }; 7389 7390 private final class ProviderIntentResolver 7391 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7392 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7393 boolean defaultOnly, int userId) { 7394 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7395 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7396 } 7397 7398 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7399 int userId) { 7400 if (!sUserManager.exists(userId)) 7401 return null; 7402 mFlags = flags; 7403 return super.queryIntent(intent, resolvedType, 7404 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7405 } 7406 7407 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7408 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7409 if (!sUserManager.exists(userId)) 7410 return null; 7411 if (packageProviders == null) { 7412 return null; 7413 } 7414 mFlags = flags; 7415 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7416 final int N = packageProviders.size(); 7417 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7418 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7419 7420 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7421 for (int i = 0; i < N; ++i) { 7422 intentFilters = packageProviders.get(i).intents; 7423 if (intentFilters != null && intentFilters.size() > 0) { 7424 PackageParser.ProviderIntentInfo[] array = 7425 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7426 intentFilters.toArray(array); 7427 listCut.add(array); 7428 } 7429 } 7430 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7431 } 7432 7433 public final void addProvider(PackageParser.Provider p) { 7434 if (mProviders.containsKey(p.getComponentName())) { 7435 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7436 return; 7437 } 7438 7439 mProviders.put(p.getComponentName(), p); 7440 if (DEBUG_SHOW_INFO) { 7441 Log.v(TAG, " " 7442 + (p.info.nonLocalizedLabel != null 7443 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7444 Log.v(TAG, " Class=" + p.info.name); 7445 } 7446 final int NI = p.intents.size(); 7447 int j; 7448 for (j = 0; j < NI; j++) { 7449 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7450 if (DEBUG_SHOW_INFO) { 7451 Log.v(TAG, " IntentFilter:"); 7452 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7453 } 7454 if (!intent.debugCheck()) { 7455 Log.w(TAG, "==> For Provider " + p.info.name); 7456 } 7457 addFilter(intent); 7458 } 7459 } 7460 7461 public final void removeProvider(PackageParser.Provider p) { 7462 mProviders.remove(p.getComponentName()); 7463 if (DEBUG_SHOW_INFO) { 7464 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7465 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7466 Log.v(TAG, " Class=" + p.info.name); 7467 } 7468 final int NI = p.intents.size(); 7469 int j; 7470 for (j = 0; j < NI; j++) { 7471 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7472 if (DEBUG_SHOW_INFO) { 7473 Log.v(TAG, " IntentFilter:"); 7474 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7475 } 7476 removeFilter(intent); 7477 } 7478 } 7479 7480 @Override 7481 protected boolean allowFilterResult( 7482 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7483 ProviderInfo filterPi = filter.provider.info; 7484 for (int i = dest.size() - 1; i >= 0; i--) { 7485 ProviderInfo destPi = dest.get(i).providerInfo; 7486 if (destPi.name == filterPi.name 7487 && destPi.packageName == filterPi.packageName) { 7488 return false; 7489 } 7490 } 7491 return true; 7492 } 7493 7494 @Override 7495 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7496 return new PackageParser.ProviderIntentInfo[size]; 7497 } 7498 7499 @Override 7500 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7501 if (!sUserManager.exists(userId)) 7502 return true; 7503 PackageParser.Package p = filter.provider.owner; 7504 if (p != null) { 7505 PackageSetting ps = (PackageSetting) p.mExtras; 7506 if (ps != null) { 7507 // System apps are never considered stopped for purposes of 7508 // filtering, because there may be no way for the user to 7509 // actually re-launch them. 7510 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7511 && ps.getStopped(userId); 7512 } 7513 } 7514 return false; 7515 } 7516 7517 @Override 7518 protected boolean isPackageForFilter(String packageName, 7519 PackageParser.ProviderIntentInfo info) { 7520 return packageName.equals(info.provider.owner.packageName); 7521 } 7522 7523 @Override 7524 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7525 int match, int userId) { 7526 if (!sUserManager.exists(userId)) 7527 return null; 7528 final PackageParser.ProviderIntentInfo info = filter; 7529 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7530 return null; 7531 } 7532 final PackageParser.Provider provider = info.provider; 7533 if (mSafeMode && (provider.info.applicationInfo.flags 7534 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7535 return null; 7536 } 7537 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7538 if (ps == null) { 7539 return null; 7540 } 7541 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7542 ps.readUserState(userId), userId); 7543 if (pi == null) { 7544 return null; 7545 } 7546 final ResolveInfo res = new ResolveInfo(); 7547 res.providerInfo = pi; 7548 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7549 res.filter = filter; 7550 } 7551 res.priority = info.getPriority(); 7552 res.preferredOrder = provider.owner.mPreferredOrder; 7553 res.match = match; 7554 res.isDefault = info.hasDefault; 7555 res.labelRes = info.labelRes; 7556 res.nonLocalizedLabel = info.nonLocalizedLabel; 7557 res.icon = info.icon; 7558 res.system = isSystemApp(res.providerInfo.applicationInfo); 7559 return res; 7560 } 7561 7562 @Override 7563 protected void sortResults(List<ResolveInfo> results) { 7564 Collections.sort(results, mResolvePrioritySorter); 7565 } 7566 7567 @Override 7568 protected void dumpFilter(PrintWriter out, String prefix, 7569 PackageParser.ProviderIntentInfo filter) { 7570 out.print(prefix); 7571 out.print( 7572 Integer.toHexString(System.identityHashCode(filter.provider))); 7573 out.print(' '); 7574 filter.provider.printComponentShortName(out); 7575 out.print(" filter "); 7576 out.println(Integer.toHexString(System.identityHashCode(filter))); 7577 } 7578 7579 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7580 = new HashMap<ComponentName, PackageParser.Provider>(); 7581 private int mFlags; 7582 }; 7583 7584 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7585 new Comparator<ResolveInfo>() { 7586 public int compare(ResolveInfo r1, ResolveInfo r2) { 7587 int v1 = r1.priority; 7588 int v2 = r2.priority; 7589 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7590 if (v1 != v2) { 7591 return (v1 > v2) ? -1 : 1; 7592 } 7593 v1 = r1.preferredOrder; 7594 v2 = r2.preferredOrder; 7595 if (v1 != v2) { 7596 return (v1 > v2) ? -1 : 1; 7597 } 7598 if (r1.isDefault != r2.isDefault) { 7599 return r1.isDefault ? -1 : 1; 7600 } 7601 v1 = r1.match; 7602 v2 = r2.match; 7603 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7604 if (v1 != v2) { 7605 return (v1 > v2) ? -1 : 1; 7606 } 7607 if (r1.system != r2.system) { 7608 return r1.system ? -1 : 1; 7609 } 7610 return 0; 7611 } 7612 }; 7613 7614 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7615 new Comparator<ProviderInfo>() { 7616 public int compare(ProviderInfo p1, ProviderInfo p2) { 7617 final int v1 = p1.initOrder; 7618 final int v2 = p2.initOrder; 7619 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7620 } 7621 }; 7622 7623 static final void sendPackageBroadcast(String action, String pkg, 7624 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7625 int[] userIds) { 7626 IActivityManager am = ActivityManagerNative.getDefault(); 7627 if (am != null) { 7628 try { 7629 if (userIds == null) { 7630 userIds = am.getRunningUserIds(); 7631 } 7632 for (int id : userIds) { 7633 final Intent intent = new Intent(action, 7634 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7635 if (extras != null) { 7636 intent.putExtras(extras); 7637 } 7638 if (targetPkg != null) { 7639 intent.setPackage(targetPkg); 7640 } 7641 // Modify the UID when posting to other users 7642 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7643 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7644 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7645 intent.putExtra(Intent.EXTRA_UID, uid); 7646 } 7647 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7648 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7649 if (DEBUG_BROADCASTS) { 7650 RuntimeException here = new RuntimeException("here"); 7651 here.fillInStackTrace(); 7652 Slog.d(TAG, "Sending to user " + id + ": " 7653 + intent.toShortString(false, true, false, false) 7654 + " " + intent.getExtras(), here); 7655 } 7656 am.broadcastIntent(null, intent, null, finishedReceiver, 7657 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7658 finishedReceiver != null, false, id); 7659 } 7660 } catch (RemoteException ex) { 7661 } 7662 } 7663 } 7664 7665 /** 7666 * Check if the external storage media is available. This is true if there 7667 * is a mounted external storage medium or if the external storage is 7668 * emulated. 7669 */ 7670 private boolean isExternalMediaAvailable() { 7671 return mMediaMounted || Environment.isExternalStorageEmulated(); 7672 } 7673 7674 @Override 7675 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7676 // writer 7677 synchronized (mPackages) { 7678 if (!isExternalMediaAvailable()) { 7679 // If the external storage is no longer mounted at this point, 7680 // the caller may not have been able to delete all of this 7681 // packages files and can not delete any more. Bail. 7682 return null; 7683 } 7684 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7685 if (lastPackage != null) { 7686 pkgs.remove(lastPackage); 7687 } 7688 if (pkgs.size() > 0) { 7689 return pkgs.get(0); 7690 } 7691 } 7692 return null; 7693 } 7694 7695 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7696 if (false) { 7697 RuntimeException here = new RuntimeException("here"); 7698 here.fillInStackTrace(); 7699 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7700 + " andCode=" + andCode, here); 7701 } 7702 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7703 userId, andCode ? 1 : 0, packageName)); 7704 } 7705 7706 void startCleaningPackages() { 7707 // reader 7708 synchronized (mPackages) { 7709 if (!isExternalMediaAvailable()) { 7710 return; 7711 } 7712 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7713 return; 7714 } 7715 } 7716 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7717 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7718 IActivityManager am = ActivityManagerNative.getDefault(); 7719 if (am != null) { 7720 try { 7721 am.startService(null, intent, null, UserHandle.USER_OWNER); 7722 } catch (RemoteException e) { 7723 } 7724 } 7725 } 7726 7727 private final class AppDirObserver extends FileObserver { 7728 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 7729 super(path, mask); 7730 mRootDir = path; 7731 mIsRom = isrom; 7732 mIsPrivileged = isPrivileged; 7733 } 7734 7735 public void onEvent(int event, String path) { 7736 String removedPackage = null; 7737 int removedAppId = -1; 7738 int[] removedUsers = null; 7739 String addedPackage = null; 7740 int addedAppId = -1; 7741 int[] addedUsers = null; 7742 7743 // TODO post a message to the handler to obtain serial ordering 7744 synchronized (mInstallLock) { 7745 String fullPathStr = null; 7746 File fullPath = null; 7747 if (path != null) { 7748 fullPath = new File(mRootDir, path); 7749 fullPathStr = fullPath.getPath(); 7750 } 7751 7752 if (DEBUG_APP_DIR_OBSERVER) 7753 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 7754 7755 if (!isApkFile(fullPath)) { 7756 if (DEBUG_APP_DIR_OBSERVER) 7757 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 7758 return; 7759 } 7760 7761 // Ignore packages that are being installed or 7762 // have just been installed. 7763 if (ignoreCodePath(fullPathStr)) { 7764 return; 7765 } 7766 PackageParser.Package p = null; 7767 PackageSetting ps = null; 7768 // reader 7769 synchronized (mPackages) { 7770 p = mAppDirs.get(fullPathStr); 7771 if (p != null) { 7772 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 7773 if (ps != null) { 7774 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7775 } else { 7776 removedUsers = sUserManager.getUserIds(); 7777 } 7778 } 7779 addedUsers = sUserManager.getUserIds(); 7780 } 7781 if ((event&REMOVE_EVENTS) != 0) { 7782 if (ps != null) { 7783 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 7784 removePackageLI(ps, true); 7785 removedPackage = ps.name; 7786 removedAppId = ps.appId; 7787 } 7788 } 7789 7790 if ((event&ADD_EVENTS) != 0) { 7791 if (p == null) { 7792 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 7793 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 7794 if (mIsRom) { 7795 flags |= PackageParser.PARSE_IS_SYSTEM 7796 | PackageParser.PARSE_IS_SYSTEM_DIR; 7797 if (mIsPrivileged) { 7798 flags |= PackageParser.PARSE_IS_PRIVILEGED; 7799 } 7800 } 7801 try { 7802 p = scanPackageLI(fullPath, flags, 7803 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 7804 System.currentTimeMillis(), UserHandle.ALL, null); 7805 } catch (PackageManagerException e) { 7806 Slog.w(TAG, "Failed to scan " + fullPath + ": " + e.getMessage()); 7807 p = null; 7808 } 7809 if (p != null) { 7810 /* 7811 * TODO this seems dangerous as the package may have 7812 * changed since we last acquired the mPackages 7813 * lock. 7814 */ 7815 // writer 7816 synchronized (mPackages) { 7817 updatePermissionsLPw(p.packageName, p, 7818 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 7819 } 7820 addedPackage = p.applicationInfo.packageName; 7821 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 7822 } 7823 } 7824 } 7825 7826 // reader 7827 synchronized (mPackages) { 7828 mSettings.writeLPr(); 7829 } 7830 } 7831 7832 if (removedPackage != null) { 7833 Bundle extras = new Bundle(1); 7834 extras.putInt(Intent.EXTRA_UID, removedAppId); 7835 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 7836 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7837 extras, null, null, removedUsers); 7838 } 7839 if (addedPackage != null) { 7840 Bundle extras = new Bundle(1); 7841 extras.putInt(Intent.EXTRA_UID, addedAppId); 7842 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 7843 extras, null, null, addedUsers); 7844 } 7845 } 7846 7847 private final String mRootDir; 7848 private final boolean mIsRom; 7849 private final boolean mIsPrivileged; 7850 } 7851 7852 @Override 7853 public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags, 7854 String installerPackageName, VerificationParams verificationParams, 7855 String packageAbiOverride) { 7856 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7857 null); 7858 7859 final File originFile = new File(originPath); 7860 final int uid = Binder.getCallingUid(); 7861 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7862 try { 7863 if (observer != null) { 7864 observer.packageInstalled("", null, INSTALL_FAILED_USER_RESTRICTED, null); 7865 } 7866 } catch (RemoteException re) { 7867 } 7868 return; 7869 } 7870 7871 UserHandle user; 7872 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7873 user = UserHandle.ALL; 7874 } else { 7875 user = new UserHandle(UserHandle.getUserId(uid)); 7876 } 7877 7878 final int filteredFlags; 7879 if (uid == Process.SHELL_UID || uid == 0) { 7880 if (DEBUG_INSTALL) { 7881 Slog.v(TAG, "Install from ADB"); 7882 } 7883 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7884 } else { 7885 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7886 } 7887 7888 verificationParams.setInstallerUid(uid); 7889 7890 final Message msg = mHandler.obtainMessage(INIT_COPY); 7891 msg.obj = new InstallParams(originFile, false, observer, filteredFlags, 7892 installerPackageName, verificationParams, user, packageAbiOverride); 7893 mHandler.sendMessage(msg); 7894 } 7895 7896 void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer, 7897 InstallSessionParams params, String installerPackageName, int installerUid, 7898 UserHandle user) { 7899 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7900 params.referrerUri, installerUid, null); 7901 7902 final Message msg = mHandler.obtainMessage(INIT_COPY); 7903 msg.obj = new InstallParams(stageDir, true, observer, params.installFlags, 7904 installerPackageName, verifParams, user, params.abiOverride); 7905 mHandler.sendMessage(msg); 7906 } 7907 7908 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7909 Bundle extras = new Bundle(1); 7910 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7911 7912 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7913 packageName, extras, null, null, new int[] {userId}); 7914 try { 7915 IActivityManager am = ActivityManagerNative.getDefault(); 7916 final boolean isSystem = 7917 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7918 if (isSystem && am.isUserRunning(userId, false)) { 7919 // The just-installed/enabled app is bundled on the system, so presumed 7920 // to be able to run automatically without needing an explicit launch. 7921 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7922 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7923 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7924 .setPackage(packageName); 7925 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7926 android.app.AppOpsManager.OP_NONE, false, false, userId); 7927 } 7928 } catch (RemoteException e) { 7929 // shouldn't happen 7930 Slog.w(TAG, "Unable to bootstrap installed package", e); 7931 } 7932 } 7933 7934 @Override 7935 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7936 int userId) { 7937 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7938 PackageSetting pkgSetting; 7939 final int uid = Binder.getCallingUid(); 7940 if (UserHandle.getUserId(uid) != userId) { 7941 mContext.enforceCallingOrSelfPermission( 7942 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7943 "setApplicationHiddenSetting for user " + userId); 7944 } 7945 7946 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7947 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7948 return false; 7949 } 7950 7951 long callingId = Binder.clearCallingIdentity(); 7952 try { 7953 boolean sendAdded = false; 7954 boolean sendRemoved = false; 7955 // writer 7956 synchronized (mPackages) { 7957 pkgSetting = mSettings.mPackages.get(packageName); 7958 if (pkgSetting == null) { 7959 return false; 7960 } 7961 if (pkgSetting.getHidden(userId) != hidden) { 7962 pkgSetting.setHidden(hidden, userId); 7963 mSettings.writePackageRestrictionsLPr(userId); 7964 if (hidden) { 7965 sendRemoved = true; 7966 } else { 7967 sendAdded = true; 7968 } 7969 } 7970 } 7971 if (sendAdded) { 7972 sendPackageAddedForUser(packageName, pkgSetting, userId); 7973 return true; 7974 } 7975 if (sendRemoved) { 7976 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7977 "hiding pkg"); 7978 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7979 } 7980 } finally { 7981 Binder.restoreCallingIdentity(callingId); 7982 } 7983 return false; 7984 } 7985 7986 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7987 int userId) { 7988 final PackageRemovedInfo info = new PackageRemovedInfo(); 7989 info.removedPackage = packageName; 7990 info.removedUsers = new int[] {userId}; 7991 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7992 info.sendBroadcast(false, false, false); 7993 } 7994 7995 /** 7996 * Returns true if application is not found or there was an error. Otherwise it returns 7997 * the hidden state of the package for the given user. 7998 */ 7999 @Override 8000 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8001 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8002 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8003 "getApplicationHidden for user " + userId); 8004 PackageSetting pkgSetting; 8005 long callingId = Binder.clearCallingIdentity(); 8006 try { 8007 // writer 8008 synchronized (mPackages) { 8009 pkgSetting = mSettings.mPackages.get(packageName); 8010 if (pkgSetting == null) { 8011 return true; 8012 } 8013 return pkgSetting.getHidden(userId); 8014 } 8015 } finally { 8016 Binder.restoreCallingIdentity(callingId); 8017 } 8018 } 8019 8020 /** 8021 * @hide 8022 */ 8023 @Override 8024 public int installExistingPackageAsUser(String packageName, int userId) { 8025 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8026 null); 8027 PackageSetting pkgSetting; 8028 final int uid = Binder.getCallingUid(); 8029 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 8030 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8031 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8032 } 8033 8034 long callingId = Binder.clearCallingIdentity(); 8035 try { 8036 boolean sendAdded = false; 8037 Bundle extras = new Bundle(1); 8038 8039 // writer 8040 synchronized (mPackages) { 8041 pkgSetting = mSettings.mPackages.get(packageName); 8042 if (pkgSetting == null) { 8043 return PackageManager.INSTALL_FAILED_INVALID_URI; 8044 } 8045 if (!pkgSetting.getInstalled(userId)) { 8046 pkgSetting.setInstalled(true, userId); 8047 pkgSetting.setHidden(false, userId); 8048 mSettings.writePackageRestrictionsLPr(userId); 8049 sendAdded = true; 8050 } 8051 } 8052 8053 if (sendAdded) { 8054 sendPackageAddedForUser(packageName, pkgSetting, userId); 8055 } 8056 } finally { 8057 Binder.restoreCallingIdentity(callingId); 8058 } 8059 8060 return PackageManager.INSTALL_SUCCEEDED; 8061 } 8062 8063 boolean isUserRestricted(int userId, String restrictionKey) { 8064 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8065 if (restrictions.getBoolean(restrictionKey, false)) { 8066 Log.w(TAG, "User is restricted: " + restrictionKey); 8067 return true; 8068 } 8069 return false; 8070 } 8071 8072 @Override 8073 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8074 mContext.enforceCallingOrSelfPermission( 8075 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8076 "Only package verification agents can verify applications"); 8077 8078 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8079 final PackageVerificationResponse response = new PackageVerificationResponse( 8080 verificationCode, Binder.getCallingUid()); 8081 msg.arg1 = id; 8082 msg.obj = response; 8083 mHandler.sendMessage(msg); 8084 } 8085 8086 @Override 8087 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8088 long millisecondsToDelay) { 8089 mContext.enforceCallingOrSelfPermission( 8090 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8091 "Only package verification agents can extend verification timeouts"); 8092 8093 final PackageVerificationState state = mPendingVerification.get(id); 8094 final PackageVerificationResponse response = new PackageVerificationResponse( 8095 verificationCodeAtTimeout, Binder.getCallingUid()); 8096 8097 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8098 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8099 } 8100 if (millisecondsToDelay < 0) { 8101 millisecondsToDelay = 0; 8102 } 8103 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8104 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8105 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8106 } 8107 8108 if ((state != null) && !state.timeoutExtended()) { 8109 state.extendTimeout(); 8110 8111 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8112 msg.arg1 = id; 8113 msg.obj = response; 8114 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8115 } 8116 } 8117 8118 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8119 int verificationCode, UserHandle user) { 8120 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8121 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8122 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8123 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8124 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8125 8126 mContext.sendBroadcastAsUser(intent, user, 8127 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8128 } 8129 8130 private ComponentName matchComponentForVerifier(String packageName, 8131 List<ResolveInfo> receivers) { 8132 ActivityInfo targetReceiver = null; 8133 8134 final int NR = receivers.size(); 8135 for (int i = 0; i < NR; i++) { 8136 final ResolveInfo info = receivers.get(i); 8137 if (info.activityInfo == null) { 8138 continue; 8139 } 8140 8141 if (packageName.equals(info.activityInfo.packageName)) { 8142 targetReceiver = info.activityInfo; 8143 break; 8144 } 8145 } 8146 8147 if (targetReceiver == null) { 8148 return null; 8149 } 8150 8151 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8152 } 8153 8154 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8155 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8156 if (pkgInfo.verifiers.length == 0) { 8157 return null; 8158 } 8159 8160 final int N = pkgInfo.verifiers.length; 8161 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8162 for (int i = 0; i < N; i++) { 8163 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8164 8165 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8166 receivers); 8167 if (comp == null) { 8168 continue; 8169 } 8170 8171 final int verifierUid = getUidForVerifier(verifierInfo); 8172 if (verifierUid == -1) { 8173 continue; 8174 } 8175 8176 if (DEBUG_VERIFY) { 8177 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8178 + " with the correct signature"); 8179 } 8180 sufficientVerifiers.add(comp); 8181 verificationState.addSufficientVerifier(verifierUid); 8182 } 8183 8184 return sufficientVerifiers; 8185 } 8186 8187 private int getUidForVerifier(VerifierInfo verifierInfo) { 8188 synchronized (mPackages) { 8189 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8190 if (pkg == null) { 8191 return -1; 8192 } else if (pkg.mSignatures.length != 1) { 8193 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8194 + " has more than one signature; ignoring"); 8195 return -1; 8196 } 8197 8198 /* 8199 * If the public key of the package's signature does not match 8200 * our expected public key, then this is a different package and 8201 * we should skip. 8202 */ 8203 8204 final byte[] expectedPublicKey; 8205 try { 8206 final Signature verifierSig = pkg.mSignatures[0]; 8207 final PublicKey publicKey = verifierSig.getPublicKey(); 8208 expectedPublicKey = publicKey.getEncoded(); 8209 } catch (CertificateException e) { 8210 return -1; 8211 } 8212 8213 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8214 8215 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8216 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8217 + " does not have the expected public key; ignoring"); 8218 return -1; 8219 } 8220 8221 return pkg.applicationInfo.uid; 8222 } 8223 } 8224 8225 @Override 8226 public void finishPackageInstall(int token) { 8227 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8228 8229 if (DEBUG_INSTALL) { 8230 Slog.v(TAG, "BM finishing package install for " + token); 8231 } 8232 8233 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8234 mHandler.sendMessage(msg); 8235 } 8236 8237 /** 8238 * Get the verification agent timeout. 8239 * 8240 * @return verification timeout in milliseconds 8241 */ 8242 private long getVerificationTimeout() { 8243 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8244 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8245 DEFAULT_VERIFICATION_TIMEOUT); 8246 } 8247 8248 /** 8249 * Get the default verification agent response code. 8250 * 8251 * @return default verification response code 8252 */ 8253 private int getDefaultVerificationResponse() { 8254 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8255 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8256 DEFAULT_VERIFICATION_RESPONSE); 8257 } 8258 8259 /** 8260 * Check whether or not package verification has been enabled. 8261 * 8262 * @return true if verification should be performed 8263 */ 8264 private boolean isVerificationEnabled(int userId, int flags) { 8265 if (!DEFAULT_VERIFY_ENABLE) { 8266 return false; 8267 } 8268 8269 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8270 8271 // Check if installing from ADB 8272 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8273 // Do not run verification in a test harness environment 8274 if (ActivityManager.isRunningInTestHarness()) { 8275 return false; 8276 } 8277 if (ensureVerifyAppsEnabled) { 8278 return true; 8279 } 8280 // Check if the developer does not want package verification for ADB installs 8281 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8282 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8283 return false; 8284 } 8285 } 8286 8287 if (ensureVerifyAppsEnabled) { 8288 return true; 8289 } 8290 8291 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8292 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8293 } 8294 8295 /** 8296 * Get the "allow unknown sources" setting. 8297 * 8298 * @return the current "allow unknown sources" setting 8299 */ 8300 private int getUnknownSourcesSettings() { 8301 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8302 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8303 -1); 8304 } 8305 8306 @Override 8307 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8308 final int uid = Binder.getCallingUid(); 8309 // writer 8310 synchronized (mPackages) { 8311 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8312 if (targetPackageSetting == null) { 8313 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8314 } 8315 8316 PackageSetting installerPackageSetting; 8317 if (installerPackageName != null) { 8318 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8319 if (installerPackageSetting == null) { 8320 throw new IllegalArgumentException("Unknown installer package: " 8321 + installerPackageName); 8322 } 8323 } else { 8324 installerPackageSetting = null; 8325 } 8326 8327 Signature[] callerSignature; 8328 Object obj = mSettings.getUserIdLPr(uid); 8329 if (obj != null) { 8330 if (obj instanceof SharedUserSetting) { 8331 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8332 } else if (obj instanceof PackageSetting) { 8333 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8334 } else { 8335 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8336 } 8337 } else { 8338 throw new SecurityException("Unknown calling uid " + uid); 8339 } 8340 8341 // Verify: can't set installerPackageName to a package that is 8342 // not signed with the same cert as the caller. 8343 if (installerPackageSetting != null) { 8344 if (compareSignatures(callerSignature, 8345 installerPackageSetting.signatures.mSignatures) 8346 != PackageManager.SIGNATURE_MATCH) { 8347 throw new SecurityException( 8348 "Caller does not have same cert as new installer package " 8349 + installerPackageName); 8350 } 8351 } 8352 8353 // Verify: if target already has an installer package, it must 8354 // be signed with the same cert as the caller. 8355 if (targetPackageSetting.installerPackageName != null) { 8356 PackageSetting setting = mSettings.mPackages.get( 8357 targetPackageSetting.installerPackageName); 8358 // If the currently set package isn't valid, then it's always 8359 // okay to change it. 8360 if (setting != null) { 8361 if (compareSignatures(callerSignature, 8362 setting.signatures.mSignatures) 8363 != PackageManager.SIGNATURE_MATCH) { 8364 throw new SecurityException( 8365 "Caller does not have same cert as old installer package " 8366 + targetPackageSetting.installerPackageName); 8367 } 8368 } 8369 } 8370 8371 // Okay! 8372 targetPackageSetting.installerPackageName = installerPackageName; 8373 scheduleWriteSettingsLocked(); 8374 } 8375 } 8376 8377 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8378 // Queue up an async operation since the package installation may take a little while. 8379 mHandler.post(new Runnable() { 8380 public void run() { 8381 mHandler.removeCallbacks(this); 8382 // Result object to be returned 8383 PackageInstalledInfo res = new PackageInstalledInfo(); 8384 res.returnCode = currentStatus; 8385 res.uid = -1; 8386 res.pkg = null; 8387 res.removedInfo = new PackageRemovedInfo(); 8388 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8389 args.doPreInstall(res.returnCode); 8390 synchronized (mInstallLock) { 8391 installPackageLI(args, true, res); 8392 } 8393 args.doPostInstall(res.returnCode, res.uid); 8394 } 8395 8396 // A restore should be performed at this point if (a) the install 8397 // succeeded, (b) the operation is not an update, and (c) the new 8398 // package has a backupAgent defined. 8399 final boolean update = res.removedInfo.removedPackage != null; 8400 boolean doRestore = (!update 8401 && res.pkg != null 8402 && res.pkg.applicationInfo.backupAgentName != null); 8403 8404 // Set up the post-install work request bookkeeping. This will be used 8405 // and cleaned up by the post-install event handling regardless of whether 8406 // there's a restore pass performed. Token values are >= 1. 8407 int token; 8408 if (mNextInstallToken < 0) mNextInstallToken = 1; 8409 token = mNextInstallToken++; 8410 8411 PostInstallData data = new PostInstallData(args, res); 8412 mRunningInstalls.put(token, data); 8413 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8414 8415 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8416 // Pass responsibility to the Backup Manager. It will perform a 8417 // restore if appropriate, then pass responsibility back to the 8418 // Package Manager to run the post-install observer callbacks 8419 // and broadcasts. 8420 IBackupManager bm = IBackupManager.Stub.asInterface( 8421 ServiceManager.getService(Context.BACKUP_SERVICE)); 8422 if (bm != null) { 8423 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8424 + " to BM for possible restore"); 8425 try { 8426 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8427 } catch (RemoteException e) { 8428 // can't happen; the backup manager is local 8429 } catch (Exception e) { 8430 Slog.e(TAG, "Exception trying to enqueue restore", e); 8431 doRestore = false; 8432 } 8433 } else { 8434 Slog.e(TAG, "Backup Manager not found!"); 8435 doRestore = false; 8436 } 8437 } 8438 8439 if (!doRestore) { 8440 // No restore possible, or the Backup Manager was mysteriously not 8441 // available -- just fire the post-install work request directly. 8442 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8443 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8444 mHandler.sendMessage(msg); 8445 } 8446 } 8447 }); 8448 } 8449 8450 private abstract class HandlerParams { 8451 private static final int MAX_RETRIES = 4; 8452 8453 /** 8454 * Number of times startCopy() has been attempted and had a non-fatal 8455 * error. 8456 */ 8457 private int mRetries = 0; 8458 8459 /** User handle for the user requesting the information or installation. */ 8460 private final UserHandle mUser; 8461 8462 HandlerParams(UserHandle user) { 8463 mUser = user; 8464 } 8465 8466 UserHandle getUser() { 8467 return mUser; 8468 } 8469 8470 final boolean startCopy() { 8471 boolean res; 8472 try { 8473 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8474 8475 if (++mRetries > MAX_RETRIES) { 8476 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8477 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8478 handleServiceError(); 8479 return false; 8480 } else { 8481 handleStartCopy(); 8482 res = true; 8483 } 8484 } catch (RemoteException e) { 8485 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8486 mHandler.sendEmptyMessage(MCS_RECONNECT); 8487 res = false; 8488 } 8489 handleReturnCode(); 8490 return res; 8491 } 8492 8493 final void serviceError() { 8494 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8495 handleServiceError(); 8496 handleReturnCode(); 8497 } 8498 8499 abstract void handleStartCopy() throws RemoteException; 8500 abstract void handleServiceError(); 8501 abstract void handleReturnCode(); 8502 } 8503 8504 class MeasureParams extends HandlerParams { 8505 private final PackageStats mStats; 8506 private boolean mSuccess; 8507 8508 private final IPackageStatsObserver mObserver; 8509 8510 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8511 super(new UserHandle(stats.userHandle)); 8512 mObserver = observer; 8513 mStats = stats; 8514 } 8515 8516 @Override 8517 public String toString() { 8518 return "MeasureParams{" 8519 + Integer.toHexString(System.identityHashCode(this)) 8520 + " " + mStats.packageName + "}"; 8521 } 8522 8523 @Override 8524 void handleStartCopy() throws RemoteException { 8525 synchronized (mInstallLock) { 8526 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8527 } 8528 8529 if (mSuccess) { 8530 final boolean mounted; 8531 if (Environment.isExternalStorageEmulated()) { 8532 mounted = true; 8533 } else { 8534 final String status = Environment.getExternalStorageState(); 8535 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8536 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8537 } 8538 8539 if (mounted) { 8540 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8541 8542 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8543 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8544 8545 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8546 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8547 8548 // Always subtract cache size, since it's a subdirectory 8549 mStats.externalDataSize -= mStats.externalCacheSize; 8550 8551 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8552 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8553 8554 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8555 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8556 } 8557 } 8558 } 8559 8560 @Override 8561 void handleReturnCode() { 8562 if (mObserver != null) { 8563 try { 8564 mObserver.onGetStatsCompleted(mStats, mSuccess); 8565 } catch (RemoteException e) { 8566 Slog.i(TAG, "Observer no longer exists."); 8567 } 8568 } 8569 } 8570 8571 @Override 8572 void handleServiceError() { 8573 Slog.e(TAG, "Could not measure application " + mStats.packageName 8574 + " external storage"); 8575 } 8576 } 8577 8578 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8579 throws RemoteException { 8580 long result = 0; 8581 for (File path : paths) { 8582 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8583 } 8584 return result; 8585 } 8586 8587 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8588 for (File path : paths) { 8589 try { 8590 mcs.clearDirectory(path.getAbsolutePath()); 8591 } catch (RemoteException e) { 8592 } 8593 } 8594 } 8595 8596 class InstallParams extends HandlerParams { 8597 /** 8598 * Location where install is coming from, before it has been 8599 * copied/renamed into place. This could be a single monolithic APK 8600 * file, or a cluster directory. This location may be untrusted. 8601 */ 8602 final File originFile; 8603 8604 /** 8605 * Flag indicating that {@link #originFile} has already been staged, 8606 * meaning downstream users don't need to defensively copy the contents. 8607 */ 8608 boolean originStaged; 8609 8610 final IPackageInstallObserver2 observer; 8611 int flags; 8612 final String installerPackageName; 8613 final VerificationParams verificationParams; 8614 private InstallArgs mArgs; 8615 private int mRet; 8616 final String packageAbiOverride; 8617 boolean multiArch; 8618 8619 InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 8620 int flags, String installerPackageName, VerificationParams verificationParams, 8621 UserHandle user, String packageAbiOverride) { 8622 super(user); 8623 this.originFile = Preconditions.checkNotNull(originFile); 8624 this.originStaged = originStaged; 8625 this.observer = observer; 8626 this.flags = flags; 8627 this.installerPackageName = installerPackageName; 8628 this.verificationParams = verificationParams; 8629 this.packageAbiOverride = packageAbiOverride; 8630 } 8631 8632 @Override 8633 public String toString() { 8634 return "InstallParams{" 8635 + Integer.toHexString(System.identityHashCode(this)) 8636 + " " + originFile + "}"; 8637 } 8638 8639 public ManifestDigest getManifestDigest() { 8640 if (verificationParams == null) { 8641 return null; 8642 } 8643 return verificationParams.getManifestDigest(); 8644 } 8645 8646 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8647 String packageName = pkgLite.packageName; 8648 int installLocation = pkgLite.installLocation; 8649 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8650 // reader 8651 synchronized (mPackages) { 8652 PackageParser.Package pkg = mPackages.get(packageName); 8653 if (pkg != null) { 8654 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8655 // Check for downgrading. 8656 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8657 if (pkgLite.versionCode < pkg.mVersionCode) { 8658 Slog.w(TAG, "Can't install update of " + packageName 8659 + " update version " + pkgLite.versionCode 8660 + " is older than installed version " 8661 + pkg.mVersionCode); 8662 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8663 } 8664 } 8665 // Check for updated system application. 8666 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8667 if (onSd) { 8668 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8669 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8670 } 8671 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8672 } else { 8673 if (onSd) { 8674 // Install flag overrides everything. 8675 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8676 } 8677 // If current upgrade specifies particular preference 8678 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8679 // Application explicitly specified internal. 8680 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8681 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8682 // App explictly prefers external. Let policy decide 8683 } else { 8684 // Prefer previous location 8685 if (isExternal(pkg)) { 8686 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8687 } 8688 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8689 } 8690 } 8691 } else { 8692 // Invalid install. Return error code 8693 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8694 } 8695 } 8696 } 8697 // All the special cases have been taken care of. 8698 // Return result based on recommended install location. 8699 if (onSd) { 8700 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8701 } 8702 return pkgLite.recommendedInstallLocation; 8703 } 8704 8705 private long getMemoryLowThreshold() { 8706 final DeviceStorageMonitorInternal 8707 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8708 if (dsm == null) { 8709 return 0L; 8710 } 8711 return dsm.getMemoryLowThreshold(); 8712 } 8713 8714 /* 8715 * Invoke remote method to get package information and install 8716 * location values. Override install location based on default 8717 * policy if needed and then create install arguments based 8718 * on the install location. 8719 */ 8720 public void handleStartCopy() throws RemoteException { 8721 int ret = PackageManager.INSTALL_SUCCEEDED; 8722 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8723 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8724 PackageInfoLite pkgLite = null; 8725 8726 if (onInt && onSd) { 8727 // Check if both bits are set. 8728 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8729 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8730 } else { 8731 final long lowThreshold = getMemoryLowThreshold(); 8732 if (lowThreshold == 0L) { 8733 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8734 } 8735 8736 // Remote call to find out default install location 8737 final String originPath = originFile.getAbsolutePath(); 8738 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold, 8739 packageAbiOverride); 8740 // Keep track of whether this package is a multiArch package until 8741 // we perform a full scan of it. We need to do this because we might 8742 // end up extracting the package shared libraries before we perform 8743 // a full scan. 8744 multiArch = pkgLite.multiArch; 8745 8746 /* 8747 * If we have too little free space, try to free cache 8748 * before giving up. 8749 */ 8750 if (pkgLite.recommendedInstallLocation 8751 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8752 final long size = mContainerService.calculateInstalledSize( 8753 originPath, isForwardLocked(), packageAbiOverride); 8754 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8755 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, 8756 lowThreshold, packageAbiOverride); 8757 } 8758 /* 8759 * The cache free must have deleted the file we 8760 * downloaded to install. 8761 * 8762 * TODO: fix the "freeCache" call to not delete 8763 * the file we care about. 8764 */ 8765 if (pkgLite.recommendedInstallLocation 8766 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8767 pkgLite.recommendedInstallLocation 8768 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8769 } 8770 } 8771 } 8772 8773 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8774 int loc = pkgLite.recommendedInstallLocation; 8775 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8776 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8777 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8778 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8779 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8780 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8781 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8782 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8783 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8784 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8785 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8786 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8787 } else { 8788 // Override with defaults if needed. 8789 loc = installLocationPolicy(pkgLite, flags); 8790 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8791 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8792 } else if (!onSd && !onInt) { 8793 // Override install location with flags 8794 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8795 // Set the flag to install on external media. 8796 flags |= PackageManager.INSTALL_EXTERNAL; 8797 flags &= ~PackageManager.INSTALL_INTERNAL; 8798 } else { 8799 // Make sure the flag for installing on external 8800 // media is unset 8801 flags |= PackageManager.INSTALL_INTERNAL; 8802 flags &= ~PackageManager.INSTALL_EXTERNAL; 8803 } 8804 } 8805 } 8806 } 8807 8808 final InstallArgs args = createInstallArgs(this); 8809 mArgs = args; 8810 8811 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8812 /* 8813 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8814 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8815 */ 8816 int userIdentifier = getUser().getIdentifier(); 8817 if (userIdentifier == UserHandle.USER_ALL 8818 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8819 userIdentifier = UserHandle.USER_OWNER; 8820 } 8821 8822 /* 8823 * Determine if we have any installed package verifiers. If we 8824 * do, then we'll defer to them to verify the packages. 8825 */ 8826 final int requiredUid = mRequiredVerifierPackage == null ? -1 8827 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8828 if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) { 8829 // TODO: send verifier the install session instead of uri 8830 final Intent verification = new Intent( 8831 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8832 verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE); 8833 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8834 8835 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8836 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8837 0 /* TODO: Which userId? */); 8838 8839 if (DEBUG_VERIFY) { 8840 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8841 + verification.toString() + " with " + pkgLite.verifiers.length 8842 + " optional verifiers"); 8843 } 8844 8845 final int verificationId = mPendingVerificationToken++; 8846 8847 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8848 8849 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8850 installerPackageName); 8851 8852 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8853 8854 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8855 pkgLite.packageName); 8856 8857 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8858 pkgLite.versionCode); 8859 8860 if (verificationParams != null) { 8861 if (verificationParams.getVerificationURI() != null) { 8862 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8863 verificationParams.getVerificationURI()); 8864 } 8865 if (verificationParams.getOriginatingURI() != null) { 8866 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8867 verificationParams.getOriginatingURI()); 8868 } 8869 if (verificationParams.getReferrer() != null) { 8870 verification.putExtra(Intent.EXTRA_REFERRER, 8871 verificationParams.getReferrer()); 8872 } 8873 if (verificationParams.getOriginatingUid() >= 0) { 8874 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8875 verificationParams.getOriginatingUid()); 8876 } 8877 if (verificationParams.getInstallerUid() >= 0) { 8878 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8879 verificationParams.getInstallerUid()); 8880 } 8881 } 8882 8883 final PackageVerificationState verificationState = new PackageVerificationState( 8884 requiredUid, args); 8885 8886 mPendingVerification.append(verificationId, verificationState); 8887 8888 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8889 receivers, verificationState); 8890 8891 /* 8892 * If any sufficient verifiers were listed in the package 8893 * manifest, attempt to ask them. 8894 */ 8895 if (sufficientVerifiers != null) { 8896 final int N = sufficientVerifiers.size(); 8897 if (N == 0) { 8898 Slog.i(TAG, "Additional verifiers required, but none installed."); 8899 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8900 } else { 8901 for (int i = 0; i < N; i++) { 8902 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8903 8904 final Intent sufficientIntent = new Intent(verification); 8905 sufficientIntent.setComponent(verifierComponent); 8906 8907 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8908 } 8909 } 8910 } 8911 8912 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8913 mRequiredVerifierPackage, receivers); 8914 if (ret == PackageManager.INSTALL_SUCCEEDED 8915 && mRequiredVerifierPackage != null) { 8916 /* 8917 * Send the intent to the required verification agent, 8918 * but only start the verification timeout after the 8919 * target BroadcastReceivers have run. 8920 */ 8921 verification.setComponent(requiredVerifierComponent); 8922 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8923 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8924 new BroadcastReceiver() { 8925 @Override 8926 public void onReceive(Context context, Intent intent) { 8927 final Message msg = mHandler 8928 .obtainMessage(CHECK_PENDING_VERIFICATION); 8929 msg.arg1 = verificationId; 8930 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8931 } 8932 }, null, 0, null, null); 8933 8934 /* 8935 * We don't want the copy to proceed until verification 8936 * succeeds, so null out this field. 8937 */ 8938 mArgs = null; 8939 } 8940 } else { 8941 /* 8942 * No package verification is enabled, so immediately start 8943 * the remote call to initiate copy using temporary file. 8944 */ 8945 ret = args.copyApk(mContainerService, true); 8946 } 8947 } 8948 8949 mRet = ret; 8950 } 8951 8952 @Override 8953 void handleReturnCode() { 8954 // If mArgs is null, then MCS couldn't be reached. When it 8955 // reconnects, it will try again to install. At that point, this 8956 // will succeed. 8957 if (mArgs != null) { 8958 processPendingInstall(mArgs, mRet); 8959 } 8960 } 8961 8962 @Override 8963 void handleServiceError() { 8964 mArgs = createInstallArgs(this); 8965 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8966 } 8967 8968 public boolean isForwardLocked() { 8969 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8970 } 8971 } 8972 8973 /* 8974 * Utility class used in movePackage api. 8975 * srcArgs and targetArgs are not set for invalid flags and make 8976 * sure to do null checks when invoking methods on them. 8977 * We probably want to return ErrorPrams for both failed installs 8978 * and moves. 8979 */ 8980 class MoveParams extends HandlerParams { 8981 final IPackageMoveObserver observer; 8982 final int flags; 8983 final String packageName; 8984 final InstallArgs srcArgs; 8985 final InstallArgs targetArgs; 8986 int uid; 8987 int mRet; 8988 8989 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8990 String packageName, String[] instructionSets, int uid, UserHandle user, 8991 boolean isMultiArch) { 8992 super(user); 8993 this.srcArgs = srcArgs; 8994 this.observer = observer; 8995 this.flags = flags; 8996 this.packageName = packageName; 8997 this.uid = uid; 8998 if (srcArgs != null) { 8999 final String codePath = srcArgs.getCodePath(); 9000 targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, 9001 instructionSets, isMultiArch); 9002 } else { 9003 targetArgs = null; 9004 } 9005 } 9006 9007 @Override 9008 public String toString() { 9009 return "MoveParams{" 9010 + Integer.toHexString(System.identityHashCode(this)) 9011 + " " + packageName + "}"; 9012 } 9013 9014 public void handleStartCopy() throws RemoteException { 9015 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9016 // Check for storage space on target medium 9017 if (!targetArgs.checkFreeStorage(mContainerService)) { 9018 Log.w(TAG, "Insufficient storage to install"); 9019 return; 9020 } 9021 9022 mRet = srcArgs.doPreCopy(); 9023 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 9024 return; 9025 } 9026 9027 mRet = targetArgs.copyApk(mContainerService, false); 9028 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 9029 srcArgs.doPostCopy(uid); 9030 return; 9031 } 9032 9033 mRet = srcArgs.doPostCopy(uid); 9034 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 9035 return; 9036 } 9037 9038 mRet = targetArgs.doPreInstall(mRet); 9039 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 9040 return; 9041 } 9042 9043 if (DEBUG_SD_INSTALL) { 9044 StringBuilder builder = new StringBuilder(); 9045 if (srcArgs != null) { 9046 builder.append("src: "); 9047 builder.append(srcArgs.getCodePath()); 9048 } 9049 if (targetArgs != null) { 9050 builder.append(" target : "); 9051 builder.append(targetArgs.getCodePath()); 9052 } 9053 Log.i(TAG, builder.toString()); 9054 } 9055 } 9056 9057 @Override 9058 void handleReturnCode() { 9059 targetArgs.doPostInstall(mRet, uid); 9060 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 9061 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 9062 currentStatus = PackageManager.MOVE_SUCCEEDED; 9063 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 9064 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 9065 } 9066 processPendingMove(this, currentStatus); 9067 } 9068 9069 @Override 9070 void handleServiceError() { 9071 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9072 } 9073 } 9074 9075 /** 9076 * Used during creation of InstallArgs 9077 * 9078 * @param flags package installation flags 9079 * @return true if should be installed on external storage 9080 */ 9081 private static boolean installOnSd(int flags) { 9082 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 9083 return false; 9084 } 9085 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 9086 return true; 9087 } 9088 return false; 9089 } 9090 9091 /** 9092 * Used during creation of InstallArgs 9093 * 9094 * @param flags package installation flags 9095 * @return true if should be installed as forward locked 9096 */ 9097 private static boolean installForwardLocked(int flags) { 9098 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9099 } 9100 9101 private InstallArgs createInstallArgs(InstallParams params) { 9102 // TODO: extend to support incoming zero-copy locations 9103 9104 if (installOnSd(params.flags) || params.isForwardLocked()) { 9105 return new AsecInstallArgs(params); 9106 } else { 9107 return new FileInstallArgs(params); 9108 } 9109 } 9110 9111 /** 9112 * Create args that describe an existing installed package. Typically used 9113 * when cleaning up old installs, or used as a move source. 9114 */ 9115 private InstallArgs createInstallArgsForExisting(int flags, String codePath, 9116 String resourcePath, String nativeLibraryRoot, String[] instructionSets, 9117 boolean isMultiArch) { 9118 final boolean isInAsec; 9119 if (installOnSd(flags)) { 9120 /* Apps on SD card are always in ASEC containers. */ 9121 isInAsec = true; 9122 } else if (installForwardLocked(flags) 9123 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9124 /* 9125 * Forward-locked apps are only in ASEC containers if they're the 9126 * new style 9127 */ 9128 isInAsec = true; 9129 } else { 9130 isInAsec = false; 9131 } 9132 9133 if (isInAsec) { 9134 return new AsecInstallArgs(codePath, instructionSets, 9135 installOnSd(flags), installForwardLocked(flags), isMultiArch); 9136 } else { 9137 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9138 instructionSets, isMultiArch); 9139 } 9140 } 9141 9142 private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName, 9143 String[] instructionSets, boolean isMultiArch) { 9144 final File codeFile = new File(codePath); 9145 if (installOnSd(flags) || installForwardLocked(flags)) { 9146 String cid = getNextCodePath(codePath, pkgName, "/" 9147 + AsecInstallArgs.RES_FILE_NAME); 9148 return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags), 9149 installForwardLocked(flags), isMultiArch); 9150 } else { 9151 return new FileInstallArgs(codeFile, instructionSets, isMultiArch); 9152 } 9153 } 9154 9155 static abstract class InstallArgs { 9156 /** @see InstallParams#originFile */ 9157 final File originFile; 9158 /** @see InstallParams#originStaged */ 9159 final boolean originStaged; 9160 9161 // TODO: define inherit location 9162 9163 final IPackageInstallObserver2 observer; 9164 // Always refers to PackageManager flags only 9165 final int flags; 9166 final String installerPackageName; 9167 final ManifestDigest manifestDigest; 9168 final UserHandle user; 9169 final String abiOverride; 9170 final boolean multiArch; 9171 9172 // The list of instruction sets supported by this app. This is currently 9173 // only used during the rmdex() phase to clean up resources. We can get rid of this 9174 // if we move dex files under the common app path. 9175 /* nullable */ String[] instructionSets; 9176 9177 InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 9178 int flags, String installerPackageName, ManifestDigest manifestDigest, 9179 UserHandle user, String[] instructionSets, 9180 String abiOverride, boolean multiArch) { 9181 this.originFile = originFile; 9182 this.originStaged = originStaged; 9183 this.flags = flags; 9184 this.observer = observer; 9185 this.installerPackageName = installerPackageName; 9186 this.manifestDigest = manifestDigest; 9187 this.user = user; 9188 this.instructionSets = instructionSets; 9189 this.abiOverride = abiOverride; 9190 this.multiArch = multiArch; 9191 } 9192 9193 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9194 abstract int doPreInstall(int status); 9195 9196 /** 9197 * Rename package into final resting place. All paths on the given 9198 * scanned package should be updated to reflect the rename. 9199 */ 9200 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9201 abstract int doPostInstall(int status, int uid); 9202 9203 /** @see PackageSettingBase#codePathString */ 9204 abstract String getCodePath(); 9205 /** @see PackageSettingBase#resourcePathString */ 9206 abstract String getResourcePath(); 9207 abstract String getLegacyNativeLibraryPath(); 9208 9209 // Need installer lock especially for dex file removal. 9210 abstract void cleanUpResourcesLI(); 9211 abstract boolean doPostDeleteLI(boolean delete); 9212 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9213 9214 /** 9215 * Called before the source arguments are copied. This is used mostly 9216 * for MoveParams when it needs to read the source file to put it in the 9217 * destination. 9218 */ 9219 int doPreCopy() { 9220 return PackageManager.INSTALL_SUCCEEDED; 9221 } 9222 9223 /** 9224 * Called after the source arguments are copied. This is used mostly for 9225 * MoveParams when it needs to read the source file to put it in the 9226 * destination. 9227 * 9228 * @return 9229 */ 9230 int doPostCopy(int uid) { 9231 return PackageManager.INSTALL_SUCCEEDED; 9232 } 9233 9234 protected boolean isFwdLocked() { 9235 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9236 } 9237 9238 UserHandle getUser() { 9239 return user; 9240 } 9241 } 9242 9243 /** 9244 * Logic to handle installation of non-ASEC applications, including copying 9245 * and renaming logic. 9246 */ 9247 class FileInstallArgs extends InstallArgs { 9248 private File codeFile; 9249 private File resourceFile; 9250 private File legacyNativeLibraryPath; 9251 9252 // Example topology: 9253 // /data/app/com.example/base.apk 9254 // /data/app/com.example/split_foo.apk 9255 // /data/app/com.example/lib/arm/libfoo.so 9256 // /data/app/com.example/lib/arm64/libfoo.so 9257 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9258 9259 /** New install */ 9260 FileInstallArgs(InstallParams params) { 9261 super(params.originFile, params.originStaged, params.observer, params.flags, 9262 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9263 null /* instruction sets */, params.packageAbiOverride, 9264 params.multiArch); 9265 if (isFwdLocked()) { 9266 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9267 } 9268 } 9269 9270 /** Existing install */ 9271 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9272 String[] instructionSets, boolean isMultiArch) { 9273 super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch); 9274 this.codeFile = (codePath != null) ? new File(codePath) : null; 9275 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9276 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9277 new File(legacyNativeLibraryPath) : null; 9278 } 9279 9280 /** New install from existing */ 9281 FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) { 9282 super(originFile, false, null, 0, null, null, null, instructionSets, null, 9283 isMultiArch); 9284 } 9285 9286 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9287 final long lowThreshold; 9288 9289 final DeviceStorageMonitorInternal 9290 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9291 if (dsm == null) { 9292 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9293 lowThreshold = 0L; 9294 } else { 9295 if (dsm.isMemoryLow()) { 9296 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9297 return false; 9298 } 9299 9300 lowThreshold = dsm.getMemoryLowThreshold(); 9301 } 9302 9303 return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9304 lowThreshold); 9305 } 9306 9307 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9308 int ret = PackageManager.INSTALL_SUCCEEDED; 9309 9310 if (originStaged) { 9311 Slog.d(TAG, originFile + " already staged; skipping copy"); 9312 codeFile = originFile; 9313 resourceFile = originFile; 9314 } else { 9315 try { 9316 final File tempDir = mInstallerService.allocateSessionDir(); 9317 codeFile = tempDir; 9318 resourceFile = tempDir; 9319 } catch (IOException e) { 9320 Slog.w(TAG, "Failed to create copy file: " + e); 9321 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9322 } 9323 9324 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9325 @Override 9326 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9327 if (!FileUtils.isValidExtFilename(name)) { 9328 throw new IllegalArgumentException("Invalid filename: " + name); 9329 } 9330 try { 9331 final File file = new File(codeFile, name); 9332 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9333 O_RDWR | O_CREAT, 0644); 9334 Os.chmod(file.getAbsolutePath(), 0644); 9335 return new ParcelFileDescriptor(fd); 9336 } catch (ErrnoException e) { 9337 throw new RemoteException("Failed to open: " + e.getMessage()); 9338 } 9339 } 9340 }; 9341 9342 ret = imcs.copyPackage(originFile.getAbsolutePath(), target); 9343 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9344 Slog.e(TAG, "Failed to copy package"); 9345 return ret; 9346 } 9347 } 9348 9349 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9350 NativeLibraryHelper.Handle handle = null; 9351 try { 9352 handle = NativeLibraryHelper.Handle.create(codeFile); 9353 if (multiArch) { 9354 // Warn if we've set an abiOverride for multi-lib packages.. 9355 // By definition, we need to copy both 32 and 64 bit libraries for 9356 // such packages. 9357 if (abiOverride != null) { 9358 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9359 } 9360 9361 int copyRet = PackageManager.NO_NATIVE_LIBRARIES; 9362 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9363 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9364 Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */); 9365 maybeThrowExceptionForMultiArchCopy("Failure copying 32 bit native libraries", copyRet); 9366 } 9367 9368 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9369 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9370 Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */); 9371 maybeThrowExceptionForMultiArchCopy("Failure copying 64 bit native libraries", copyRet); 9372 } 9373 } else { 9374 String[] abiList = (abiOverride != null) ? 9375 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 9376 9377 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null && 9378 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9379 abiList = Build.SUPPORTED_32_BIT_ABIS; 9380 } 9381 9382 int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList, 9383 true /* use isa specific subdirs */); 9384 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9385 Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]"); 9386 return copyRet; 9387 } 9388 } 9389 } catch (IOException e) { 9390 Slog.e(TAG, "Copying native libraries failed", e); 9391 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9392 } catch (PackageManagerException pme) { 9393 Slog.e(TAG, "Copying native libraries failed", pme); 9394 ret = pme.error; 9395 } finally { 9396 IoUtils.closeQuietly(handle); 9397 } 9398 9399 return ret; 9400 } 9401 9402 int doPreInstall(int status) { 9403 if (status != PackageManager.INSTALL_SUCCEEDED) { 9404 cleanUp(); 9405 } 9406 return status; 9407 } 9408 9409 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9410 if (status != PackageManager.INSTALL_SUCCEEDED) { 9411 cleanUp(); 9412 return false; 9413 } else { 9414 final File beforeCodeFile = codeFile; 9415 final File afterCodeFile = getNextCodePath(pkg.packageName); 9416 9417 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9418 try { 9419 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9420 } catch (ErrnoException e) { 9421 Slog.d(TAG, "Failed to rename", e); 9422 return false; 9423 } 9424 9425 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9426 Slog.d(TAG, "Failed to restorecon"); 9427 return false; 9428 } 9429 9430 // Reflect the rename internally 9431 codeFile = afterCodeFile; 9432 resourceFile = afterCodeFile; 9433 9434 // Reflect the rename in scanned details 9435 pkg.codePath = afterCodeFile.getAbsolutePath(); 9436 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9437 pkg.baseCodePath); 9438 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9439 pkg.splitCodePaths); 9440 9441 // Reflect the rename in app info 9442 pkg.applicationInfo.setCodePath(pkg.codePath); 9443 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9444 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9445 pkg.applicationInfo.setResourcePath(pkg.codePath); 9446 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9447 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9448 9449 return true; 9450 } 9451 } 9452 9453 int doPostInstall(int status, int uid) { 9454 if (status != PackageManager.INSTALL_SUCCEEDED) { 9455 cleanUp(); 9456 } 9457 return status; 9458 } 9459 9460 @Override 9461 String getCodePath() { 9462 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9463 } 9464 9465 @Override 9466 String getResourcePath() { 9467 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9468 } 9469 9470 @Override 9471 String getLegacyNativeLibraryPath() { 9472 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9473 } 9474 9475 private boolean cleanUp() { 9476 if (codeFile == null || !codeFile.exists()) { 9477 return false; 9478 } 9479 9480 if (codeFile.isDirectory()) { 9481 FileUtils.deleteContents(codeFile); 9482 } 9483 codeFile.delete(); 9484 9485 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9486 resourceFile.delete(); 9487 } 9488 9489 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9490 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9491 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9492 } 9493 legacyNativeLibraryPath.delete(); 9494 } 9495 9496 return true; 9497 } 9498 9499 void cleanUpResourcesLI() { 9500 // Try enumerating all code paths before deleting 9501 List<String> allCodePaths = Collections.EMPTY_LIST; 9502 if (codeFile != null && codeFile.exists()) { 9503 try { 9504 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9505 allCodePaths = pkg.getAllCodePaths(); 9506 } catch (PackageParserException e) { 9507 // Ignored; we tried our best 9508 } 9509 } 9510 9511 cleanUp(); 9512 9513 if (!allCodePaths.isEmpty()) { 9514 if (instructionSets == null) { 9515 throw new IllegalStateException("instructionSet == null"); 9516 } 9517 9518 for (String codePath : allCodePaths) { 9519 for (String instructionSet : instructionSets) { 9520 int retCode = mInstaller.rmdex(codePath, instructionSet); 9521 if (retCode < 0) { 9522 Slog.w(TAG, "Couldn't remove dex file for package: " 9523 + " at location " + codePath + ", retcode=" + retCode); 9524 // we don't consider this to be a failure of the core package deletion 9525 } 9526 } 9527 } 9528 } 9529 } 9530 9531 boolean doPostDeleteLI(boolean delete) { 9532 // XXX err, shouldn't we respect the delete flag? 9533 cleanUpResourcesLI(); 9534 return true; 9535 } 9536 } 9537 9538 private boolean isAsecExternal(String cid) { 9539 final String asecPath = PackageHelper.getSdFilesystem(cid); 9540 return !asecPath.startsWith(mAsecInternalPath); 9541 } 9542 9543 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9544 PackageManagerException { 9545 if (copyRet < 0) { 9546 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9547 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9548 throw new PackageManagerException(copyRet, message); 9549 } 9550 } 9551 } 9552 9553 /** 9554 * Extract the MountService "container ID" from the full code path of an 9555 * .apk. 9556 */ 9557 static String cidFromCodePath(String fullCodePath) { 9558 int eidx = fullCodePath.lastIndexOf("/"); 9559 String subStr1 = fullCodePath.substring(0, eidx); 9560 int sidx = subStr1.lastIndexOf("/"); 9561 return subStr1.substring(sidx+1, eidx); 9562 } 9563 9564 /** 9565 * Logic to handle installation of ASEC applications, including copying and 9566 * renaming logic. 9567 */ 9568 class AsecInstallArgs extends InstallArgs { 9569 // TODO: teach about handling cluster directories 9570 9571 static final String RES_FILE_NAME = "pkg.apk"; 9572 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9573 9574 String cid; 9575 String packagePath; 9576 String resourcePath; 9577 String legacyNativeLibraryDir; 9578 9579 /** New install */ 9580 AsecInstallArgs(InstallParams params) { 9581 super(params.originFile, params.originStaged, params.observer, params.flags, 9582 params.installerPackageName, params.getManifestDigest(), 9583 params.getUser(), null /* instruction sets */, 9584 params.packageAbiOverride, params.multiArch); 9585 } 9586 9587 /** Existing install */ 9588 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9589 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9590 super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9591 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9592 instructionSets, null, isMultiArch); 9593 // Extract cid from fullCodePath 9594 int eidx = fullCodePath.lastIndexOf("/"); 9595 String subStr1 = fullCodePath.substring(0, eidx); 9596 int sidx = subStr1.lastIndexOf("/"); 9597 cid = subStr1.substring(sidx+1, eidx); 9598 setCachePath(subStr1); 9599 } 9600 9601 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked, 9602 boolean isMultiArch) { 9603 super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9604 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9605 instructionSets, null, isMultiArch); 9606 this.cid = cid; 9607 setCachePath(PackageHelper.getSdDir(cid)); 9608 } 9609 9610 /** New install from existing */ 9611 AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets, 9612 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9613 super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9614 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9615 instructionSets, null, isMultiArch); 9616 this.cid = cid; 9617 } 9618 9619 void createCopyFile() { 9620 cid = getTempContainerId(); 9621 } 9622 9623 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9624 return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9625 abiOverride); 9626 } 9627 9628 private final boolean isExternal() { 9629 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9630 } 9631 9632 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9633 if (temp) { 9634 createCopyFile(); 9635 } else { 9636 /* 9637 * Pre-emptively destroy the container since it's destroyed if 9638 * copying fails due to it existing anyway. 9639 */ 9640 PackageHelper.destroySdDir(cid); 9641 } 9642 9643 final String newCachePath = imcs.copyPackageToContainer( 9644 originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9645 isFwdLocked(), abiOverride); 9646 9647 if (newCachePath != null) { 9648 setCachePath(newCachePath); 9649 return PackageManager.INSTALL_SUCCEEDED; 9650 } else { 9651 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9652 } 9653 } 9654 9655 @Override 9656 String getCodePath() { 9657 return packagePath; 9658 } 9659 9660 @Override 9661 String getResourcePath() { 9662 return resourcePath; 9663 } 9664 9665 @Override 9666 String getLegacyNativeLibraryPath() { 9667 return legacyNativeLibraryDir; 9668 } 9669 9670 int doPreInstall(int status) { 9671 if (status != PackageManager.INSTALL_SUCCEEDED) { 9672 // Destroy container 9673 PackageHelper.destroySdDir(cid); 9674 } else { 9675 boolean mounted = PackageHelper.isContainerMounted(cid); 9676 if (!mounted) { 9677 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9678 Process.SYSTEM_UID); 9679 if (newCachePath != null) { 9680 setCachePath(newCachePath); 9681 } else { 9682 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9683 } 9684 } 9685 } 9686 return status; 9687 } 9688 9689 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9690 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9691 String newCachePath = null; 9692 if (PackageHelper.isContainerMounted(cid)) { 9693 // Unmount the container 9694 if (!PackageHelper.unMountSdDir(cid)) { 9695 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9696 return false; 9697 } 9698 } 9699 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9700 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9701 " which might be stale. Will try to clean up."); 9702 // Clean up the stale container and proceed to recreate. 9703 if (!PackageHelper.destroySdDir(newCacheId)) { 9704 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9705 return false; 9706 } 9707 // Successfully cleaned up stale container. Try to rename again. 9708 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9709 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9710 + " inspite of cleaning it up."); 9711 return false; 9712 } 9713 } 9714 if (!PackageHelper.isContainerMounted(newCacheId)) { 9715 Slog.w(TAG, "Mounting container " + newCacheId); 9716 newCachePath = PackageHelper.mountSdDir(newCacheId, 9717 getEncryptKey(), Process.SYSTEM_UID); 9718 } else { 9719 newCachePath = PackageHelper.getSdDir(newCacheId); 9720 } 9721 if (newCachePath == null) { 9722 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9723 return false; 9724 } 9725 Log.i(TAG, "Succesfully renamed " + cid + 9726 " to " + newCacheId + 9727 " at new path: " + newCachePath); 9728 cid = newCacheId; 9729 setCachePath(newCachePath); 9730 9731 // TODO: extend to support split APKs 9732 pkg.codePath = getCodePath(); 9733 pkg.baseCodePath = getCodePath(); 9734 pkg.splitCodePaths = null; 9735 9736 pkg.applicationInfo.setCodePath(getCodePath()); 9737 pkg.applicationInfo.setBaseCodePath(getCodePath()); 9738 pkg.applicationInfo.setSplitCodePaths(null); 9739 pkg.applicationInfo.setResourcePath(getResourcePath()); 9740 pkg.applicationInfo.setBaseResourcePath(getResourcePath()); 9741 pkg.applicationInfo.setSplitResourcePaths(null); 9742 9743 return true; 9744 } 9745 9746 private void setCachePath(String newCachePath) { 9747 File cachePath = new File(newCachePath); 9748 legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath(); 9749 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9750 9751 if (isFwdLocked()) { 9752 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9753 } else { 9754 resourcePath = packagePath; 9755 } 9756 } 9757 9758 int doPostInstall(int status, int uid) { 9759 if (status != PackageManager.INSTALL_SUCCEEDED) { 9760 cleanUp(); 9761 } else { 9762 final int groupOwner; 9763 final String protectedFile; 9764 if (isFwdLocked()) { 9765 groupOwner = UserHandle.getSharedAppGid(uid); 9766 protectedFile = RES_FILE_NAME; 9767 } else { 9768 groupOwner = -1; 9769 protectedFile = null; 9770 } 9771 9772 if (uid < Process.FIRST_APPLICATION_UID 9773 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9774 Slog.e(TAG, "Failed to finalize " + cid); 9775 PackageHelper.destroySdDir(cid); 9776 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9777 } 9778 9779 boolean mounted = PackageHelper.isContainerMounted(cid); 9780 if (!mounted) { 9781 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9782 } 9783 } 9784 return status; 9785 } 9786 9787 private void cleanUp() { 9788 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9789 9790 // Destroy secure container 9791 PackageHelper.destroySdDir(cid); 9792 } 9793 9794 void cleanUpResourcesLI() { 9795 String sourceFile = getCodePath(); 9796 // Remove dex file 9797 if (instructionSets == null) { 9798 throw new IllegalStateException("instructionSet == null"); 9799 } 9800 for (String instructionSet : instructionSets) { 9801 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9802 if (retCode < 0) { 9803 Slog.w(TAG, "Couldn't remove dex file for package: " 9804 + " at location " 9805 + sourceFile.toString() + ", retcode=" + retCode); 9806 // we don't consider this to be a failure of the core package deletion 9807 } 9808 } 9809 cleanUp(); 9810 } 9811 9812 boolean matchContainer(String app) { 9813 if (cid.startsWith(app)) { 9814 return true; 9815 } 9816 return false; 9817 } 9818 9819 String getPackageName() { 9820 return getAsecPackageName(cid); 9821 } 9822 9823 boolean doPostDeleteLI(boolean delete) { 9824 boolean ret = false; 9825 boolean mounted = PackageHelper.isContainerMounted(cid); 9826 if (mounted) { 9827 // Unmount first 9828 ret = PackageHelper.unMountSdDir(cid); 9829 } 9830 if (ret && delete) { 9831 cleanUpResourcesLI(); 9832 } 9833 return ret; 9834 } 9835 9836 @Override 9837 int doPreCopy() { 9838 if (isFwdLocked()) { 9839 if (!PackageHelper.fixSdPermissions(cid, 9840 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9841 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9842 } 9843 } 9844 9845 return PackageManager.INSTALL_SUCCEEDED; 9846 } 9847 9848 @Override 9849 int doPostCopy(int uid) { 9850 if (isFwdLocked()) { 9851 if (uid < Process.FIRST_APPLICATION_UID 9852 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9853 RES_FILE_NAME)) { 9854 Slog.e(TAG, "Failed to finalize " + cid); 9855 PackageHelper.destroySdDir(cid); 9856 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9857 } 9858 } 9859 9860 return PackageManager.INSTALL_SUCCEEDED; 9861 } 9862 } 9863 9864 static String getAsecPackageName(String packageCid) { 9865 int idx = packageCid.lastIndexOf("-"); 9866 if (idx == -1) { 9867 return packageCid; 9868 } 9869 return packageCid.substring(0, idx); 9870 } 9871 9872 // Utility method used to create code paths based on package name and available index. 9873 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9874 String idxStr = ""; 9875 int idx = 1; 9876 // Fall back to default value of idx=1 if prefix is not 9877 // part of oldCodePath 9878 if (oldCodePath != null) { 9879 String subStr = oldCodePath; 9880 // Drop the suffix right away 9881 if (suffix != null && subStr.endsWith(suffix)) { 9882 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9883 } 9884 // If oldCodePath already contains prefix find out the 9885 // ending index to either increment or decrement. 9886 int sidx = subStr.lastIndexOf(prefix); 9887 if (sidx != -1) { 9888 subStr = subStr.substring(sidx + prefix.length()); 9889 if (subStr != null) { 9890 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9891 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9892 } 9893 try { 9894 idx = Integer.parseInt(subStr); 9895 if (idx <= 1) { 9896 idx++; 9897 } else { 9898 idx--; 9899 } 9900 } catch(NumberFormatException e) { 9901 } 9902 } 9903 } 9904 } 9905 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9906 return prefix + idxStr; 9907 } 9908 9909 private File getNextCodePath(String packageName) { 9910 int suffix = 1; 9911 File result; 9912 do { 9913 result = new File(mAppInstallDir, packageName + "-" + suffix); 9914 suffix++; 9915 } while (result.exists()); 9916 return result; 9917 } 9918 9919 // Utility method used to ignore ADD/REMOVE events 9920 // by directory observer. 9921 private static boolean ignoreCodePath(String fullPathStr) { 9922 String apkName = deriveCodePathName(fullPathStr); 9923 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9924 if (idx != -1 && ((idx+1) < apkName.length())) { 9925 // Make sure the package ends with a numeral 9926 String version = apkName.substring(idx+1); 9927 try { 9928 Integer.parseInt(version); 9929 return true; 9930 } catch (NumberFormatException e) {} 9931 } 9932 return false; 9933 } 9934 9935 // Utility method that returns the relative package path with respect 9936 // to the installation directory. Like say for /data/data/com.test-1.apk 9937 // string com.test-1 is returned. 9938 static String deriveCodePathName(String codePath) { 9939 if (codePath == null) { 9940 return null; 9941 } 9942 final File codeFile = new File(codePath); 9943 final String name = codeFile.getName(); 9944 if (codeFile.isDirectory()) { 9945 return name; 9946 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9947 final int lastDot = name.lastIndexOf('.'); 9948 return name.substring(0, lastDot); 9949 } else { 9950 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9951 return null; 9952 } 9953 } 9954 9955 class PackageInstalledInfo { 9956 String name; 9957 int uid; 9958 // The set of users that originally had this package installed. 9959 int[] origUsers; 9960 // The set of users that now have this package installed. 9961 int[] newUsers; 9962 PackageParser.Package pkg; 9963 int returnCode; 9964 String returnMsg; 9965 PackageRemovedInfo removedInfo; 9966 9967 public void setError(int code, String msg) { 9968 returnCode = code; 9969 returnMsg = msg; 9970 Slog.w(TAG, msg); 9971 } 9972 9973 public void setError(String msg, PackageParserException e) { 9974 returnCode = e.error; 9975 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9976 Slog.w(TAG, msg, e); 9977 } 9978 9979 public void setError(String msg, PackageManagerException e) { 9980 returnCode = e.error; 9981 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9982 Slog.w(TAG, msg, e); 9983 } 9984 9985 // In some error cases we want to convey more info back to the observer 9986 String origPackage; 9987 String origPermission; 9988 } 9989 9990 /* 9991 * Install a non-existing package. 9992 */ 9993 private void installNewPackageLI(PackageParser.Package pkg, 9994 int parseFlags, int scanMode, UserHandle user, 9995 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9996 // Remember this for later, in case we need to rollback this install 9997 String pkgName = pkg.packageName; 9998 9999 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10000 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 10001 synchronized(mPackages) { 10002 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10003 // A package with the same name is already installed, though 10004 // it has been renamed to an older name. The package we 10005 // are trying to install should be installed as an update to 10006 // the existing one, but that has not been requested, so bail. 10007 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10008 + " without first uninstalling package running as " 10009 + mSettings.mRenamedPackages.get(pkgName)); 10010 return; 10011 } 10012 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 10013 // Don't allow installation over an existing package with the same name. 10014 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10015 + " without first uninstalling."); 10016 return; 10017 } 10018 } 10019 10020 try { 10021 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 10022 System.currentTimeMillis(), user, abiOverride); 10023 10024 updateSettingsLI(newPackage, installerPackageName, null, null, res); 10025 // delete the partially installed application. the data directory will have to be 10026 // restored if it was already existing 10027 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10028 // remove package from internal structures. Note that we want deletePackageX to 10029 // delete the package data and cache directories that it created in 10030 // scanPackageLocked, unless those directories existed before we even tried to 10031 // install. 10032 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10033 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10034 res.removedInfo, true); 10035 } 10036 10037 } catch (PackageManagerException e) { 10038 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10039 } 10040 } 10041 10042 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10043 // Upgrade keysets are being used. Determine if new package has a superset of the 10044 // required keys. 10045 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10046 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10047 for (int i = 0; i < upgradeKeySets.length; i++) { 10048 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10049 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10050 return true; 10051 } 10052 } 10053 return false; 10054 } 10055 10056 private void replacePackageLI(PackageParser.Package pkg, 10057 int parseFlags, int scanMode, UserHandle user, 10058 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10059 PackageParser.Package oldPackage; 10060 String pkgName = pkg.packageName; 10061 int[] allUsers; 10062 boolean[] perUserInstalled; 10063 10064 // First find the old package info and check signatures 10065 synchronized(mPackages) { 10066 oldPackage = mPackages.get(pkgName); 10067 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10068 PackageSetting ps = mSettings.mPackages.get(pkgName); 10069 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10070 // default to original signature matching 10071 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10072 != PackageManager.SIGNATURE_MATCH) { 10073 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10074 "New package has a different signature: " + pkgName); 10075 return; 10076 } 10077 } else { 10078 if(!checkUpgradeKeySetLP(ps, pkg)) { 10079 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10080 "New package not signed by keys specified by upgrade-keysets: " 10081 + pkgName); 10082 return; 10083 } 10084 } 10085 10086 // In case of rollback, remember per-user/profile install state 10087 allUsers = sUserManager.getUserIds(); 10088 perUserInstalled = new boolean[allUsers.length]; 10089 for (int i = 0; i < allUsers.length; i++) { 10090 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10091 } 10092 } 10093 10094 boolean sysPkg = (isSystemApp(oldPackage)); 10095 if (sysPkg) { 10096 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10097 user, allUsers, perUserInstalled, installerPackageName, res, 10098 abiOverride); 10099 } else { 10100 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10101 user, allUsers, perUserInstalled, installerPackageName, res, 10102 abiOverride); 10103 } 10104 } 10105 10106 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10107 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10108 int[] allUsers, boolean[] perUserInstalled, 10109 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10110 String pkgName = deletedPackage.packageName; 10111 boolean deletedPkg = true; 10112 boolean updatedSettings = false; 10113 10114 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10115 + deletedPackage); 10116 long origUpdateTime; 10117 if (pkg.mExtras != null) { 10118 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10119 } else { 10120 origUpdateTime = 0; 10121 } 10122 10123 // First delete the existing package while retaining the data directory 10124 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10125 res.removedInfo, true)) { 10126 // If the existing package wasn't successfully deleted 10127 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10128 deletedPkg = false; 10129 } else { 10130 // Successfully deleted the old package. Now proceed with re-installation 10131 deleteCodeCacheDirsLI(pkgName); 10132 try { 10133 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10134 scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user, abiOverride); 10135 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10136 updatedSettings = true; 10137 } catch (PackageManagerException e) { 10138 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10139 } 10140 } 10141 10142 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10143 // remove package from internal structures. Note that we want deletePackageX to 10144 // delete the package data and cache directories that it created in 10145 // scanPackageLocked, unless those directories existed before we even tried to 10146 // install. 10147 if(updatedSettings) { 10148 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10149 deletePackageLI( 10150 pkgName, null, true, allUsers, perUserInstalled, 10151 PackageManager.DELETE_KEEP_DATA, 10152 res.removedInfo, true); 10153 } 10154 // Since we failed to install the new package we need to restore the old 10155 // package that we deleted. 10156 if (deletedPkg) { 10157 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10158 File restoreFile = new File(deletedPackage.codePath); 10159 // Parse old package 10160 boolean oldOnSd = isExternal(deletedPackage); 10161 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10162 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10163 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10164 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 10165 | SCAN_UPDATE_TIME; 10166 try { 10167 scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null, 10168 null); 10169 } catch (PackageManagerException e) { 10170 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10171 + e.getMessage()); 10172 return; 10173 } 10174 // Restore of old package succeeded. Update permissions. 10175 // writer 10176 synchronized (mPackages) { 10177 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10178 UPDATE_PERMISSIONS_ALL); 10179 // can downgrade to reader 10180 mSettings.writeLPr(); 10181 } 10182 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10183 } 10184 } 10185 } 10186 10187 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10188 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10189 int[] allUsers, boolean[] perUserInstalled, 10190 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10191 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10192 + ", old=" + deletedPackage); 10193 boolean updatedSettings = false; 10194 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 10195 PackageParser.PARSE_IS_SYSTEM; 10196 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10197 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10198 } 10199 String packageName = deletedPackage.packageName; 10200 if (packageName == null) { 10201 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10202 "Attempt to delete null packageName."); 10203 return; 10204 } 10205 PackageParser.Package oldPkg; 10206 PackageSetting oldPkgSetting; 10207 // reader 10208 synchronized (mPackages) { 10209 oldPkg = mPackages.get(packageName); 10210 oldPkgSetting = mSettings.mPackages.get(packageName); 10211 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10212 (oldPkgSetting == null)) { 10213 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10214 "Couldn't find package:" + packageName + " information"); 10215 return; 10216 } 10217 } 10218 10219 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10220 10221 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10222 res.removedInfo.removedPackage = packageName; 10223 // Remove existing system package 10224 removePackageLI(oldPkgSetting, true); 10225 // writer 10226 synchronized (mPackages) { 10227 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10228 // We didn't need to disable the .apk as a current system package, 10229 // which means we are replacing another update that is already 10230 // installed. We need to make sure to delete the older one's .apk. 10231 res.removedInfo.args = createInstallArgsForExisting(0, 10232 deletedPackage.applicationInfo.getCodePath(), 10233 deletedPackage.applicationInfo.getResourcePath(), 10234 deletedPackage.applicationInfo.nativeLibraryRootDir, 10235 getAppDexInstructionSets(deletedPackage.applicationInfo), 10236 isMultiArch(deletedPackage.applicationInfo)); 10237 } else { 10238 res.removedInfo.args = null; 10239 } 10240 } 10241 10242 // Successfully disabled the old package. Now proceed with re-installation 10243 deleteCodeCacheDirsLI(packageName); 10244 10245 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10246 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10247 10248 PackageParser.Package newPackage = null; 10249 try { 10250 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride); 10251 if (newPackage.mExtras != null) { 10252 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10253 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10254 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10255 10256 // is the update attempting to change shared user? that isn't going to work... 10257 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10258 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10259 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10260 + " to " + newPkgSetting.sharedUser); 10261 updatedSettings = true; 10262 } 10263 } 10264 10265 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10266 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10267 updatedSettings = true; 10268 } 10269 10270 } catch (PackageManagerException e) { 10271 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10272 } 10273 10274 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10275 // Re installation failed. Restore old information 10276 // Remove new pkg information 10277 if (newPackage != null) { 10278 removeInstalledPackageLI(newPackage, true); 10279 } 10280 // Add back the old system package 10281 try { 10282 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, 10283 null); 10284 } catch (PackageManagerException e) { 10285 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10286 } 10287 // Restore the old system information in Settings 10288 synchronized(mPackages) { 10289 if (updatedSettings) { 10290 mSettings.enableSystemPackageLPw(packageName); 10291 mSettings.setInstallerPackageName(packageName, 10292 oldPkgSetting.installerPackageName); 10293 } 10294 mSettings.writeLPr(); 10295 } 10296 } 10297 } 10298 10299 // Utility method used to move dex files during install. 10300 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10301 // TODO: extend to move split APK dex files 10302 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10303 final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo); 10304 for (String instructionSet : instructionSets) { 10305 int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath, 10306 instructionSet); 10307 if (retCode != 0) { 10308 /* 10309 * Programs may be lazily run through dexopt, so the 10310 * source may not exist. However, something seems to 10311 * have gone wrong, so note that dexopt needs to be 10312 * run again and remove the source file. In addition, 10313 * remove the target to make sure there isn't a stale 10314 * file from a previous version of the package. 10315 */ 10316 newPackage.mDexOptPerformed.clear(); 10317 mInstaller.rmdex(oldCodePath, instructionSet); 10318 mInstaller.rmdex(newPackage.baseCodePath, instructionSet); 10319 } 10320 } 10321 } 10322 return PackageManager.INSTALL_SUCCEEDED; 10323 } 10324 10325 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10326 int[] allUsers, boolean[] perUserInstalled, 10327 PackageInstalledInfo res) { 10328 String pkgName = newPackage.packageName; 10329 synchronized (mPackages) { 10330 //write settings. the installStatus will be incomplete at this stage. 10331 //note that the new package setting would have already been 10332 //added to mPackages. It hasn't been persisted yet. 10333 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10334 mSettings.writeLPr(); 10335 } 10336 10337 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10338 10339 synchronized (mPackages) { 10340 updatePermissionsLPw(newPackage.packageName, newPackage, 10341 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10342 ? UPDATE_PERMISSIONS_ALL : 0)); 10343 // For system-bundled packages, we assume that installing an upgraded version 10344 // of the package implies that the user actually wants to run that new code, 10345 // so we enable the package. 10346 if (isSystemApp(newPackage)) { 10347 // NB: implicit assumption that system package upgrades apply to all users 10348 if (DEBUG_INSTALL) { 10349 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10350 } 10351 PackageSetting ps = mSettings.mPackages.get(pkgName); 10352 if (ps != null) { 10353 if (res.origUsers != null) { 10354 for (int userHandle : res.origUsers) { 10355 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10356 userHandle, installerPackageName); 10357 } 10358 } 10359 // Also convey the prior install/uninstall state 10360 if (allUsers != null && perUserInstalled != null) { 10361 for (int i = 0; i < allUsers.length; i++) { 10362 if (DEBUG_INSTALL) { 10363 Slog.d(TAG, " user " + allUsers[i] 10364 + " => " + perUserInstalled[i]); 10365 } 10366 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10367 } 10368 // these install state changes will be persisted in the 10369 // upcoming call to mSettings.writeLPr(). 10370 } 10371 } 10372 } 10373 res.name = pkgName; 10374 res.uid = newPackage.applicationInfo.uid; 10375 res.pkg = newPackage; 10376 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10377 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10378 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10379 //to update install status 10380 mSettings.writeLPr(); 10381 } 10382 } 10383 10384 private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) { 10385 int pFlags = args.flags; 10386 String installerPackageName = args.installerPackageName; 10387 File tmpPackageFile = new File(args.getCodePath()); 10388 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10389 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10390 boolean replace = false; 10391 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10392 | (newInstall ? SCAN_NEW_INSTALL : 0); 10393 // Result object to be returned 10394 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10395 10396 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10397 // Retrieve PackageSettings and parse package 10398 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10399 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10400 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10401 PackageParser pp = new PackageParser(); 10402 pp.setSeparateProcesses(mSeparateProcesses); 10403 pp.setDisplayMetrics(mMetrics); 10404 10405 final PackageParser.Package pkg; 10406 try { 10407 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10408 } catch (PackageParserException e) { 10409 res.setError("Failed parse during installPackageLI", e); 10410 return; 10411 } 10412 10413 String pkgName = res.name = pkg.packageName; 10414 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10415 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10416 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10417 return; 10418 } 10419 } 10420 10421 try { 10422 pp.collectCertificates(pkg, parseFlags); 10423 pp.collectManifestDigest(pkg); 10424 } catch (PackageParserException e) { 10425 res.setError("Failed collect during installPackageLI", e); 10426 return; 10427 } 10428 10429 /* If the installer passed in a manifest digest, compare it now. */ 10430 if (args.manifestDigest != null) { 10431 if (DEBUG_INSTALL) { 10432 final String parsedManifest = pkg.manifestDigest == null ? "null" 10433 : pkg.manifestDigest.toString(); 10434 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10435 + parsedManifest); 10436 } 10437 10438 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10439 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10440 return; 10441 } 10442 } else if (DEBUG_INSTALL) { 10443 final String parsedManifest = pkg.manifestDigest == null 10444 ? "null" : pkg.manifestDigest.toString(); 10445 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10446 } 10447 10448 // Get rid of all references to package scan path via parser. 10449 pp = null; 10450 String oldCodePath = null; 10451 boolean systemApp = false; 10452 synchronized (mPackages) { 10453 // Check whether the newly-scanned package wants to define an already-defined perm 10454 int N = pkg.permissions.size(); 10455 for (int i = N-1; i >= 0; i--) { 10456 PackageParser.Permission perm = pkg.permissions.get(i); 10457 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10458 if (bp != null) { 10459 // If the defining package is signed with our cert, it's okay. This 10460 // also includes the "updating the same package" case, of course. 10461 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10462 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10463 // If the owning package is the system itself, we log but allow 10464 // install to proceed; we fail the install on all other permission 10465 // redefinitions. 10466 if (!bp.sourcePackage.equals("android")) { 10467 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10468 + pkg.packageName + " attempting to redeclare permission " 10469 + perm.info.name + " already owned by " + bp.sourcePackage); 10470 res.origPermission = perm.info.name; 10471 res.origPackage = bp.sourcePackage; 10472 return; 10473 } else { 10474 Slog.w(TAG, "Package " + pkg.packageName 10475 + " attempting to redeclare system permission " 10476 + perm.info.name + "; ignoring new declaration"); 10477 pkg.permissions.remove(i); 10478 } 10479 } 10480 } 10481 } 10482 10483 // Check if installing already existing package 10484 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10485 String oldName = mSettings.mRenamedPackages.get(pkgName); 10486 if (pkg.mOriginalPackages != null 10487 && pkg.mOriginalPackages.contains(oldName) 10488 && mPackages.containsKey(oldName)) { 10489 // This package is derived from an original package, 10490 // and this device has been updating from that original 10491 // name. We must continue using the original name, so 10492 // rename the new package here. 10493 pkg.setPackageName(oldName); 10494 pkgName = pkg.packageName; 10495 replace = true; 10496 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10497 + oldName + " pkgName=" + pkgName); 10498 } else if (mPackages.containsKey(pkgName)) { 10499 // This package, under its official name, already exists 10500 // on the device; we should replace it. 10501 replace = true; 10502 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10503 } 10504 } 10505 PackageSetting ps = mSettings.mPackages.get(pkgName); 10506 if (ps != null) { 10507 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10508 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10509 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10510 systemApp = (ps.pkg.applicationInfo.flags & 10511 ApplicationInfo.FLAG_SYSTEM) != 0; 10512 } 10513 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10514 } 10515 } 10516 10517 if (systemApp && onSd) { 10518 // Disable updates to system apps on sdcard 10519 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10520 "Cannot install updates to system apps on sdcard"); 10521 return; 10522 } 10523 10524 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10525 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10526 return; 10527 } 10528 10529 if (replace) { 10530 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10531 installerPackageName, res, args.abiOverride); 10532 } else { 10533 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10534 installerPackageName, res, args.abiOverride); 10535 } 10536 synchronized (mPackages) { 10537 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10538 if (ps != null) { 10539 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10540 } 10541 } 10542 } 10543 10544 private static boolean isForwardLocked(PackageParser.Package pkg) { 10545 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10546 } 10547 10548 private static boolean isForwardLocked(ApplicationInfo info) { 10549 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10550 } 10551 10552 private boolean isForwardLocked(PackageSetting ps) { 10553 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10554 } 10555 10556 private static boolean isMultiArch(PackageSetting ps) { 10557 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10558 } 10559 10560 private static boolean isMultiArch(ApplicationInfo info) { 10561 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10562 } 10563 10564 private static boolean isExternal(PackageParser.Package pkg) { 10565 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10566 } 10567 10568 private static boolean isExternal(PackageSetting ps) { 10569 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10570 } 10571 10572 private static boolean isExternal(ApplicationInfo info) { 10573 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10574 } 10575 10576 private static boolean isSystemApp(PackageParser.Package pkg) { 10577 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10578 } 10579 10580 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10581 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10582 } 10583 10584 private static boolean isSystemApp(ApplicationInfo info) { 10585 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10586 } 10587 10588 private static boolean isSystemApp(PackageSetting ps) { 10589 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10590 } 10591 10592 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10593 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10594 } 10595 10596 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10597 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10598 } 10599 10600 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10601 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10602 } 10603 10604 private int packageFlagsToInstallFlags(PackageSetting ps) { 10605 int installFlags = 0; 10606 if (isExternal(ps)) { 10607 installFlags |= PackageManager.INSTALL_EXTERNAL; 10608 } 10609 if (isForwardLocked(ps)) { 10610 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10611 } 10612 return installFlags; 10613 } 10614 10615 private void deleteTempPackageFiles() { 10616 final FilenameFilter filter = new FilenameFilter() { 10617 public boolean accept(File dir, String name) { 10618 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10619 } 10620 }; 10621 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10622 file.delete(); 10623 } 10624 } 10625 10626 @Override 10627 public void deletePackageAsUser(final String packageName, 10628 final IPackageDeleteObserver observer, 10629 final int userId, final int flags) { 10630 mContext.enforceCallingOrSelfPermission( 10631 android.Manifest.permission.DELETE_PACKAGES, null); 10632 final int uid = Binder.getCallingUid(); 10633 if (UserHandle.getUserId(uid) != userId) { 10634 mContext.enforceCallingPermission( 10635 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10636 "deletePackage for user " + userId); 10637 } 10638 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10639 try { 10640 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 10641 } catch (RemoteException re) { 10642 } 10643 return; 10644 } 10645 10646 boolean uninstallBlocked = false; 10647 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10648 int[] users = sUserManager.getUserIds(); 10649 for (int i = 0; i < users.length; ++i) { 10650 if (getBlockUninstallForUser(packageName, users[i])) { 10651 uninstallBlocked = true; 10652 break; 10653 } 10654 } 10655 } else { 10656 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10657 } 10658 if (uninstallBlocked) { 10659 try { 10660 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED); 10661 } catch (RemoteException re) { 10662 } 10663 return; 10664 } 10665 10666 if (DEBUG_REMOVE) { 10667 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10668 } 10669 // Queue up an async operation since the package deletion may take a little while. 10670 mHandler.post(new Runnable() { 10671 public void run() { 10672 mHandler.removeCallbacks(this); 10673 final int returnCode = deletePackageX(packageName, userId, flags); 10674 if (observer != null) { 10675 try { 10676 observer.packageDeleted(packageName, returnCode); 10677 } catch (RemoteException e) { 10678 Log.i(TAG, "Observer no longer exists."); 10679 } //end catch 10680 } //end if 10681 } //end run 10682 }); 10683 } 10684 10685 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10686 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10687 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10688 try { 10689 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10690 || dpm.isDeviceOwner(packageName))) { 10691 return true; 10692 } 10693 } catch (RemoteException e) { 10694 } 10695 return false; 10696 } 10697 10698 /** 10699 * This method is an internal method that could be get invoked either 10700 * to delete an installed package or to clean up a failed installation. 10701 * After deleting an installed package, a broadcast is sent to notify any 10702 * listeners that the package has been installed. For cleaning up a failed 10703 * installation, the broadcast is not necessary since the package's 10704 * installation wouldn't have sent the initial broadcast either 10705 * The key steps in deleting a package are 10706 * deleting the package information in internal structures like mPackages, 10707 * deleting the packages base directories through installd 10708 * updating mSettings to reflect current status 10709 * persisting settings for later use 10710 * sending a broadcast if necessary 10711 */ 10712 private int deletePackageX(String packageName, int userId, int flags) { 10713 final PackageRemovedInfo info = new PackageRemovedInfo(); 10714 final boolean res; 10715 10716 if (isPackageDeviceAdmin(packageName, userId)) { 10717 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10718 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10719 } 10720 10721 boolean removedForAllUsers = false; 10722 boolean systemUpdate = false; 10723 10724 // for the uninstall-updates case and restricted profiles, remember the per- 10725 // userhandle installed state 10726 int[] allUsers; 10727 boolean[] perUserInstalled; 10728 synchronized (mPackages) { 10729 PackageSetting ps = mSettings.mPackages.get(packageName); 10730 allUsers = sUserManager.getUserIds(); 10731 perUserInstalled = new boolean[allUsers.length]; 10732 for (int i = 0; i < allUsers.length; i++) { 10733 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10734 } 10735 } 10736 10737 synchronized (mInstallLock) { 10738 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10739 res = deletePackageLI(packageName, 10740 (flags & PackageManager.DELETE_ALL_USERS) != 0 10741 ? UserHandle.ALL : new UserHandle(userId), 10742 true, allUsers, perUserInstalled, 10743 flags | REMOVE_CHATTY, info, true); 10744 systemUpdate = info.isRemovedPackageSystemUpdate; 10745 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10746 removedForAllUsers = true; 10747 } 10748 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10749 + " removedForAllUsers=" + removedForAllUsers); 10750 } 10751 10752 if (res) { 10753 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10754 10755 // If the removed package was a system update, the old system package 10756 // was re-enabled; we need to broadcast this information 10757 if (systemUpdate) { 10758 Bundle extras = new Bundle(1); 10759 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10760 ? info.removedAppId : info.uid); 10761 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10762 10763 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10764 extras, null, null, null); 10765 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10766 extras, null, null, null); 10767 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10768 null, packageName, null, null); 10769 } 10770 } 10771 // Force a gc here. 10772 Runtime.getRuntime().gc(); 10773 // Delete the resources here after sending the broadcast to let 10774 // other processes clean up before deleting resources. 10775 if (info.args != null) { 10776 synchronized (mInstallLock) { 10777 info.args.doPostDeleteLI(true); 10778 } 10779 } 10780 10781 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10782 } 10783 10784 static class PackageRemovedInfo { 10785 String removedPackage; 10786 int uid = -1; 10787 int removedAppId = -1; 10788 int[] removedUsers = null; 10789 boolean isRemovedPackageSystemUpdate = false; 10790 // Clean up resources deleted packages. 10791 InstallArgs args = null; 10792 10793 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10794 Bundle extras = new Bundle(1); 10795 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10796 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10797 if (replacing) { 10798 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10799 } 10800 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10801 if (removedPackage != null) { 10802 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10803 extras, null, null, removedUsers); 10804 if (fullRemove && !replacing) { 10805 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10806 extras, null, null, removedUsers); 10807 } 10808 } 10809 if (removedAppId >= 0) { 10810 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10811 removedUsers); 10812 } 10813 } 10814 } 10815 10816 /* 10817 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10818 * flag is not set, the data directory is removed as well. 10819 * make sure this flag is set for partially installed apps. If not its meaningless to 10820 * delete a partially installed application. 10821 */ 10822 private void removePackageDataLI(PackageSetting ps, 10823 int[] allUserHandles, boolean[] perUserInstalled, 10824 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10825 String packageName = ps.name; 10826 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10827 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10828 // Retrieve object to delete permissions for shared user later on 10829 final PackageSetting deletedPs; 10830 // reader 10831 synchronized (mPackages) { 10832 deletedPs = mSettings.mPackages.get(packageName); 10833 if (outInfo != null) { 10834 outInfo.removedPackage = packageName; 10835 outInfo.removedUsers = deletedPs != null 10836 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10837 : null; 10838 } 10839 } 10840 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10841 removeDataDirsLI(packageName); 10842 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10843 } 10844 // writer 10845 synchronized (mPackages) { 10846 if (deletedPs != null) { 10847 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10848 if (outInfo != null) { 10849 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10850 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10851 } 10852 if (deletedPs != null) { 10853 updatePermissionsLPw(deletedPs.name, null, 0); 10854 if (deletedPs.sharedUser != null) { 10855 // remove permissions associated with package 10856 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10857 } 10858 } 10859 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10860 } 10861 // make sure to preserve per-user disabled state if this removal was just 10862 // a downgrade of a system app to the factory package 10863 if (allUserHandles != null && perUserInstalled != null) { 10864 if (DEBUG_REMOVE) { 10865 Slog.d(TAG, "Propagating install state across downgrade"); 10866 } 10867 for (int i = 0; i < allUserHandles.length; i++) { 10868 if (DEBUG_REMOVE) { 10869 Slog.d(TAG, " user " + allUserHandles[i] 10870 + " => " + perUserInstalled[i]); 10871 } 10872 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10873 } 10874 } 10875 } 10876 // can downgrade to reader 10877 if (writeSettings) { 10878 // Save settings now 10879 mSettings.writeLPr(); 10880 } 10881 } 10882 if (outInfo != null) { 10883 // A user ID was deleted here. Go through all users and remove it 10884 // from KeyStore. 10885 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10886 } 10887 } 10888 10889 static boolean locationIsPrivileged(File path) { 10890 try { 10891 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10892 .getCanonicalPath(); 10893 return path.getCanonicalPath().startsWith(privilegedAppDir); 10894 } catch (IOException e) { 10895 Slog.e(TAG, "Unable to access code path " + path); 10896 } 10897 return false; 10898 } 10899 10900 /* 10901 * Tries to delete system package. 10902 */ 10903 private boolean deleteSystemPackageLI(PackageSetting newPs, 10904 int[] allUserHandles, boolean[] perUserInstalled, 10905 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10906 final boolean applyUserRestrictions 10907 = (allUserHandles != null) && (perUserInstalled != null); 10908 PackageSetting disabledPs = null; 10909 // Confirm if the system package has been updated 10910 // An updated system app can be deleted. This will also have to restore 10911 // the system pkg from system partition 10912 // reader 10913 synchronized (mPackages) { 10914 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10915 } 10916 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10917 + " disabledPs=" + disabledPs); 10918 if (disabledPs == null) { 10919 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10920 return false; 10921 } else if (DEBUG_REMOVE) { 10922 Slog.d(TAG, "Deleting system pkg from data partition"); 10923 } 10924 if (DEBUG_REMOVE) { 10925 if (applyUserRestrictions) { 10926 Slog.d(TAG, "Remembering install states:"); 10927 for (int i = 0; i < allUserHandles.length; i++) { 10928 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10929 } 10930 } 10931 } 10932 // Delete the updated package 10933 outInfo.isRemovedPackageSystemUpdate = true; 10934 if (disabledPs.versionCode < newPs.versionCode) { 10935 // Delete data for downgrades 10936 flags &= ~PackageManager.DELETE_KEEP_DATA; 10937 } else { 10938 // Preserve data by setting flag 10939 flags |= PackageManager.DELETE_KEEP_DATA; 10940 } 10941 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10942 allUserHandles, perUserInstalled, outInfo, writeSettings); 10943 if (!ret) { 10944 return false; 10945 } 10946 // writer 10947 synchronized (mPackages) { 10948 // Reinstate the old system package 10949 mSettings.enableSystemPackageLPw(newPs.name); 10950 // Remove any native libraries from the upgraded package. 10951 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10952 } 10953 // Install the system package 10954 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10955 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10956 if (locationIsPrivileged(disabledPs.codePath)) { 10957 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10958 } 10959 10960 final PackageParser.Package newPkg; 10961 try { 10962 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, 10963 null, null); 10964 } catch (PackageManagerException e) { 10965 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10966 return false; 10967 } 10968 10969 // writer 10970 synchronized (mPackages) { 10971 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10972 setBundledAppAbisAndRoots(newPkg, ps); 10973 updatePermissionsLPw(newPkg.packageName, newPkg, 10974 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10975 if (applyUserRestrictions) { 10976 if (DEBUG_REMOVE) { 10977 Slog.d(TAG, "Propagating install state across reinstall"); 10978 } 10979 for (int i = 0; i < allUserHandles.length; i++) { 10980 if (DEBUG_REMOVE) { 10981 Slog.d(TAG, " user " + allUserHandles[i] 10982 + " => " + perUserInstalled[i]); 10983 } 10984 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10985 } 10986 // Regardless of writeSettings we need to ensure that this restriction 10987 // state propagation is persisted 10988 mSettings.writeAllUsersPackageRestrictionsLPr(); 10989 } 10990 // can downgrade to reader here 10991 if (writeSettings) { 10992 mSettings.writeLPr(); 10993 } 10994 } 10995 return true; 10996 } 10997 10998 private boolean deleteInstalledPackageLI(PackageSetting ps, 10999 boolean deleteCodeAndResources, int flags, 11000 int[] allUserHandles, boolean[] perUserInstalled, 11001 PackageRemovedInfo outInfo, boolean writeSettings) { 11002 if (outInfo != null) { 11003 outInfo.uid = ps.appId; 11004 } 11005 11006 // Delete package data from internal structures and also remove data if flag is set 11007 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11008 11009 // Delete application code and resources 11010 if (deleteCodeAndResources && (outInfo != null)) { 11011 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11012 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11013 getAppDexInstructionSets(ps), isMultiArch(ps)); 11014 } 11015 return true; 11016 } 11017 11018 @Override 11019 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11020 int userId) { 11021 mContext.enforceCallingOrSelfPermission( 11022 android.Manifest.permission.DELETE_PACKAGES, null); 11023 synchronized (mPackages) { 11024 PackageSetting ps = mSettings.mPackages.get(packageName); 11025 if (ps == null) { 11026 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11027 return false; 11028 } 11029 if (!ps.getInstalled(userId)) { 11030 // Can't block uninstall for an app that is not installed or enabled. 11031 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11032 return false; 11033 } 11034 ps.setBlockUninstall(blockUninstall, userId); 11035 mSettings.writePackageRestrictionsLPr(userId); 11036 } 11037 return true; 11038 } 11039 11040 @Override 11041 public boolean getBlockUninstallForUser(String packageName, int userId) { 11042 synchronized (mPackages) { 11043 PackageSetting ps = mSettings.mPackages.get(packageName); 11044 if (ps == null) { 11045 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11046 return false; 11047 } 11048 return ps.getBlockUninstall(userId); 11049 } 11050 } 11051 11052 /* 11053 * This method handles package deletion in general 11054 */ 11055 private boolean deletePackageLI(String packageName, UserHandle user, 11056 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11057 int flags, PackageRemovedInfo outInfo, 11058 boolean writeSettings) { 11059 if (packageName == null) { 11060 Slog.w(TAG, "Attempt to delete null packageName."); 11061 return false; 11062 } 11063 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11064 PackageSetting ps; 11065 boolean dataOnly = false; 11066 int removeUser = -1; 11067 int appId = -1; 11068 synchronized (mPackages) { 11069 ps = mSettings.mPackages.get(packageName); 11070 if (ps == null) { 11071 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11072 return false; 11073 } 11074 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11075 && user.getIdentifier() != UserHandle.USER_ALL) { 11076 // The caller is asking that the package only be deleted for a single 11077 // user. To do this, we just mark its uninstalled state and delete 11078 // its data. If this is a system app, we only allow this to happen if 11079 // they have set the special DELETE_SYSTEM_APP which requests different 11080 // semantics than normal for uninstalling system apps. 11081 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11082 ps.setUserState(user.getIdentifier(), 11083 COMPONENT_ENABLED_STATE_DEFAULT, 11084 false, //installed 11085 true, //stopped 11086 true, //notLaunched 11087 false, //hidden 11088 null, null, null, 11089 false // blockUninstall 11090 ); 11091 if (!isSystemApp(ps)) { 11092 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11093 // Other user still have this package installed, so all 11094 // we need to do is clear this user's data and save that 11095 // it is uninstalled. 11096 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11097 removeUser = user.getIdentifier(); 11098 appId = ps.appId; 11099 mSettings.writePackageRestrictionsLPr(removeUser); 11100 } else { 11101 // We need to set it back to 'installed' so the uninstall 11102 // broadcasts will be sent correctly. 11103 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11104 ps.setInstalled(true, user.getIdentifier()); 11105 } 11106 } else { 11107 // This is a system app, so we assume that the 11108 // other users still have this package installed, so all 11109 // we need to do is clear this user's data and save that 11110 // it is uninstalled. 11111 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11112 removeUser = user.getIdentifier(); 11113 appId = ps.appId; 11114 mSettings.writePackageRestrictionsLPr(removeUser); 11115 } 11116 } 11117 } 11118 11119 if (removeUser >= 0) { 11120 // From above, we determined that we are deleting this only 11121 // for a single user. Continue the work here. 11122 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11123 if (outInfo != null) { 11124 outInfo.removedPackage = packageName; 11125 outInfo.removedAppId = appId; 11126 outInfo.removedUsers = new int[] {removeUser}; 11127 } 11128 mInstaller.clearUserData(packageName, removeUser); 11129 removeKeystoreDataIfNeeded(removeUser, appId); 11130 schedulePackageCleaning(packageName, removeUser, false); 11131 return true; 11132 } 11133 11134 if (dataOnly) { 11135 // Delete application data first 11136 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11137 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11138 return true; 11139 } 11140 11141 boolean ret = false; 11142 if (isSystemApp(ps)) { 11143 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11144 // When an updated system application is deleted we delete the existing resources as well and 11145 // fall back to existing code in system partition 11146 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11147 flags, outInfo, writeSettings); 11148 } else { 11149 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11150 // Kill application pre-emptively especially for apps on sd. 11151 killApplication(packageName, ps.appId, "uninstall pkg"); 11152 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11153 allUserHandles, perUserInstalled, 11154 outInfo, writeSettings); 11155 } 11156 11157 return ret; 11158 } 11159 11160 private final class ClearStorageConnection implements ServiceConnection { 11161 IMediaContainerService mContainerService; 11162 11163 @Override 11164 public void onServiceConnected(ComponentName name, IBinder service) { 11165 synchronized (this) { 11166 mContainerService = IMediaContainerService.Stub.asInterface(service); 11167 notifyAll(); 11168 } 11169 } 11170 11171 @Override 11172 public void onServiceDisconnected(ComponentName name) { 11173 } 11174 } 11175 11176 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11177 final boolean mounted; 11178 if (Environment.isExternalStorageEmulated()) { 11179 mounted = true; 11180 } else { 11181 final String status = Environment.getExternalStorageState(); 11182 11183 mounted = status.equals(Environment.MEDIA_MOUNTED) 11184 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11185 } 11186 11187 if (!mounted) { 11188 return; 11189 } 11190 11191 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11192 int[] users; 11193 if (userId == UserHandle.USER_ALL) { 11194 users = sUserManager.getUserIds(); 11195 } else { 11196 users = new int[] { userId }; 11197 } 11198 final ClearStorageConnection conn = new ClearStorageConnection(); 11199 if (mContext.bindServiceAsUser( 11200 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11201 try { 11202 for (int curUser : users) { 11203 long timeout = SystemClock.uptimeMillis() + 5000; 11204 synchronized (conn) { 11205 long now = SystemClock.uptimeMillis(); 11206 while (conn.mContainerService == null && now < timeout) { 11207 try { 11208 conn.wait(timeout - now); 11209 } catch (InterruptedException e) { 11210 } 11211 } 11212 } 11213 if (conn.mContainerService == null) { 11214 return; 11215 } 11216 11217 final UserEnvironment userEnv = new UserEnvironment(curUser); 11218 clearDirectory(conn.mContainerService, 11219 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11220 if (allData) { 11221 clearDirectory(conn.mContainerService, 11222 userEnv.buildExternalStorageAppDataDirs(packageName)); 11223 clearDirectory(conn.mContainerService, 11224 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11225 } 11226 } 11227 } finally { 11228 mContext.unbindService(conn); 11229 } 11230 } 11231 } 11232 11233 @Override 11234 public void clearApplicationUserData(final String packageName, 11235 final IPackageDataObserver observer, final int userId) { 11236 mContext.enforceCallingOrSelfPermission( 11237 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11238 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11239 // Queue up an async operation since the package deletion may take a little while. 11240 mHandler.post(new Runnable() { 11241 public void run() { 11242 mHandler.removeCallbacks(this); 11243 final boolean succeeded; 11244 synchronized (mInstallLock) { 11245 succeeded = clearApplicationUserDataLI(packageName, userId); 11246 } 11247 clearExternalStorageDataSync(packageName, userId, true); 11248 if (succeeded) { 11249 // invoke DeviceStorageMonitor's update method to clear any notifications 11250 DeviceStorageMonitorInternal 11251 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11252 if (dsm != null) { 11253 dsm.checkMemory(); 11254 } 11255 } 11256 if(observer != null) { 11257 try { 11258 observer.onRemoveCompleted(packageName, succeeded); 11259 } catch (RemoteException e) { 11260 Log.i(TAG, "Observer no longer exists."); 11261 } 11262 } //end if observer 11263 } //end run 11264 }); 11265 } 11266 11267 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11268 if (packageName == null) { 11269 Slog.w(TAG, "Attempt to delete null packageName."); 11270 return false; 11271 } 11272 PackageParser.Package p; 11273 boolean dataOnly = false; 11274 final int appId; 11275 synchronized (mPackages) { 11276 p = mPackages.get(packageName); 11277 if (p == null) { 11278 dataOnly = true; 11279 PackageSetting ps = mSettings.mPackages.get(packageName); 11280 if ((ps == null) || (ps.pkg == null)) { 11281 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11282 return false; 11283 } 11284 p = ps.pkg; 11285 } 11286 if (!dataOnly) { 11287 // need to check this only for fully installed applications 11288 if (p == null) { 11289 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11290 return false; 11291 } 11292 final ApplicationInfo applicationInfo = p.applicationInfo; 11293 if (applicationInfo == null) { 11294 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11295 return false; 11296 } 11297 } 11298 if (p != null && p.applicationInfo != null) { 11299 appId = p.applicationInfo.uid; 11300 } else { 11301 appId = -1; 11302 } 11303 } 11304 int retCode = mInstaller.clearUserData(packageName, userId); 11305 if (retCode < 0) { 11306 Slog.w(TAG, "Couldn't remove cache files for package: " 11307 + packageName); 11308 return false; 11309 } 11310 removeKeystoreDataIfNeeded(userId, appId); 11311 return true; 11312 } 11313 11314 /** 11315 * Remove entries from the keystore daemon. Will only remove it if the 11316 * {@code appId} is valid. 11317 */ 11318 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11319 if (appId < 0) { 11320 return; 11321 } 11322 11323 final KeyStore keyStore = KeyStore.getInstance(); 11324 if (keyStore != null) { 11325 if (userId == UserHandle.USER_ALL) { 11326 for (final int individual : sUserManager.getUserIds()) { 11327 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11328 } 11329 } else { 11330 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11331 } 11332 } else { 11333 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11334 } 11335 } 11336 11337 @Override 11338 public void deleteApplicationCacheFiles(final String packageName, 11339 final IPackageDataObserver observer) { 11340 mContext.enforceCallingOrSelfPermission( 11341 android.Manifest.permission.DELETE_CACHE_FILES, null); 11342 // Queue up an async operation since the package deletion may take a little while. 11343 final int userId = UserHandle.getCallingUserId(); 11344 mHandler.post(new Runnable() { 11345 public void run() { 11346 mHandler.removeCallbacks(this); 11347 final boolean succeded; 11348 synchronized (mInstallLock) { 11349 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11350 } 11351 clearExternalStorageDataSync(packageName, userId, false); 11352 if(observer != null) { 11353 try { 11354 observer.onRemoveCompleted(packageName, succeded); 11355 } catch (RemoteException e) { 11356 Log.i(TAG, "Observer no longer exists."); 11357 } 11358 } //end if observer 11359 } //end run 11360 }); 11361 } 11362 11363 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11364 if (packageName == null) { 11365 Slog.w(TAG, "Attempt to delete null packageName."); 11366 return false; 11367 } 11368 PackageParser.Package p; 11369 synchronized (mPackages) { 11370 p = mPackages.get(packageName); 11371 } 11372 if (p == null) { 11373 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11374 return false; 11375 } 11376 final ApplicationInfo applicationInfo = p.applicationInfo; 11377 if (applicationInfo == null) { 11378 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11379 return false; 11380 } 11381 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11382 if (retCode < 0) { 11383 Slog.w(TAG, "Couldn't remove cache files for package: " 11384 + packageName + " u" + userId); 11385 return false; 11386 } 11387 return true; 11388 } 11389 11390 @Override 11391 public void getPackageSizeInfo(final String packageName, int userHandle, 11392 final IPackageStatsObserver observer) { 11393 mContext.enforceCallingOrSelfPermission( 11394 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11395 if (packageName == null) { 11396 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11397 } 11398 11399 PackageStats stats = new PackageStats(packageName, userHandle); 11400 11401 /* 11402 * Queue up an async operation since the package measurement may take a 11403 * little while. 11404 */ 11405 Message msg = mHandler.obtainMessage(INIT_COPY); 11406 msg.obj = new MeasureParams(stats, observer); 11407 mHandler.sendMessage(msg); 11408 } 11409 11410 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11411 PackageStats pStats) { 11412 if (packageName == null) { 11413 Slog.w(TAG, "Attempt to get size of null packageName."); 11414 return false; 11415 } 11416 PackageParser.Package p; 11417 boolean dataOnly = false; 11418 String libDirRoot = null; 11419 String asecPath = null; 11420 PackageSetting ps = null; 11421 synchronized (mPackages) { 11422 p = mPackages.get(packageName); 11423 ps = mSettings.mPackages.get(packageName); 11424 if(p == null) { 11425 dataOnly = true; 11426 if((ps == null) || (ps.pkg == null)) { 11427 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11428 return false; 11429 } 11430 p = ps.pkg; 11431 } 11432 if (ps != null) { 11433 libDirRoot = ps.legacyNativeLibraryPathString; 11434 } 11435 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11436 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11437 if (secureContainerId != null) { 11438 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11439 } 11440 } 11441 } 11442 String publicSrcDir = null; 11443 if(!dataOnly) { 11444 final ApplicationInfo applicationInfo = p.applicationInfo; 11445 if (applicationInfo == null) { 11446 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11447 return false; 11448 } 11449 if (isForwardLocked(p)) { 11450 publicSrcDir = applicationInfo.getBaseResourcePath(); 11451 } 11452 } 11453 // TODO: extend to measure size of split APKs 11454 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11455 // not just the first level. 11456 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11457 // just the primary. 11458 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11459 publicSrcDir, asecPath, getAppDexInstructionSets(ps), 11460 pStats); 11461 if (res < 0) { 11462 return false; 11463 } 11464 11465 // Fix-up for forward-locked applications in ASEC containers. 11466 if (!isExternal(p)) { 11467 pStats.codeSize += pStats.externalCodeSize; 11468 pStats.externalCodeSize = 0L; 11469 } 11470 11471 return true; 11472 } 11473 11474 11475 @Override 11476 public void addPackageToPreferred(String packageName) { 11477 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11478 } 11479 11480 @Override 11481 public void removePackageFromPreferred(String packageName) { 11482 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11483 } 11484 11485 @Override 11486 public List<PackageInfo> getPreferredPackages(int flags) { 11487 return new ArrayList<PackageInfo>(); 11488 } 11489 11490 private int getUidTargetSdkVersionLockedLPr(int uid) { 11491 Object obj = mSettings.getUserIdLPr(uid); 11492 if (obj instanceof SharedUserSetting) { 11493 final SharedUserSetting sus = (SharedUserSetting) obj; 11494 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11495 final Iterator<PackageSetting> it = sus.packages.iterator(); 11496 while (it.hasNext()) { 11497 final PackageSetting ps = it.next(); 11498 if (ps.pkg != null) { 11499 int v = ps.pkg.applicationInfo.targetSdkVersion; 11500 if (v < vers) vers = v; 11501 } 11502 } 11503 return vers; 11504 } else if (obj instanceof PackageSetting) { 11505 final PackageSetting ps = (PackageSetting) obj; 11506 if (ps.pkg != null) { 11507 return ps.pkg.applicationInfo.targetSdkVersion; 11508 } 11509 } 11510 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11511 } 11512 11513 @Override 11514 public void addPreferredActivity(IntentFilter filter, int match, 11515 ComponentName[] set, ComponentName activity, int userId) { 11516 addPreferredActivityInternal(filter, match, set, activity, true, userId); 11517 } 11518 11519 private void addPreferredActivityInternal(IntentFilter filter, int match, 11520 ComponentName[] set, ComponentName activity, boolean always, int userId) { 11521 // writer 11522 int callingUid = Binder.getCallingUid(); 11523 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11524 if (filter.countActions() == 0) { 11525 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11526 return; 11527 } 11528 synchronized (mPackages) { 11529 if (mContext.checkCallingOrSelfPermission( 11530 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11531 != PackageManager.PERMISSION_GRANTED) { 11532 if (getUidTargetSdkVersionLockedLPr(callingUid) 11533 < Build.VERSION_CODES.FROYO) { 11534 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11535 + callingUid); 11536 return; 11537 } 11538 mContext.enforceCallingOrSelfPermission( 11539 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11540 } 11541 11542 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 11543 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11544 mSettings.editPreferredActivitiesLPw(userId).addFilter( 11545 new PreferredActivity(filter, match, set, activity, always)); 11546 mSettings.writePackageRestrictionsLPr(userId); 11547 } 11548 } 11549 11550 @Override 11551 public void replacePreferredActivity(IntentFilter filter, int match, 11552 ComponentName[] set, ComponentName activity) { 11553 if (filter.countActions() != 1) { 11554 throw new IllegalArgumentException( 11555 "replacePreferredActivity expects filter to have only 1 action."); 11556 } 11557 if (filter.countDataAuthorities() != 0 11558 || filter.countDataPaths() != 0 11559 || filter.countDataSchemes() > 1 11560 || filter.countDataTypes() != 0) { 11561 throw new IllegalArgumentException( 11562 "replacePreferredActivity expects filter to have no data authorities, " + 11563 "paths, or types; and at most one scheme."); 11564 } 11565 synchronized (mPackages) { 11566 if (mContext.checkCallingOrSelfPermission( 11567 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11568 != PackageManager.PERMISSION_GRANTED) { 11569 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11570 < Build.VERSION_CODES.FROYO) { 11571 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11572 + Binder.getCallingUid()); 11573 return; 11574 } 11575 mContext.enforceCallingOrSelfPermission( 11576 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11577 } 11578 11579 final int callingUserId = UserHandle.getCallingUserId(); 11580 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 11581 if (pir != null) { 11582 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 11583 if (filter.countDataSchemes() == 1) { 11584 Uri.Builder builder = new Uri.Builder(); 11585 builder.scheme(filter.getDataScheme(0)); 11586 intent.setData(builder.build()); 11587 } 11588 List<PreferredActivity> matches = pir.queryIntent( 11589 intent, null, true, callingUserId); 11590 if (DEBUG_PREFERRED) { 11591 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 11592 } 11593 for (int i = 0; i < matches.size(); i++) { 11594 PreferredActivity pa = matches.get(i); 11595 if (DEBUG_PREFERRED) { 11596 Slog.i(TAG, "Removing preferred activity " 11597 + pa.mPref.mComponent + ":"); 11598 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11599 } 11600 pir.removeFilter(pa); 11601 } 11602 } 11603 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 11604 } 11605 } 11606 11607 @Override 11608 public void clearPackagePreferredActivities(String packageName) { 11609 final int uid = Binder.getCallingUid(); 11610 // writer 11611 synchronized (mPackages) { 11612 PackageParser.Package pkg = mPackages.get(packageName); 11613 if (pkg == null || pkg.applicationInfo.uid != uid) { 11614 if (mContext.checkCallingOrSelfPermission( 11615 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11616 != PackageManager.PERMISSION_GRANTED) { 11617 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11618 < Build.VERSION_CODES.FROYO) { 11619 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11620 + Binder.getCallingUid()); 11621 return; 11622 } 11623 mContext.enforceCallingOrSelfPermission( 11624 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11625 } 11626 } 11627 11628 int user = UserHandle.getCallingUserId(); 11629 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11630 mSettings.writePackageRestrictionsLPr(user); 11631 scheduleWriteSettingsLocked(); 11632 } 11633 } 11634 } 11635 11636 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11637 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11638 ArrayList<PreferredActivity> removed = null; 11639 boolean changed = false; 11640 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11641 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11642 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11643 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11644 continue; 11645 } 11646 Iterator<PreferredActivity> it = pir.filterIterator(); 11647 while (it.hasNext()) { 11648 PreferredActivity pa = it.next(); 11649 // Mark entry for removal only if it matches the package name 11650 // and the entry is of type "always". 11651 if (packageName == null || 11652 (pa.mPref.mComponent.getPackageName().equals(packageName) 11653 && pa.mPref.mAlways)) { 11654 if (removed == null) { 11655 removed = new ArrayList<PreferredActivity>(); 11656 } 11657 removed.add(pa); 11658 } 11659 } 11660 if (removed != null) { 11661 for (int j=0; j<removed.size(); j++) { 11662 PreferredActivity pa = removed.get(j); 11663 pir.removeFilter(pa); 11664 } 11665 changed = true; 11666 } 11667 } 11668 return changed; 11669 } 11670 11671 @Override 11672 public void resetPreferredActivities(int userId) { 11673 mContext.enforceCallingOrSelfPermission( 11674 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11675 // writer 11676 synchronized (mPackages) { 11677 int user = UserHandle.getCallingUserId(); 11678 clearPackagePreferredActivitiesLPw(null, user); 11679 mSettings.readDefaultPreferredAppsLPw(this, user); 11680 mSettings.writePackageRestrictionsLPr(user); 11681 scheduleWriteSettingsLocked(); 11682 } 11683 } 11684 11685 @Override 11686 public int getPreferredActivities(List<IntentFilter> outFilters, 11687 List<ComponentName> outActivities, String packageName) { 11688 11689 int num = 0; 11690 final int userId = UserHandle.getCallingUserId(); 11691 // reader 11692 synchronized (mPackages) { 11693 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11694 if (pir != null) { 11695 final Iterator<PreferredActivity> it = pir.filterIterator(); 11696 while (it.hasNext()) { 11697 final PreferredActivity pa = it.next(); 11698 if (packageName == null 11699 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11700 && pa.mPref.mAlways)) { 11701 if (outFilters != null) { 11702 outFilters.add(new IntentFilter(pa)); 11703 } 11704 if (outActivities != null) { 11705 outActivities.add(pa.mPref.mComponent); 11706 } 11707 } 11708 } 11709 } 11710 } 11711 11712 return num; 11713 } 11714 11715 @Override 11716 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11717 int userId) { 11718 int callingUid = Binder.getCallingUid(); 11719 if (callingUid != Process.SYSTEM_UID) { 11720 throw new SecurityException( 11721 "addPersistentPreferredActivity can only be run by the system"); 11722 } 11723 if (filter.countActions() == 0) { 11724 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11725 return; 11726 } 11727 synchronized (mPackages) { 11728 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11729 " :"); 11730 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11731 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11732 new PersistentPreferredActivity(filter, activity)); 11733 mSettings.writePackageRestrictionsLPr(userId); 11734 } 11735 } 11736 11737 @Override 11738 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11739 int callingUid = Binder.getCallingUid(); 11740 if (callingUid != Process.SYSTEM_UID) { 11741 throw new SecurityException( 11742 "clearPackagePersistentPreferredActivities can only be run by the system"); 11743 } 11744 ArrayList<PersistentPreferredActivity> removed = null; 11745 boolean changed = false; 11746 synchronized (mPackages) { 11747 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11748 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11749 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11750 .valueAt(i); 11751 if (userId != thisUserId) { 11752 continue; 11753 } 11754 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11755 while (it.hasNext()) { 11756 PersistentPreferredActivity ppa = it.next(); 11757 // Mark entry for removal only if it matches the package name. 11758 if (ppa.mComponent.getPackageName().equals(packageName)) { 11759 if (removed == null) { 11760 removed = new ArrayList<PersistentPreferredActivity>(); 11761 } 11762 removed.add(ppa); 11763 } 11764 } 11765 if (removed != null) { 11766 for (int j=0; j<removed.size(); j++) { 11767 PersistentPreferredActivity ppa = removed.get(j); 11768 ppir.removeFilter(ppa); 11769 } 11770 changed = true; 11771 } 11772 } 11773 11774 if (changed) { 11775 mSettings.writePackageRestrictionsLPr(userId); 11776 } 11777 } 11778 } 11779 11780 @Override 11781 public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId, 11782 int targetUserId, int flags) { 11783 mContext.enforceCallingOrSelfPermission( 11784 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11785 if (intentFilter.countActions() == 0) { 11786 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11787 return; 11788 } 11789 synchronized (mPackages) { 11790 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11791 targetUserId, flags); 11792 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11793 mSettings.writePackageRestrictionsLPr(sourceUserId); 11794 } 11795 } 11796 11797 public void addCrossProfileIntentsForPackage(String packageName, 11798 int sourceUserId, int targetUserId) { 11799 mContext.enforceCallingOrSelfPermission( 11800 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11801 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11802 mSettings.writePackageRestrictionsLPr(sourceUserId); 11803 } 11804 11805 public void removeCrossProfileIntentsForPackage(String packageName, 11806 int sourceUserId, int targetUserId) { 11807 mContext.enforceCallingOrSelfPermission( 11808 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11809 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11810 mSettings.writePackageRestrictionsLPr(sourceUserId); 11811 } 11812 11813 @Override 11814 public void clearCrossProfileIntentFilters(int sourceUserId) { 11815 mContext.enforceCallingOrSelfPermission( 11816 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11817 synchronized (mPackages) { 11818 CrossProfileIntentResolver resolver = 11819 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11820 HashSet<CrossProfileIntentFilter> set = 11821 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11822 for (CrossProfileIntentFilter filter : set) { 11823 if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) { 11824 resolver.removeFilter(filter); 11825 } 11826 } 11827 mSettings.writePackageRestrictionsLPr(sourceUserId); 11828 } 11829 } 11830 11831 @Override 11832 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11833 Intent intent = new Intent(Intent.ACTION_MAIN); 11834 intent.addCategory(Intent.CATEGORY_HOME); 11835 11836 final int callingUserId = UserHandle.getCallingUserId(); 11837 List<ResolveInfo> list = queryIntentActivities(intent, null, 11838 PackageManager.GET_META_DATA, callingUserId); 11839 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11840 true, false, false, callingUserId); 11841 11842 allHomeCandidates.clear(); 11843 if (list != null) { 11844 for (ResolveInfo ri : list) { 11845 allHomeCandidates.add(ri); 11846 } 11847 } 11848 return (preferred == null || preferred.activityInfo == null) 11849 ? null 11850 : new ComponentName(preferred.activityInfo.packageName, 11851 preferred.activityInfo.name); 11852 } 11853 11854 @Override 11855 public void setApplicationEnabledSetting(String appPackageName, 11856 int newState, int flags, int userId, String callingPackage) { 11857 if (!sUserManager.exists(userId)) return; 11858 if (callingPackage == null) { 11859 callingPackage = Integer.toString(Binder.getCallingUid()); 11860 } 11861 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11862 } 11863 11864 @Override 11865 public void setComponentEnabledSetting(ComponentName componentName, 11866 int newState, int flags, int userId) { 11867 if (!sUserManager.exists(userId)) return; 11868 setEnabledSetting(componentName.getPackageName(), 11869 componentName.getClassName(), newState, flags, userId, null); 11870 } 11871 11872 private void setEnabledSetting(final String packageName, String className, int newState, 11873 final int flags, int userId, String callingPackage) { 11874 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11875 || newState == COMPONENT_ENABLED_STATE_ENABLED 11876 || newState == COMPONENT_ENABLED_STATE_DISABLED 11877 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11878 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11879 throw new IllegalArgumentException("Invalid new component state: " 11880 + newState); 11881 } 11882 PackageSetting pkgSetting; 11883 final int uid = Binder.getCallingUid(); 11884 final int permission = mContext.checkCallingOrSelfPermission( 11885 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11886 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11887 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11888 boolean sendNow = false; 11889 boolean isApp = (className == null); 11890 String componentName = isApp ? packageName : className; 11891 int packageUid = -1; 11892 ArrayList<String> components; 11893 11894 // writer 11895 synchronized (mPackages) { 11896 pkgSetting = mSettings.mPackages.get(packageName); 11897 if (pkgSetting == null) { 11898 if (className == null) { 11899 throw new IllegalArgumentException( 11900 "Unknown package: " + packageName); 11901 } 11902 throw new IllegalArgumentException( 11903 "Unknown component: " + packageName 11904 + "/" + className); 11905 } 11906 // Allow root and verify that userId is not being specified by a different user 11907 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11908 throw new SecurityException( 11909 "Permission Denial: attempt to change component state from pid=" 11910 + Binder.getCallingPid() 11911 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11912 } 11913 if (className == null) { 11914 // We're dealing with an application/package level state change 11915 if (pkgSetting.getEnabled(userId) == newState) { 11916 // Nothing to do 11917 return; 11918 } 11919 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11920 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11921 // Don't care about who enables an app. 11922 callingPackage = null; 11923 } 11924 pkgSetting.setEnabled(newState, userId, callingPackage); 11925 // pkgSetting.pkg.mSetEnabled = newState; 11926 } else { 11927 // We're dealing with a component level state change 11928 // First, verify that this is a valid class name. 11929 PackageParser.Package pkg = pkgSetting.pkg; 11930 if (pkg == null || !pkg.hasComponentClassName(className)) { 11931 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11932 throw new IllegalArgumentException("Component class " + className 11933 + " does not exist in " + packageName); 11934 } else { 11935 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11936 + className + " does not exist in " + packageName); 11937 } 11938 } 11939 switch (newState) { 11940 case COMPONENT_ENABLED_STATE_ENABLED: 11941 if (!pkgSetting.enableComponentLPw(className, userId)) { 11942 return; 11943 } 11944 break; 11945 case COMPONENT_ENABLED_STATE_DISABLED: 11946 if (!pkgSetting.disableComponentLPw(className, userId)) { 11947 return; 11948 } 11949 break; 11950 case COMPONENT_ENABLED_STATE_DEFAULT: 11951 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11952 return; 11953 } 11954 break; 11955 default: 11956 Slog.e(TAG, "Invalid new component state: " + newState); 11957 return; 11958 } 11959 } 11960 mSettings.writePackageRestrictionsLPr(userId); 11961 components = mPendingBroadcasts.get(userId, packageName); 11962 final boolean newPackage = components == null; 11963 if (newPackage) { 11964 components = new ArrayList<String>(); 11965 } 11966 if (!components.contains(componentName)) { 11967 components.add(componentName); 11968 } 11969 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11970 sendNow = true; 11971 // Purge entry from pending broadcast list if another one exists already 11972 // since we are sending one right away. 11973 mPendingBroadcasts.remove(userId, packageName); 11974 } else { 11975 if (newPackage) { 11976 mPendingBroadcasts.put(userId, packageName, components); 11977 } 11978 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11979 // Schedule a message 11980 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11981 } 11982 } 11983 } 11984 11985 long callingId = Binder.clearCallingIdentity(); 11986 try { 11987 if (sendNow) { 11988 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11989 sendPackageChangedBroadcast(packageName, 11990 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11991 } 11992 } finally { 11993 Binder.restoreCallingIdentity(callingId); 11994 } 11995 } 11996 11997 private void sendPackageChangedBroadcast(String packageName, 11998 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11999 if (DEBUG_INSTALL) 12000 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12001 + componentNames); 12002 Bundle extras = new Bundle(4); 12003 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12004 String nameList[] = new String[componentNames.size()]; 12005 componentNames.toArray(nameList); 12006 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12007 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12008 extras.putInt(Intent.EXTRA_UID, packageUid); 12009 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12010 new int[] {UserHandle.getUserId(packageUid)}); 12011 } 12012 12013 @Override 12014 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12015 if (!sUserManager.exists(userId)) return; 12016 final int uid = Binder.getCallingUid(); 12017 final int permission = mContext.checkCallingOrSelfPermission( 12018 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12019 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12020 enforceCrossUserPermission(uid, userId, true, "stop package"); 12021 // writer 12022 synchronized (mPackages) { 12023 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12024 uid, userId)) { 12025 scheduleWritePackageRestrictionsLocked(userId); 12026 } 12027 } 12028 } 12029 12030 @Override 12031 public String getInstallerPackageName(String packageName) { 12032 // reader 12033 synchronized (mPackages) { 12034 return mSettings.getInstallerPackageNameLPr(packageName); 12035 } 12036 } 12037 12038 @Override 12039 public int getApplicationEnabledSetting(String packageName, int userId) { 12040 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12041 int uid = Binder.getCallingUid(); 12042 enforceCrossUserPermission(uid, userId, false, "get enabled"); 12043 // reader 12044 synchronized (mPackages) { 12045 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12046 } 12047 } 12048 12049 @Override 12050 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12051 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12052 int uid = Binder.getCallingUid(); 12053 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 12054 // reader 12055 synchronized (mPackages) { 12056 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12057 } 12058 } 12059 12060 @Override 12061 public void enterSafeMode() { 12062 enforceSystemOrRoot("Only the system can request entering safe mode"); 12063 12064 if (!mSystemReady) { 12065 mSafeMode = true; 12066 } 12067 } 12068 12069 @Override 12070 public void systemReady() { 12071 mSystemReady = true; 12072 12073 // Read the compatibilty setting when the system is ready. 12074 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12075 mContext.getContentResolver(), 12076 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12077 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12078 if (DEBUG_SETTINGS) { 12079 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12080 } 12081 12082 synchronized (mPackages) { 12083 // Verify that all of the preferred activity components actually 12084 // exist. It is possible for applications to be updated and at 12085 // that point remove a previously declared activity component that 12086 // had been set as a preferred activity. We try to clean this up 12087 // the next time we encounter that preferred activity, but it is 12088 // possible for the user flow to never be able to return to that 12089 // situation so here we do a sanity check to make sure we haven't 12090 // left any junk around. 12091 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12092 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12093 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12094 removed.clear(); 12095 for (PreferredActivity pa : pir.filterSet()) { 12096 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12097 removed.add(pa); 12098 } 12099 } 12100 if (removed.size() > 0) { 12101 for (int r=0; r<removed.size(); r++) { 12102 PreferredActivity pa = removed.get(r); 12103 Slog.w(TAG, "Removing dangling preferred activity: " 12104 + pa.mPref.mComponent); 12105 pir.removeFilter(pa); 12106 } 12107 mSettings.writePackageRestrictionsLPr( 12108 mSettings.mPreferredActivities.keyAt(i)); 12109 } 12110 } 12111 } 12112 sUserManager.systemReady(); 12113 } 12114 12115 @Override 12116 public boolean isSafeMode() { 12117 return mSafeMode; 12118 } 12119 12120 @Override 12121 public boolean hasSystemUidErrors() { 12122 return mHasSystemUidErrors; 12123 } 12124 12125 static String arrayToString(int[] array) { 12126 StringBuffer buf = new StringBuffer(128); 12127 buf.append('['); 12128 if (array != null) { 12129 for (int i=0; i<array.length; i++) { 12130 if (i > 0) buf.append(", "); 12131 buf.append(array[i]); 12132 } 12133 } 12134 buf.append(']'); 12135 return buf.toString(); 12136 } 12137 12138 static class DumpState { 12139 public static final int DUMP_LIBS = 1 << 0; 12140 public static final int DUMP_FEATURES = 1 << 1; 12141 public static final int DUMP_RESOLVERS = 1 << 2; 12142 public static final int DUMP_PERMISSIONS = 1 << 3; 12143 public static final int DUMP_PACKAGES = 1 << 4; 12144 public static final int DUMP_SHARED_USERS = 1 << 5; 12145 public static final int DUMP_MESSAGES = 1 << 6; 12146 public static final int DUMP_PROVIDERS = 1 << 7; 12147 public static final int DUMP_VERIFIERS = 1 << 8; 12148 public static final int DUMP_PREFERRED = 1 << 9; 12149 public static final int DUMP_PREFERRED_XML = 1 << 10; 12150 public static final int DUMP_KEYSETS = 1 << 11; 12151 public static final int DUMP_VERSION = 1 << 12; 12152 public static final int DUMP_INSTALLS = 1 << 13; 12153 12154 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12155 12156 private int mTypes; 12157 12158 private int mOptions; 12159 12160 private boolean mTitlePrinted; 12161 12162 private SharedUserSetting mSharedUser; 12163 12164 public boolean isDumping(int type) { 12165 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12166 return true; 12167 } 12168 12169 return (mTypes & type) != 0; 12170 } 12171 12172 public void setDump(int type) { 12173 mTypes |= type; 12174 } 12175 12176 public boolean isOptionEnabled(int option) { 12177 return (mOptions & option) != 0; 12178 } 12179 12180 public void setOptionEnabled(int option) { 12181 mOptions |= option; 12182 } 12183 12184 public boolean onTitlePrinted() { 12185 final boolean printed = mTitlePrinted; 12186 mTitlePrinted = true; 12187 return printed; 12188 } 12189 12190 public boolean getTitlePrinted() { 12191 return mTitlePrinted; 12192 } 12193 12194 public void setTitlePrinted(boolean enabled) { 12195 mTitlePrinted = enabled; 12196 } 12197 12198 public SharedUserSetting getSharedUser() { 12199 return mSharedUser; 12200 } 12201 12202 public void setSharedUser(SharedUserSetting user) { 12203 mSharedUser = user; 12204 } 12205 } 12206 12207 @Override 12208 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12209 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12210 != PackageManager.PERMISSION_GRANTED) { 12211 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12212 + Binder.getCallingPid() 12213 + ", uid=" + Binder.getCallingUid() 12214 + " without permission " 12215 + android.Manifest.permission.DUMP); 12216 return; 12217 } 12218 12219 DumpState dumpState = new DumpState(); 12220 boolean fullPreferred = false; 12221 boolean checkin = false; 12222 12223 String packageName = null; 12224 12225 int opti = 0; 12226 while (opti < args.length) { 12227 String opt = args[opti]; 12228 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12229 break; 12230 } 12231 opti++; 12232 if ("-a".equals(opt)) { 12233 // Right now we only know how to print all. 12234 } else if ("-h".equals(opt)) { 12235 pw.println("Package manager dump options:"); 12236 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12237 pw.println(" --checkin: dump for a checkin"); 12238 pw.println(" -f: print details of intent filters"); 12239 pw.println(" -h: print this help"); 12240 pw.println(" cmd may be one of:"); 12241 pw.println(" l[ibraries]: list known shared libraries"); 12242 pw.println(" f[ibraries]: list device features"); 12243 pw.println(" k[eysets]: print known keysets"); 12244 pw.println(" r[esolvers]: dump intent resolvers"); 12245 pw.println(" perm[issions]: dump permissions"); 12246 pw.println(" pref[erred]: print preferred package settings"); 12247 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12248 pw.println(" prov[iders]: dump content providers"); 12249 pw.println(" p[ackages]: dump installed packages"); 12250 pw.println(" s[hared-users]: dump shared user IDs"); 12251 pw.println(" m[essages]: print collected runtime messages"); 12252 pw.println(" v[erifiers]: print package verifier info"); 12253 pw.println(" version: print database version info"); 12254 pw.println(" write: write current settings now"); 12255 pw.println(" <package.name>: info about given package"); 12256 pw.println(" installs: details about install sessions"); 12257 return; 12258 } else if ("--checkin".equals(opt)) { 12259 checkin = true; 12260 } else if ("-f".equals(opt)) { 12261 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12262 } else { 12263 pw.println("Unknown argument: " + opt + "; use -h for help"); 12264 } 12265 } 12266 12267 // Is the caller requesting to dump a particular piece of data? 12268 if (opti < args.length) { 12269 String cmd = args[opti]; 12270 opti++; 12271 // Is this a package name? 12272 if ("android".equals(cmd) || cmd.contains(".")) { 12273 packageName = cmd; 12274 // When dumping a single package, we always dump all of its 12275 // filter information since the amount of data will be reasonable. 12276 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12277 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12278 dumpState.setDump(DumpState.DUMP_LIBS); 12279 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12280 dumpState.setDump(DumpState.DUMP_FEATURES); 12281 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12282 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12283 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12284 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12285 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12286 dumpState.setDump(DumpState.DUMP_PREFERRED); 12287 } else if ("preferred-xml".equals(cmd)) { 12288 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12289 if (opti < args.length && "--full".equals(args[opti])) { 12290 fullPreferred = true; 12291 opti++; 12292 } 12293 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12294 dumpState.setDump(DumpState.DUMP_PACKAGES); 12295 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12296 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12297 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12298 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12299 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12300 dumpState.setDump(DumpState.DUMP_MESSAGES); 12301 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12302 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12303 } else if ("version".equals(cmd)) { 12304 dumpState.setDump(DumpState.DUMP_VERSION); 12305 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12306 dumpState.setDump(DumpState.DUMP_KEYSETS); 12307 } else if ("write".equals(cmd)) { 12308 synchronized (mPackages) { 12309 mSettings.writeLPr(); 12310 pw.println("Settings written."); 12311 return; 12312 } 12313 } else if ("installs".equals(cmd)) { 12314 dumpState.setDump(DumpState.DUMP_INSTALLS); 12315 } 12316 } 12317 12318 if (checkin) { 12319 pw.println("vers,1"); 12320 } 12321 12322 // reader 12323 synchronized (mPackages) { 12324 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12325 if (!checkin) { 12326 if (dumpState.onTitlePrinted()) 12327 pw.println(); 12328 pw.println("Database versions:"); 12329 pw.print(" SDK Version:"); 12330 pw.print(" internal="); 12331 pw.print(mSettings.mInternalSdkPlatform); 12332 pw.print(" external="); 12333 pw.println(mSettings.mExternalSdkPlatform); 12334 pw.print(" DB Version:"); 12335 pw.print(" internal="); 12336 pw.print(mSettings.mInternalDatabaseVersion); 12337 pw.print(" external="); 12338 pw.println(mSettings.mExternalDatabaseVersion); 12339 } 12340 } 12341 12342 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12343 if (!checkin) { 12344 if (dumpState.onTitlePrinted()) 12345 pw.println(); 12346 pw.println("Verifiers:"); 12347 pw.print(" Required: "); 12348 pw.print(mRequiredVerifierPackage); 12349 pw.print(" (uid="); 12350 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12351 pw.println(")"); 12352 } else if (mRequiredVerifierPackage != null) { 12353 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12354 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12355 } 12356 } 12357 12358 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12359 boolean printedHeader = false; 12360 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12361 while (it.hasNext()) { 12362 String name = it.next(); 12363 SharedLibraryEntry ent = mSharedLibraries.get(name); 12364 if (!checkin) { 12365 if (!printedHeader) { 12366 if (dumpState.onTitlePrinted()) 12367 pw.println(); 12368 pw.println("Libraries:"); 12369 printedHeader = true; 12370 } 12371 pw.print(" "); 12372 } else { 12373 pw.print("lib,"); 12374 } 12375 pw.print(name); 12376 if (!checkin) { 12377 pw.print(" -> "); 12378 } 12379 if (ent.path != null) { 12380 if (!checkin) { 12381 pw.print("(jar) "); 12382 pw.print(ent.path); 12383 } else { 12384 pw.print(",jar,"); 12385 pw.print(ent.path); 12386 } 12387 } else { 12388 if (!checkin) { 12389 pw.print("(apk) "); 12390 pw.print(ent.apk); 12391 } else { 12392 pw.print(",apk,"); 12393 pw.print(ent.apk); 12394 } 12395 } 12396 pw.println(); 12397 } 12398 } 12399 12400 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12401 if (dumpState.onTitlePrinted()) 12402 pw.println(); 12403 if (!checkin) { 12404 pw.println("Features:"); 12405 } 12406 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12407 while (it.hasNext()) { 12408 String name = it.next(); 12409 if (!checkin) { 12410 pw.print(" "); 12411 } else { 12412 pw.print("feat,"); 12413 } 12414 pw.println(name); 12415 } 12416 } 12417 12418 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12419 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12420 : "Activity Resolver Table:", " ", packageName, 12421 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12422 dumpState.setTitlePrinted(true); 12423 } 12424 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12425 : "Receiver Resolver Table:", " ", packageName, 12426 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12427 dumpState.setTitlePrinted(true); 12428 } 12429 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12430 : "Service Resolver Table:", " ", packageName, 12431 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12432 dumpState.setTitlePrinted(true); 12433 } 12434 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12435 : "Provider Resolver Table:", " ", packageName, 12436 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12437 dumpState.setTitlePrinted(true); 12438 } 12439 } 12440 12441 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12442 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12443 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12444 int user = mSettings.mPreferredActivities.keyAt(i); 12445 if (pir.dump(pw, 12446 dumpState.getTitlePrinted() 12447 ? "\nPreferred Activities User " + user + ":" 12448 : "Preferred Activities User " + user + ":", " ", 12449 packageName, true)) { 12450 dumpState.setTitlePrinted(true); 12451 } 12452 } 12453 } 12454 12455 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12456 pw.flush(); 12457 FileOutputStream fout = new FileOutputStream(fd); 12458 BufferedOutputStream str = new BufferedOutputStream(fout); 12459 XmlSerializer serializer = new FastXmlSerializer(); 12460 try { 12461 serializer.setOutput(str, "utf-8"); 12462 serializer.startDocument(null, true); 12463 serializer.setFeature( 12464 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12465 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12466 serializer.endDocument(); 12467 serializer.flush(); 12468 } catch (IllegalArgumentException e) { 12469 pw.println("Failed writing: " + e); 12470 } catch (IllegalStateException e) { 12471 pw.println("Failed writing: " + e); 12472 } catch (IOException e) { 12473 pw.println("Failed writing: " + e); 12474 } 12475 } 12476 12477 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12478 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12479 if (packageName == null) { 12480 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12481 if (iperm == 0) { 12482 if (dumpState.onTitlePrinted()) 12483 pw.println(); 12484 pw.println("AppOp Permissions:"); 12485 } 12486 pw.print(" AppOp Permission "); 12487 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12488 pw.println(":"); 12489 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12490 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12491 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12492 } 12493 } 12494 } 12495 } 12496 12497 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12498 boolean printedSomething = false; 12499 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12500 if (packageName != null && !packageName.equals(p.info.packageName)) { 12501 continue; 12502 } 12503 if (!printedSomething) { 12504 if (dumpState.onTitlePrinted()) 12505 pw.println(); 12506 pw.println("Registered ContentProviders:"); 12507 printedSomething = true; 12508 } 12509 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12510 pw.print(" "); pw.println(p.toString()); 12511 } 12512 printedSomething = false; 12513 for (Map.Entry<String, PackageParser.Provider> entry : 12514 mProvidersByAuthority.entrySet()) { 12515 PackageParser.Provider p = entry.getValue(); 12516 if (packageName != null && !packageName.equals(p.info.packageName)) { 12517 continue; 12518 } 12519 if (!printedSomething) { 12520 if (dumpState.onTitlePrinted()) 12521 pw.println(); 12522 pw.println("ContentProvider Authorities:"); 12523 printedSomething = true; 12524 } 12525 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12526 pw.print(" "); pw.println(p.toString()); 12527 if (p.info != null && p.info.applicationInfo != null) { 12528 final String appInfo = p.info.applicationInfo.toString(); 12529 pw.print(" applicationInfo="); pw.println(appInfo); 12530 } 12531 } 12532 } 12533 12534 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12535 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12536 } 12537 12538 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12539 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12540 } 12541 12542 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12543 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12544 } 12545 12546 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) { 12547 if (dumpState.onTitlePrinted()) pw.println(); 12548 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12549 } 12550 12551 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12552 if (dumpState.onTitlePrinted()) pw.println(); 12553 mSettings.dumpReadMessagesLPr(pw, dumpState); 12554 12555 pw.println(); 12556 pw.println("Package warning messages:"); 12557 final File fname = getSettingsProblemFile(); 12558 FileInputStream in = null; 12559 try { 12560 in = new FileInputStream(fname); 12561 final int avail = in.available(); 12562 final byte[] data = new byte[avail]; 12563 in.read(data); 12564 pw.print(new String(data)); 12565 } catch (FileNotFoundException e) { 12566 } catch (IOException e) { 12567 } finally { 12568 if (in != null) { 12569 try { 12570 in.close(); 12571 } catch (IOException e) { 12572 } 12573 } 12574 } 12575 } 12576 } 12577 } 12578 12579 // ------- apps on sdcard specific code ------- 12580 static final boolean DEBUG_SD_INSTALL = false; 12581 12582 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12583 12584 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12585 12586 private boolean mMediaMounted = false; 12587 12588 private String getEncryptKey() { 12589 try { 12590 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12591 SD_ENCRYPTION_KEYSTORE_NAME); 12592 if (sdEncKey == null) { 12593 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12594 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12595 if (sdEncKey == null) { 12596 Slog.e(TAG, "Failed to create encryption keys"); 12597 return null; 12598 } 12599 } 12600 return sdEncKey; 12601 } catch (NoSuchAlgorithmException nsae) { 12602 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12603 return null; 12604 } catch (IOException ioe) { 12605 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12606 return null; 12607 } 12608 12609 } 12610 12611 /* package */static String getTempContainerId() { 12612 int tmpIdx = 1; 12613 String list[] = PackageHelper.getSecureContainerList(); 12614 if (list != null) { 12615 for (final String name : list) { 12616 // Ignore null and non-temporary container entries 12617 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12618 continue; 12619 } 12620 12621 String subStr = name.substring(mTempContainerPrefix.length()); 12622 try { 12623 int cid = Integer.parseInt(subStr); 12624 if (cid >= tmpIdx) { 12625 tmpIdx = cid + 1; 12626 } 12627 } catch (NumberFormatException e) { 12628 } 12629 } 12630 } 12631 return mTempContainerPrefix + tmpIdx; 12632 } 12633 12634 /* 12635 * Update media status on PackageManager. 12636 */ 12637 @Override 12638 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12639 int callingUid = Binder.getCallingUid(); 12640 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12641 throw new SecurityException("Media status can only be updated by the system"); 12642 } 12643 // reader; this apparently protects mMediaMounted, but should probably 12644 // be a different lock in that case. 12645 synchronized (mPackages) { 12646 Log.i(TAG, "Updating external media status from " 12647 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12648 + (mediaStatus ? "mounted" : "unmounted")); 12649 if (DEBUG_SD_INSTALL) 12650 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12651 + ", mMediaMounted=" + mMediaMounted); 12652 if (mediaStatus == mMediaMounted) { 12653 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12654 : 0, -1); 12655 mHandler.sendMessage(msg); 12656 return; 12657 } 12658 mMediaMounted = mediaStatus; 12659 } 12660 // Queue up an async operation since the package installation may take a 12661 // little while. 12662 mHandler.post(new Runnable() { 12663 public void run() { 12664 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12665 } 12666 }); 12667 } 12668 12669 /** 12670 * Called by MountService when the initial ASECs to scan are available. 12671 * Should block until all the ASEC containers are finished being scanned. 12672 */ 12673 public void scanAvailableAsecs() { 12674 updateExternalMediaStatusInner(true, false, false); 12675 if (mShouldRestoreconData) { 12676 SELinuxMMAC.setRestoreconDone(); 12677 mShouldRestoreconData = false; 12678 } 12679 } 12680 12681 /* 12682 * Collect information of applications on external media, map them against 12683 * existing containers and update information based on current mount status. 12684 * Please note that we always have to report status if reportStatus has been 12685 * set to true especially when unloading packages. 12686 */ 12687 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12688 boolean externalStorage) { 12689 // Collection of uids 12690 int uidArr[] = null; 12691 // Collection of stale containers 12692 HashSet<String> removeCids = new HashSet<String>(); 12693 // Collection of packages on external media with valid containers. 12694 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12695 // Get list of secure containers. 12696 final String list[] = PackageHelper.getSecureContainerList(); 12697 if (list == null || list.length == 0) { 12698 Log.i(TAG, "No secure containers on sdcard"); 12699 } else { 12700 // Process list of secure containers and categorize them 12701 // as active or stale based on their package internal state. 12702 int uidList[] = new int[list.length]; 12703 int num = 0; 12704 // reader 12705 synchronized (mPackages) { 12706 for (String cid : list) { 12707 if (DEBUG_SD_INSTALL) 12708 Log.i(TAG, "Processing container " + cid); 12709 String pkgName = getAsecPackageName(cid); 12710 if (pkgName == null) { 12711 if (DEBUG_SD_INSTALL) 12712 Log.i(TAG, "Container : " + cid + " stale"); 12713 removeCids.add(cid); 12714 continue; 12715 } 12716 if (DEBUG_SD_INSTALL) 12717 Log.i(TAG, "Looking for pkg : " + pkgName); 12718 12719 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12720 if (ps == null) { 12721 Log.i(TAG, "Deleting container with no matching settings " + cid); 12722 removeCids.add(cid); 12723 continue; 12724 } 12725 12726 /* 12727 * Skip packages that are not external if we're unmounting 12728 * external storage. 12729 */ 12730 if (externalStorage && !isMounted && !isExternal(ps)) { 12731 continue; 12732 } 12733 12734 final AsecInstallArgs args = new AsecInstallArgs(cid, 12735 getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps)); 12736 // The package status is changed only if the code path 12737 // matches between settings and the container id. 12738 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12739 if (DEBUG_SD_INSTALL) { 12740 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12741 + " at code path: " + ps.codePathString); 12742 } 12743 12744 // We do have a valid package installed on sdcard 12745 processCids.put(args, ps.codePathString); 12746 final int uid = ps.appId; 12747 if (uid != -1) { 12748 uidList[num++] = uid; 12749 } 12750 } else { 12751 Log.i(TAG, "Deleting stale container for " + cid); 12752 removeCids.add(cid); 12753 } 12754 } 12755 } 12756 12757 if (num > 0) { 12758 // Sort uid list 12759 Arrays.sort(uidList, 0, num); 12760 // Throw away duplicates 12761 uidArr = new int[num]; 12762 uidArr[0] = uidList[0]; 12763 int di = 0; 12764 for (int i = 1; i < num; i++) { 12765 if (uidList[i - 1] != uidList[i]) { 12766 uidArr[di++] = uidList[i]; 12767 } 12768 } 12769 } 12770 } 12771 // Process packages with valid entries. 12772 if (isMounted) { 12773 if (DEBUG_SD_INSTALL) 12774 Log.i(TAG, "Loading packages"); 12775 loadMediaPackages(processCids, uidArr, removeCids); 12776 startCleaningPackages(); 12777 } else { 12778 if (DEBUG_SD_INSTALL) 12779 Log.i(TAG, "Unloading packages"); 12780 unloadMediaPackages(processCids, uidArr, reportStatus); 12781 } 12782 } 12783 12784 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12785 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12786 int size = pkgList.size(); 12787 if (size > 0) { 12788 // Send broadcasts here 12789 Bundle extras = new Bundle(); 12790 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12791 .toArray(new String[size])); 12792 if (uidArr != null) { 12793 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12794 } 12795 if (replacing) { 12796 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12797 } 12798 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12799 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12800 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12801 } 12802 } 12803 12804 /* 12805 * Look at potentially valid container ids from processCids If package 12806 * information doesn't match the one on record or package scanning fails, 12807 * the cid is added to list of removeCids. We currently don't delete stale 12808 * containers. 12809 */ 12810 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12811 HashSet<String> removeCids) { 12812 ArrayList<String> pkgList = new ArrayList<String>(); 12813 Set<AsecInstallArgs> keys = processCids.keySet(); 12814 boolean doGc = false; 12815 for (AsecInstallArgs args : keys) { 12816 String codePath = processCids.get(args); 12817 if (DEBUG_SD_INSTALL) 12818 Log.i(TAG, "Loading container : " + args.cid); 12819 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12820 try { 12821 // Make sure there are no container errors first. 12822 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12823 Slog.e(TAG, "Failed to mount cid : " + args.cid 12824 + " when installing from sdcard"); 12825 continue; 12826 } 12827 // Check code path here. 12828 if (codePath == null || !codePath.equals(args.getCodePath())) { 12829 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12830 + " does not match one in settings " + codePath); 12831 continue; 12832 } 12833 // Parse package 12834 int parseFlags = mDefParseFlags; 12835 if (args.isExternal()) { 12836 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12837 } 12838 if (args.isFwdLocked()) { 12839 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12840 } 12841 12842 doGc = true; 12843 synchronized (mInstallLock) { 12844 PackageParser.Package pkg = null; 12845 try { 12846 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null, null); 12847 } catch (PackageManagerException e) { 12848 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12849 } 12850 // Scan the package 12851 if (pkg != null) { 12852 /* 12853 * TODO why is the lock being held? doPostInstall is 12854 * called in other places without the lock. This needs 12855 * to be straightened out. 12856 */ 12857 // writer 12858 synchronized (mPackages) { 12859 retCode = PackageManager.INSTALL_SUCCEEDED; 12860 pkgList.add(pkg.packageName); 12861 // Post process args 12862 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12863 pkg.applicationInfo.uid); 12864 } 12865 } else { 12866 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12867 } 12868 } 12869 12870 } finally { 12871 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12872 // Don't destroy container here. Wait till gc clears things 12873 // up. 12874 removeCids.add(args.cid); 12875 } 12876 } 12877 } 12878 // writer 12879 synchronized (mPackages) { 12880 // If the platform SDK has changed since the last time we booted, 12881 // we need to re-grant app permission to catch any new ones that 12882 // appear. This is really a hack, and means that apps can in some 12883 // cases get permissions that the user didn't initially explicitly 12884 // allow... it would be nice to have some better way to handle 12885 // this situation. 12886 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12887 if (regrantPermissions) 12888 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12889 + mSdkVersion + "; regranting permissions for external storage"); 12890 mSettings.mExternalSdkPlatform = mSdkVersion; 12891 12892 // Make sure group IDs have been assigned, and any permission 12893 // changes in other apps are accounted for 12894 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12895 | (regrantPermissions 12896 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12897 : 0)); 12898 12899 mSettings.updateExternalDatabaseVersion(); 12900 12901 // can downgrade to reader 12902 // Persist settings 12903 mSettings.writeLPr(); 12904 } 12905 // Send a broadcast to let everyone know we are done processing 12906 if (pkgList.size() > 0) { 12907 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12908 } 12909 // Force gc to avoid any stale parser references that we might have. 12910 if (doGc) { 12911 Runtime.getRuntime().gc(); 12912 } 12913 // List stale containers and destroy stale temporary containers. 12914 if (removeCids != null) { 12915 for (String cid : removeCids) { 12916 if (cid.startsWith(mTempContainerPrefix)) { 12917 Log.i(TAG, "Destroying stale temporary container " + cid); 12918 PackageHelper.destroySdDir(cid); 12919 } else { 12920 Log.w(TAG, "Container " + cid + " is stale"); 12921 } 12922 } 12923 } 12924 } 12925 12926 /* 12927 * Utility method to unload a list of specified containers 12928 */ 12929 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12930 // Just unmount all valid containers. 12931 for (AsecInstallArgs arg : cidArgs) { 12932 synchronized (mInstallLock) { 12933 arg.doPostDeleteLI(false); 12934 } 12935 } 12936 } 12937 12938 /* 12939 * Unload packages mounted on external media. This involves deleting package 12940 * data from internal structures, sending broadcasts about diabled packages, 12941 * gc'ing to free up references, unmounting all secure containers 12942 * corresponding to packages on external media, and posting a 12943 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12944 * that we always have to post this message if status has been requested no 12945 * matter what. 12946 */ 12947 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12948 final boolean reportStatus) { 12949 if (DEBUG_SD_INSTALL) 12950 Log.i(TAG, "unloading media packages"); 12951 ArrayList<String> pkgList = new ArrayList<String>(); 12952 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12953 final Set<AsecInstallArgs> keys = processCids.keySet(); 12954 for (AsecInstallArgs args : keys) { 12955 String pkgName = args.getPackageName(); 12956 if (DEBUG_SD_INSTALL) 12957 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12958 // Delete package internally 12959 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12960 synchronized (mInstallLock) { 12961 boolean res = deletePackageLI(pkgName, null, false, null, null, 12962 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12963 if (res) { 12964 pkgList.add(pkgName); 12965 } else { 12966 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12967 failedList.add(args); 12968 } 12969 } 12970 } 12971 12972 // reader 12973 synchronized (mPackages) { 12974 // We didn't update the settings after removing each package; 12975 // write them now for all packages. 12976 mSettings.writeLPr(); 12977 } 12978 12979 // We have to absolutely send UPDATED_MEDIA_STATUS only 12980 // after confirming that all the receivers processed the ordered 12981 // broadcast when packages get disabled, force a gc to clean things up. 12982 // and unload all the containers. 12983 if (pkgList.size() > 0) { 12984 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12985 new IIntentReceiver.Stub() { 12986 public void performReceive(Intent intent, int resultCode, String data, 12987 Bundle extras, boolean ordered, boolean sticky, 12988 int sendingUser) throws RemoteException { 12989 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12990 reportStatus ? 1 : 0, 1, keys); 12991 mHandler.sendMessage(msg); 12992 } 12993 }); 12994 } else { 12995 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12996 keys); 12997 mHandler.sendMessage(msg); 12998 } 12999 } 13000 13001 /** Binder call */ 13002 @Override 13003 public void movePackage(final String packageName, final IPackageMoveObserver observer, 13004 final int flags) { 13005 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 13006 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 13007 int returnCode = PackageManager.MOVE_SUCCEEDED; 13008 int currFlags = 0; 13009 int newFlags = 0; 13010 // reader 13011 synchronized (mPackages) { 13012 PackageParser.Package pkg = mPackages.get(packageName); 13013 if (pkg == null) { 13014 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13015 } else { 13016 // Disable moving fwd locked apps and system packages 13017 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 13018 Slog.w(TAG, "Cannot move system application"); 13019 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13020 } else if (pkg.mOperationPending) { 13021 Slog.w(TAG, "Attempt to move package which has pending operations"); 13022 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13023 } else { 13024 // Find install location first 13025 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13026 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13027 Slog.w(TAG, "Ambigous flags specified for move location."); 13028 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13029 } else { 13030 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 13031 : PackageManager.INSTALL_INTERNAL; 13032 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 13033 : PackageManager.INSTALL_INTERNAL; 13034 13035 if (newFlags == currFlags) { 13036 Slog.w(TAG, "No move required. Trying to move to same location"); 13037 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13038 } else { 13039 if (isForwardLocked(pkg)) { 13040 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13041 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13042 } 13043 } 13044 } 13045 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13046 pkg.mOperationPending = true; 13047 } 13048 } 13049 } 13050 13051 /* 13052 * TODO this next block probably shouldn't be inside the lock. We 13053 * can't guarantee these won't change after this is fired off 13054 * anyway. 13055 */ 13056 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13057 processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false), 13058 returnCode); 13059 } else { 13060 Message msg = mHandler.obtainMessage(INIT_COPY); 13061 final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 13062 final boolean multiArch = isMultiArch(pkg.applicationInfo); 13063 InstallArgs srcArgs = createInstallArgsForExisting(currFlags, 13064 pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(), 13065 pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch); 13066 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 13067 instructionSets, pkg.applicationInfo.uid, user, multiArch); 13068 msg.obj = mp; 13069 mHandler.sendMessage(msg); 13070 } 13071 } 13072 } 13073 13074 private void processPendingMove(final MoveParams mp, final int currentStatus) { 13075 // Queue up an async operation since the package deletion may take a 13076 // little while. 13077 mHandler.post(new Runnable() { 13078 public void run() { 13079 // TODO fix this; this does nothing. 13080 mHandler.removeCallbacks(this); 13081 int returnCode = currentStatus; 13082 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 13083 int uidArr[] = null; 13084 ArrayList<String> pkgList = null; 13085 synchronized (mPackages) { 13086 PackageParser.Package pkg = mPackages.get(mp.packageName); 13087 if (pkg == null) { 13088 Slog.w(TAG, " Package " + mp.packageName 13089 + " doesn't exist. Aborting move"); 13090 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13091 } else if (!mp.srcArgs.getCodePath().equals( 13092 pkg.applicationInfo.getCodePath())) { 13093 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 13094 + mp.srcArgs.getCodePath() + " to " 13095 + pkg.applicationInfo.getCodePath() 13096 + " Aborting move and returning error"); 13097 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13098 } else { 13099 uidArr = new int[] { 13100 pkg.applicationInfo.uid 13101 }; 13102 pkgList = new ArrayList<String>(); 13103 pkgList.add(mp.packageName); 13104 } 13105 } 13106 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13107 // Send resources unavailable broadcast 13108 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 13109 // Update package code and resource paths 13110 synchronized (mInstallLock) { 13111 synchronized (mPackages) { 13112 PackageParser.Package pkg = mPackages.get(mp.packageName); 13113 // Recheck for package again. 13114 if (pkg == null) { 13115 Slog.w(TAG, " Package " + mp.packageName 13116 + " doesn't exist. Aborting move"); 13117 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13118 } else if (!mp.srcArgs.getCodePath().equals( 13119 pkg.applicationInfo.getCodePath())) { 13120 Slog.w(TAG, "Package " + mp.packageName 13121 + " code path changed from " + mp.srcArgs.getCodePath() 13122 + " to " + pkg.applicationInfo.getCodePath() 13123 + " Aborting move and returning error"); 13124 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13125 } else { 13126 final String oldCodePath = pkg.codePath; 13127 final String newCodePath = mp.targetArgs.getCodePath(); 13128 final String newResPath = mp.targetArgs.getResourcePath(); 13129 // TODO: This assumes the new style of installation. 13130 // should we look at legacyNativeLibraryPath ? 13131 final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath(); 13132 final File newNativeDir = new File(newNativeRoot); 13133 13134 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 13135 // TODO(multiArch): Fix this so that it looks at the existing 13136 // recorded CPU abis from the package. There's no need for a separate 13137 // round of ABI scanning here. 13138 NativeLibraryHelper.Handle handle = null; 13139 try { 13140 handle = NativeLibraryHelper.Handle.create( 13141 new File(newCodePath)); 13142 final int abi = NativeLibraryHelper.findSupportedAbi( 13143 handle, Build.SUPPORTED_ABIS); 13144 if (abi >= 0) { 13145 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 13146 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 13147 } 13148 } catch (IOException ioe) { 13149 Slog.w(TAG, "Unable to extract native libs for package :" 13150 + mp.packageName, ioe); 13151 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13152 } finally { 13153 IoUtils.closeQuietly(handle); 13154 } 13155 } 13156 13157 final int[] users = sUserManager.getUserIds(); 13158 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13159 for (int user : users) { 13160 // TODO(multiArch): Fix this so that it links to the 13161 // correct directory. We're currently pointing to root. but we 13162 // must point to the arch specific subdirectory (if applicable). 13163 // 13164 // TODO(multiArch): Bogus reference to nativeLibraryDir. 13165 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 13166 newNativeRoot, user) < 0) { 13167 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13168 } 13169 } 13170 } 13171 13172 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13173 pkg.codePath = newCodePath; 13174 pkg.baseCodePath = newCodePath; 13175 // Move dex files around 13176 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 13177 // Moving of dex files failed. Set 13178 // error code and abort move. 13179 pkg.codePath = oldCodePath; 13180 pkg.baseCodePath = oldCodePath; 13181 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13182 } 13183 } 13184 13185 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13186 pkg.applicationInfo.setCodePath(newCodePath); 13187 pkg.applicationInfo.setBaseCodePath(newCodePath); 13188 pkg.applicationInfo.setSplitCodePaths(null); 13189 pkg.applicationInfo.setResourcePath(newResPath); 13190 pkg.applicationInfo.setBaseResourcePath(newResPath); 13191 pkg.applicationInfo.setSplitResourcePaths(null); 13192 13193 PackageSetting ps = (PackageSetting) pkg.mExtras; 13194 ps.codePath = new File(pkg.applicationInfo.getCodePath()); 13195 ps.codePathString = ps.codePath.getPath(); 13196 ps.resourcePath = new File(pkg.applicationInfo.getResourcePath()); 13197 ps.resourcePathString = ps.resourcePath.getPath(); 13198 13199 // Note that we don't have to recalculate the primary and secondary 13200 // CPU ABIs because they must already have been calculated during the 13201 // initial install of the app. 13202 ps.legacyNativeLibraryPathString = null; 13203 13204 // Set the application info flag 13205 // correctly. 13206 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 13207 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13208 } else { 13209 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13210 } 13211 ps.setFlags(pkg.applicationInfo.flags); 13212 mAppDirs.remove(oldCodePath); 13213 mAppDirs.put(newCodePath, pkg); 13214 // Persist settings 13215 mSettings.writeLPr(); 13216 } 13217 } 13218 } 13219 } 13220 // Send resources available broadcast 13221 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13222 } 13223 } 13224 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13225 // Clean up failed installation 13226 if (mp.targetArgs != null) { 13227 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 13228 -1); 13229 } 13230 } else { 13231 // Force a gc to clear things up. 13232 Runtime.getRuntime().gc(); 13233 // Delete older code 13234 synchronized (mInstallLock) { 13235 mp.srcArgs.doPostDeleteLI(true); 13236 } 13237 } 13238 13239 // Allow more operations on this file if we didn't fail because 13240 // an operation was already pending for this package. 13241 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 13242 synchronized (mPackages) { 13243 PackageParser.Package pkg = mPackages.get(mp.packageName); 13244 if (pkg != null) { 13245 pkg.mOperationPending = false; 13246 } 13247 } 13248 } 13249 13250 IPackageMoveObserver observer = mp.observer; 13251 if (observer != null) { 13252 try { 13253 observer.packageMoved(mp.packageName, returnCode); 13254 } catch (RemoteException e) { 13255 Log.i(TAG, "Observer no longer exists."); 13256 } 13257 } 13258 } 13259 }); 13260 } 13261 13262 @Override 13263 public boolean setInstallLocation(int loc) { 13264 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13265 null); 13266 if (getInstallLocation() == loc) { 13267 return true; 13268 } 13269 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13270 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13271 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13272 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13273 return true; 13274 } 13275 return false; 13276 } 13277 13278 @Override 13279 public int getInstallLocation() { 13280 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13281 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13282 PackageHelper.APP_INSTALL_AUTO); 13283 } 13284 13285 /** Called by UserManagerService */ 13286 void cleanUpUserLILPw(int userHandle) { 13287 mDirtyUsers.remove(userHandle); 13288 mSettings.removeUserLPw(userHandle); 13289 mPendingBroadcasts.remove(userHandle); 13290 if (mInstaller != null) { 13291 // Technically, we shouldn't be doing this with the package lock 13292 // held. However, this is very rare, and there is already so much 13293 // other disk I/O going on, that we'll let it slide for now. 13294 mInstaller.removeUserDataDirs(userHandle); 13295 } 13296 mUserNeedsBadging.delete(userHandle); 13297 } 13298 13299 /** Called by UserManagerService */ 13300 void createNewUserLILPw(int userHandle, File path) { 13301 if (mInstaller != null) { 13302 mInstaller.createUserConfig(userHandle); 13303 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13304 } 13305 } 13306 13307 @Override 13308 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13309 mContext.enforceCallingOrSelfPermission( 13310 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13311 "Only package verification agents can read the verifier device identity"); 13312 13313 synchronized (mPackages) { 13314 return mSettings.getVerifierDeviceIdentityLPw(); 13315 } 13316 } 13317 13318 @Override 13319 public void setPermissionEnforced(String permission, boolean enforced) { 13320 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13321 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13322 synchronized (mPackages) { 13323 if (mSettings.mReadExternalStorageEnforced == null 13324 || mSettings.mReadExternalStorageEnforced != enforced) { 13325 mSettings.mReadExternalStorageEnforced = enforced; 13326 mSettings.writeLPr(); 13327 } 13328 } 13329 // kill any non-foreground processes so we restart them and 13330 // grant/revoke the GID. 13331 final IActivityManager am = ActivityManagerNative.getDefault(); 13332 if (am != null) { 13333 final long token = Binder.clearCallingIdentity(); 13334 try { 13335 am.killProcessesBelowForeground("setPermissionEnforcement"); 13336 } catch (RemoteException e) { 13337 } finally { 13338 Binder.restoreCallingIdentity(token); 13339 } 13340 } 13341 } else { 13342 throw new IllegalArgumentException("No selective enforcement for " + permission); 13343 } 13344 } 13345 13346 @Override 13347 @Deprecated 13348 public boolean isPermissionEnforced(String permission) { 13349 return true; 13350 } 13351 13352 @Override 13353 public boolean isStorageLow() { 13354 final long token = Binder.clearCallingIdentity(); 13355 try { 13356 final DeviceStorageMonitorInternal 13357 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13358 if (dsm != null) { 13359 return dsm.isMemoryLow(); 13360 } else { 13361 return false; 13362 } 13363 } finally { 13364 Binder.restoreCallingIdentity(token); 13365 } 13366 } 13367 13368 @Override 13369 public IPackageInstaller getPackageInstaller() { 13370 return mInstallerService; 13371 } 13372 13373 private boolean userNeedsBadging(int userId) { 13374 int index = mUserNeedsBadging.indexOfKey(userId); 13375 if (index < 0) { 13376 final UserInfo userInfo; 13377 final long token = Binder.clearCallingIdentity(); 13378 try { 13379 userInfo = sUserManager.getUserInfo(userId); 13380 } finally { 13381 Binder.restoreCallingIdentity(token); 13382 } 13383 final boolean b; 13384 if (userInfo != null && userInfo.isManagedProfile()) { 13385 b = true; 13386 } else { 13387 b = false; 13388 } 13389 mUserNeedsBadging.put(userId, b); 13390 return b; 13391 } 13392 return mUserNeedsBadging.valueAt(index); 13393 } 13394 13395 @Override 13396 public KeySetHandle getKeySetByAlias(String packageName, String alias) { 13397 if (packageName == null || alias == null) { 13398 return null; 13399 } 13400 synchronized(mPackages) { 13401 final PackageParser.Package pkg = mPackages.get(packageName); 13402 if (pkg == null) { 13403 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13404 throw new IllegalArgumentException("Unknown package: " + packageName); 13405 } 13406 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13407 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13408 throw new SecurityException("May not access KeySets defined by" 13409 + " aliases in other applications."); 13410 } 13411 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13412 return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias); 13413 } 13414 } 13415 13416 @Override 13417 public KeySetHandle getSigningKeySet(String packageName) { 13418 if (packageName == null) { 13419 return null; 13420 } 13421 synchronized(mPackages) { 13422 final PackageParser.Package pkg = mPackages.get(packageName); 13423 if (pkg == null) { 13424 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13425 throw new IllegalArgumentException("Unknown package: " + packageName); 13426 } 13427 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13428 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13429 throw new SecurityException("May not access signing KeySet of other apps."); 13430 } 13431 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13432 return ksms.getSigningKeySetByPackageNameLPr(packageName); 13433 } 13434 } 13435 13436 @Override 13437 public boolean isPackageSignedByKeySet(String packageName, IBinder ks) { 13438 if (packageName == null || ks == null) { 13439 return false; 13440 } 13441 synchronized(mPackages) { 13442 final PackageParser.Package pkg = mPackages.get(packageName); 13443 if (pkg == null) { 13444 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13445 throw new IllegalArgumentException("Unknown package: " + packageName); 13446 } 13447 if (ks instanceof KeySetHandle) { 13448 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13449 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks); 13450 } 13451 return false; 13452 } 13453 } 13454 13455 @Override 13456 public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) { 13457 if (packageName == null || ks == null) { 13458 return false; 13459 } 13460 synchronized(mPackages) { 13461 final PackageParser.Package pkg = mPackages.get(packageName); 13462 if (pkg == null) { 13463 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13464 throw new IllegalArgumentException("Unknown package: " + packageName); 13465 } 13466 if (ks instanceof KeySetHandle) { 13467 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13468 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks); 13469 } 13470 return false; 13471 } 13472 } 13473} 13474