PackageManagerService.java revision e0b0bef75b66f0a87039c8f58c17b1596a2baebe
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 32import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 36import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 37import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 38import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 39import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 41import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 43import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 44import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 46import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 47import static android.content.pm.PackageParser.isApkFile; 48import static android.os.Process.PACKAGE_INFO_GID; 49import static android.os.Process.SYSTEM_UID; 50import static android.system.OsConstants.O_CREAT; 51import static android.system.OsConstants.O_RDWR; 52import static android.system.OsConstants.S_IRGRP; 53import static android.system.OsConstants.S_IROTH; 54import static android.system.OsConstants.S_IRWXU; 55import static android.system.OsConstants.S_IXGRP; 56import static android.system.OsConstants.S_IXOTH; 57import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 58import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 59import static com.android.internal.util.ArrayUtils.appendInt; 60import static com.android.internal.util.ArrayUtils.removeInt; 61 62import android.util.ArrayMap; 63 64import com.android.internal.R; 65import com.android.internal.app.IMediaContainerService; 66import com.android.internal.app.ResolverActivity; 67import com.android.internal.content.NativeLibraryHelper; 68import com.android.internal.content.PackageHelper; 69import com.android.internal.os.IParcelFileDescriptorFactory; 70import com.android.internal.util.ArrayUtils; 71import com.android.internal.util.FastPrintWriter; 72import com.android.internal.util.FastXmlSerializer; 73import com.android.internal.util.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.Log; 168import android.util.LogPrinter; 169import android.util.PrintStreamPrinter; 170import android.util.Slog; 171import android.util.SparseArray; 172import android.util.SparseBooleanArray; 173import android.view.Display; 174 175import java.io.BufferedInputStream; 176import java.io.BufferedOutputStream; 177import java.io.File; 178import java.io.FileDescriptor; 179import java.io.FileInputStream; 180import java.io.FileNotFoundException; 181import java.io.FileOutputStream; 182import java.io.FilenameFilter; 183import java.io.IOException; 184import java.io.InputStream; 185import java.io.PrintWriter; 186import java.nio.charset.StandardCharsets; 187import java.security.NoSuchAlgorithmException; 188import java.security.PublicKey; 189import java.security.cert.CertificateEncodingException; 190import java.security.cert.CertificateException; 191import java.text.SimpleDateFormat; 192import java.util.ArrayList; 193import java.util.Arrays; 194import java.util.Collection; 195import java.util.Collections; 196import java.util.Comparator; 197import java.util.Date; 198import java.util.HashMap; 199import java.util.HashSet; 200import java.util.Iterator; 201import java.util.List; 202import java.util.Map; 203import java.util.Set; 204import java.util.concurrent.atomic.AtomicBoolean; 205import java.util.concurrent.atomic.AtomicLong; 206 207import dalvik.system.DexFile; 208import dalvik.system.StaleDexCacheError; 209import dalvik.system.VMRuntime; 210 211import libcore.io.IoUtils; 212 213/** 214 * Keep track of all those .apks everywhere. 215 * 216 * This is very central to the platform's security; please run the unit 217 * tests whenever making modifications here: 218 * 219mmm frameworks/base/tests/AndroidTests 220adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 221adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 222 * 223 * {@hide} 224 */ 225public class PackageManagerService extends IPackageManager.Stub { 226 static final String TAG = "PackageManager"; 227 static final boolean DEBUG_SETTINGS = false; 228 static final boolean DEBUG_PREFERRED = false; 229 static final boolean DEBUG_UPGRADE = false; 230 private static final boolean DEBUG_INSTALL = false; 231 private static final boolean DEBUG_REMOVE = false; 232 private static final boolean DEBUG_BROADCASTS = false; 233 private static final boolean DEBUG_SHOW_INFO = false; 234 private static final boolean DEBUG_PACKAGE_INFO = false; 235 private static final boolean DEBUG_INTENT_MATCHING = false; 236 private static final boolean DEBUG_PACKAGE_SCANNING = false; 237 private static final boolean DEBUG_APP_DIR_OBSERVER = false; 238 private static final boolean DEBUG_VERIFY = false; 239 private static final boolean DEBUG_DEXOPT = false; 240 private static final boolean DEBUG_ABI_SELECTION = false; 241 242 private static final int RADIO_UID = Process.PHONE_UID; 243 private static final int LOG_UID = Process.LOG_UID; 244 private static final int NFC_UID = Process.NFC_UID; 245 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 246 private static final int SHELL_UID = Process.SHELL_UID; 247 248 // Cap the size of permission trees that 3rd party apps can define 249 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 250 251 private static final int REMOVE_EVENTS = 252 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM; 253 private static final int ADD_EVENTS = 254 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO; 255 256 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS; 257 // Suffix used during package installation when copying/moving 258 // package apks to install directory. 259 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 260 261 static final int SCAN_MONITOR = 1<<0; 262 static final int SCAN_NO_DEX = 1<<1; 263 static final int SCAN_FORCE_DEX = 1<<2; 264 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 265 static final int SCAN_NEW_INSTALL = 1<<4; 266 static final int SCAN_NO_PATHS = 1<<5; 267 static final int SCAN_UPDATE_TIME = 1<<6; 268 static final int SCAN_DEFER_DEX = 1<<7; 269 static final int SCAN_BOOTING = 1<<8; 270 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 271 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 272 273 static final int REMOVE_CHATTY = 1<<16; 274 275 /** 276 * Timeout (in milliseconds) after which the watchdog should declare that 277 * our handler thread is wedged. The usual default for such things is one 278 * minute but we sometimes do very lengthy I/O operations on this thread, 279 * such as installing multi-gigabyte applications, so ours needs to be longer. 280 */ 281 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 282 283 /** 284 * Whether verification is enabled by default. 285 */ 286 private static final boolean DEFAULT_VERIFY_ENABLE = true; 287 288 /** 289 * The default maximum time to wait for the verification agent to return in 290 * milliseconds. 291 */ 292 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 293 294 /** 295 * The default response for package verification timeout. 296 * 297 * This can be either PackageManager.VERIFICATION_ALLOW or 298 * PackageManager.VERIFICATION_REJECT. 299 */ 300 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 301 302 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 303 304 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 305 DEFAULT_CONTAINER_PACKAGE, 306 "com.android.defcontainer.DefaultContainerService"); 307 308 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 309 310 private static final String LIB_DIR_NAME = "lib"; 311 private static final String LIB64_DIR_NAME = "lib64"; 312 313 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 314 315 static final String mTempContainerPrefix = "smdl2tmp"; 316 317 private static String sPreferredInstructionSet; 318 319 final ServiceThread mHandlerThread; 320 321 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 322 private static final String IDMAP_SUFFIX = "@idmap"; 323 324 final PackageHandler mHandler; 325 326 final int mSdkVersion = Build.VERSION.SDK_INT; 327 328 final Context mContext; 329 final boolean mFactoryTest; 330 final boolean mOnlyCore; 331 final DisplayMetrics mMetrics; 332 final int mDefParseFlags; 333 final String[] mSeparateProcesses; 334 335 // This is where all application persistent data goes. 336 final File mAppDataDir; 337 338 // This is where all application persistent data goes for secondary users. 339 final File mUserAppDataDir; 340 341 /** The location for ASEC container files on internal storage. */ 342 final String mAsecInternalPath; 343 344 // This is the object monitoring the framework dir. 345 final FileObserver mFrameworkInstallObserver; 346 347 // This is the object monitoring the system app dir. 348 final FileObserver mSystemInstallObserver; 349 350 // This is the object monitoring the privileged system app dir. 351 final FileObserver mPrivilegedInstallObserver; 352 353 // This is the object monitoring the vendor app dir. 354 final FileObserver mVendorInstallObserver; 355 356 // This is the object monitoring the vendor overlay package dir. 357 final FileObserver mVendorOverlayInstallObserver; 358 359 // This is the object monitoring the OEM app dir. 360 final FileObserver mOemInstallObserver; 361 362 // This is the object monitoring mAppInstallDir. 363 final FileObserver mAppInstallObserver; 364 365 // This is the object monitoring mDrmAppPrivateInstallDir. 366 final FileObserver mDrmAppInstallObserver; 367 368 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 369 // LOCK HELD. Can be called with mInstallLock held. 370 final Installer mInstaller; 371 372 /** Directory where installed third-party apps stored */ 373 final File mAppInstallDir; 374 375 /** 376 * Directory to which applications installed internally have their 377 * 32 bit native libraries copied. 378 */ 379 private File mAppLib32InstallDir; 380 381 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 382 // apps. 383 final File mDrmAppPrivateInstallDir; 384 385 // ---------------------------------------------------------------- 386 387 // Lock for state used when installing and doing other long running 388 // operations. Methods that must be called with this lock held have 389 // the suffix "LI". 390 final Object mInstallLock = new Object(); 391 392 // These are the directories in the 3rd party applications installed dir 393 // that we have currently loaded packages from. Keys are the application's 394 // installed zip file (absolute codePath), and values are Package. 395 final HashMap<String, PackageParser.Package> mAppDirs = 396 new HashMap<String, PackageParser.Package>(); 397 398 // ---------------------------------------------------------------- 399 400 // Keys are String (package name), values are Package. This also serves 401 // as the lock for the global state. Methods that must be called with 402 // this lock held have the prefix "LP". 403 final HashMap<String, PackageParser.Package> mPackages = 404 new HashMap<String, PackageParser.Package>(); 405 406 // Tracks available target package names -> overlay package paths. 407 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 408 new HashMap<String, HashMap<String, PackageParser.Package>>(); 409 410 final Settings mSettings; 411 boolean mRestoredSettings; 412 413 // System configuration read by SystemConfig. 414 final int[] mGlobalGids; 415 final SparseArray<HashSet<String>> mSystemPermissions; 416 final HashMap<String, FeatureInfo> mAvailableFeatures; 417 418 // If mac_permissions.xml was found for seinfo labeling. 419 boolean mFoundPolicyFile; 420 421 // If a recursive restorecon of /data/data/<pkg> is needed. 422 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 423 424 public static final class SharedLibraryEntry { 425 public final String path; 426 public final String apk; 427 428 SharedLibraryEntry(String _path, String _apk) { 429 path = _path; 430 apk = _apk; 431 } 432 } 433 434 // Currently known shared libraries. 435 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 436 new HashMap<String, SharedLibraryEntry>(); 437 438 // All available activities, for your resolving pleasure. 439 final ActivityIntentResolver mActivities = 440 new ActivityIntentResolver(); 441 442 // All available receivers, for your resolving pleasure. 443 final ActivityIntentResolver mReceivers = 444 new ActivityIntentResolver(); 445 446 // All available services, for your resolving pleasure. 447 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 448 449 // All available providers, for your resolving pleasure. 450 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 451 452 // Mapping from provider base names (first directory in content URI codePath) 453 // to the provider information. 454 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 455 new HashMap<String, PackageParser.Provider>(); 456 457 // Mapping from instrumentation class names to info about them. 458 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 459 new HashMap<ComponentName, PackageParser.Instrumentation>(); 460 461 // Mapping from permission names to info about them. 462 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 463 new HashMap<String, PackageParser.PermissionGroup>(); 464 465 // Packages whose data we have transfered into another package, thus 466 // should no longer exist. 467 final HashSet<String> mTransferedPackages = new HashSet<String>(); 468 469 // Broadcast actions that are only available to the system. 470 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 471 472 /** List of packages waiting for verification. */ 473 final SparseArray<PackageVerificationState> mPendingVerification 474 = new SparseArray<PackageVerificationState>(); 475 476 final PackageInstallerService mInstallerService; 477 478 HashSet<PackageParser.Package> mDeferredDexOpt = null; 479 480 // Cache of users who need badging. 481 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 482 483 /** Token for keys in mPendingVerification. */ 484 private int mPendingVerificationToken = 0; 485 486 boolean mSystemReady; 487 boolean mSafeMode; 488 boolean mHasSystemUidErrors; 489 490 ApplicationInfo mAndroidApplication; 491 final ActivityInfo mResolveActivity = new ActivityInfo(); 492 final ResolveInfo mResolveInfo = new ResolveInfo(); 493 ComponentName mResolveComponentName; 494 PackageParser.Package mPlatformPackage; 495 ComponentName mCustomResolverComponentName; 496 497 boolean mResolverReplaced = false; 498 499 // Set of pending broadcasts for aggregating enable/disable of components. 500 static class PendingPackageBroadcasts { 501 // for each user id, a map of <package name -> components within that package> 502 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 503 504 public PendingPackageBroadcasts() { 505 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 506 } 507 508 public ArrayList<String> get(int userId, String packageName) { 509 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 510 return packages.get(packageName); 511 } 512 513 public void put(int userId, String packageName, ArrayList<String> components) { 514 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 515 packages.put(packageName, components); 516 } 517 518 public void remove(int userId, String packageName) { 519 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 520 if (packages != null) { 521 packages.remove(packageName); 522 } 523 } 524 525 public void remove(int userId) { 526 mUidMap.remove(userId); 527 } 528 529 public int userIdCount() { 530 return mUidMap.size(); 531 } 532 533 public int userIdAt(int n) { 534 return mUidMap.keyAt(n); 535 } 536 537 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 538 return mUidMap.get(userId); 539 } 540 541 public int size() { 542 // total number of pending broadcast entries across all userIds 543 int num = 0; 544 for (int i = 0; i< mUidMap.size(); i++) { 545 num += mUidMap.valueAt(i).size(); 546 } 547 return num; 548 } 549 550 public void clear() { 551 mUidMap.clear(); 552 } 553 554 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 555 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 556 if (map == null) { 557 map = new HashMap<String, ArrayList<String>>(); 558 mUidMap.put(userId, map); 559 } 560 return map; 561 } 562 } 563 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 564 565 // Service Connection to remote media container service to copy 566 // package uri's from external media onto secure containers 567 // or internal storage. 568 private IMediaContainerService mContainerService = null; 569 570 static final int SEND_PENDING_BROADCAST = 1; 571 static final int MCS_BOUND = 3; 572 static final int END_COPY = 4; 573 static final int INIT_COPY = 5; 574 static final int MCS_UNBIND = 6; 575 static final int START_CLEANING_PACKAGE = 7; 576 static final int FIND_INSTALL_LOC = 8; 577 static final int POST_INSTALL = 9; 578 static final int MCS_RECONNECT = 10; 579 static final int MCS_GIVE_UP = 11; 580 static final int UPDATED_MEDIA_STATUS = 12; 581 static final int WRITE_SETTINGS = 13; 582 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 583 static final int PACKAGE_VERIFIED = 15; 584 static final int CHECK_PENDING_VERIFICATION = 16; 585 586 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 587 588 // Delay time in millisecs 589 static final int BROADCAST_DELAY = 10 * 1000; 590 591 static UserManagerService sUserManager; 592 593 // Stores a list of users whose package restrictions file needs to be updated 594 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 595 596 final private DefaultContainerConnection mDefContainerConn = 597 new DefaultContainerConnection(); 598 class DefaultContainerConnection implements ServiceConnection { 599 public void onServiceConnected(ComponentName name, IBinder service) { 600 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 601 IMediaContainerService imcs = 602 IMediaContainerService.Stub.asInterface(service); 603 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 604 } 605 606 public void onServiceDisconnected(ComponentName name) { 607 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 608 } 609 }; 610 611 // Recordkeeping of restore-after-install operations that are currently in flight 612 // between the Package Manager and the Backup Manager 613 class PostInstallData { 614 public InstallArgs args; 615 public PackageInstalledInfo res; 616 617 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 618 args = _a; 619 res = _r; 620 } 621 }; 622 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 623 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 624 625 private final String mRequiredVerifierPackage; 626 627 private final PackageUsage mPackageUsage = new PackageUsage(); 628 629 private class PackageUsage { 630 private static final int WRITE_INTERVAL 631 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 632 633 private final Object mFileLock = new Object(); 634 private final AtomicLong mLastWritten = new AtomicLong(0); 635 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 636 637 private boolean mIsHistoricalPackageUsageAvailable = true; 638 639 boolean isHistoricalPackageUsageAvailable() { 640 return mIsHistoricalPackageUsageAvailable; 641 } 642 643 void write(boolean force) { 644 if (force) { 645 writeInternal(); 646 return; 647 } 648 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 649 && !DEBUG_DEXOPT) { 650 return; 651 } 652 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 653 new Thread("PackageUsage_DiskWriter") { 654 @Override 655 public void run() { 656 try { 657 writeInternal(); 658 } finally { 659 mBackgroundWriteRunning.set(false); 660 } 661 } 662 }.start(); 663 } 664 } 665 666 private void writeInternal() { 667 synchronized (mPackages) { 668 synchronized (mFileLock) { 669 AtomicFile file = getFile(); 670 FileOutputStream f = null; 671 try { 672 f = file.startWrite(); 673 BufferedOutputStream out = new BufferedOutputStream(f); 674 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 675 StringBuilder sb = new StringBuilder(); 676 for (PackageParser.Package pkg : mPackages.values()) { 677 if (pkg.mLastPackageUsageTimeInMills == 0) { 678 continue; 679 } 680 sb.setLength(0); 681 sb.append(pkg.packageName); 682 sb.append(' '); 683 sb.append((long)pkg.mLastPackageUsageTimeInMills); 684 sb.append('\n'); 685 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 686 } 687 out.flush(); 688 file.finishWrite(f); 689 } catch (IOException e) { 690 if (f != null) { 691 file.failWrite(f); 692 } 693 Log.e(TAG, "Failed to write package usage times", e); 694 } 695 } 696 } 697 mLastWritten.set(SystemClock.elapsedRealtime()); 698 } 699 700 void readLP() { 701 synchronized (mFileLock) { 702 AtomicFile file = getFile(); 703 BufferedInputStream in = null; 704 try { 705 in = new BufferedInputStream(file.openRead()); 706 StringBuffer sb = new StringBuffer(); 707 while (true) { 708 String packageName = readToken(in, sb, ' '); 709 if (packageName == null) { 710 break; 711 } 712 String timeInMillisString = readToken(in, sb, '\n'); 713 if (timeInMillisString == null) { 714 throw new IOException("Failed to find last usage time for package " 715 + packageName); 716 } 717 PackageParser.Package pkg = mPackages.get(packageName); 718 if (pkg == null) { 719 continue; 720 } 721 long timeInMillis; 722 try { 723 timeInMillis = Long.parseLong(timeInMillisString.toString()); 724 } catch (NumberFormatException e) { 725 throw new IOException("Failed to parse " + timeInMillisString 726 + " as a long.", e); 727 } 728 pkg.mLastPackageUsageTimeInMills = timeInMillis; 729 } 730 } catch (FileNotFoundException expected) { 731 mIsHistoricalPackageUsageAvailable = false; 732 } catch (IOException e) { 733 Log.w(TAG, "Failed to read package usage times", e); 734 } finally { 735 IoUtils.closeQuietly(in); 736 } 737 } 738 mLastWritten.set(SystemClock.elapsedRealtime()); 739 } 740 741 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 742 throws IOException { 743 sb.setLength(0); 744 while (true) { 745 int ch = in.read(); 746 if (ch == -1) { 747 if (sb.length() == 0) { 748 return null; 749 } 750 throw new IOException("Unexpected EOF"); 751 } 752 if (ch == endOfToken) { 753 return sb.toString(); 754 } 755 sb.append((char)ch); 756 } 757 } 758 759 private AtomicFile getFile() { 760 File dataDir = Environment.getDataDirectory(); 761 File systemDir = new File(dataDir, "system"); 762 File fname = new File(systemDir, "package-usage.list"); 763 return new AtomicFile(fname); 764 } 765 } 766 767 class PackageHandler extends Handler { 768 private boolean mBound = false; 769 final ArrayList<HandlerParams> mPendingInstalls = 770 new ArrayList<HandlerParams>(); 771 772 private boolean connectToService() { 773 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 774 " DefaultContainerService"); 775 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 776 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 777 if (mContext.bindServiceAsUser(service, mDefContainerConn, 778 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 779 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 780 mBound = true; 781 return true; 782 } 783 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 784 return false; 785 } 786 787 private void disconnectService() { 788 mContainerService = null; 789 mBound = false; 790 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 791 mContext.unbindService(mDefContainerConn); 792 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 793 } 794 795 PackageHandler(Looper looper) { 796 super(looper); 797 } 798 799 public void handleMessage(Message msg) { 800 try { 801 doHandleMessage(msg); 802 } finally { 803 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 804 } 805 } 806 807 void doHandleMessage(Message msg) { 808 switch (msg.what) { 809 case INIT_COPY: { 810 HandlerParams params = (HandlerParams) msg.obj; 811 int idx = mPendingInstalls.size(); 812 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 813 // If a bind was already initiated we dont really 814 // need to do anything. The pending install 815 // will be processed later on. 816 if (!mBound) { 817 // If this is the only one pending we might 818 // have to bind to the service again. 819 if (!connectToService()) { 820 Slog.e(TAG, "Failed to bind to media container service"); 821 params.serviceError(); 822 return; 823 } else { 824 // Once we bind to the service, the first 825 // pending request will be processed. 826 mPendingInstalls.add(idx, params); 827 } 828 } else { 829 mPendingInstalls.add(idx, params); 830 // Already bound to the service. Just make 831 // sure we trigger off processing the first request. 832 if (idx == 0) { 833 mHandler.sendEmptyMessage(MCS_BOUND); 834 } 835 } 836 break; 837 } 838 case MCS_BOUND: { 839 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 840 if (msg.obj != null) { 841 mContainerService = (IMediaContainerService) msg.obj; 842 } 843 if (mContainerService == null) { 844 // Something seriously wrong. Bail out 845 Slog.e(TAG, "Cannot bind to media container service"); 846 for (HandlerParams params : mPendingInstalls) { 847 // Indicate service bind error 848 params.serviceError(); 849 } 850 mPendingInstalls.clear(); 851 } else if (mPendingInstalls.size() > 0) { 852 HandlerParams params = mPendingInstalls.get(0); 853 if (params != null) { 854 if (params.startCopy()) { 855 // We are done... look for more work or to 856 // go idle. 857 if (DEBUG_SD_INSTALL) Log.i(TAG, 858 "Checking for more work or unbind..."); 859 // Delete pending install 860 if (mPendingInstalls.size() > 0) { 861 mPendingInstalls.remove(0); 862 } 863 if (mPendingInstalls.size() == 0) { 864 if (mBound) { 865 if (DEBUG_SD_INSTALL) Log.i(TAG, 866 "Posting delayed MCS_UNBIND"); 867 removeMessages(MCS_UNBIND); 868 Message ubmsg = obtainMessage(MCS_UNBIND); 869 // Unbind after a little delay, to avoid 870 // continual thrashing. 871 sendMessageDelayed(ubmsg, 10000); 872 } 873 } else { 874 // There are more pending requests in queue. 875 // Just post MCS_BOUND message to trigger processing 876 // of next pending install. 877 if (DEBUG_SD_INSTALL) Log.i(TAG, 878 "Posting MCS_BOUND for next work"); 879 mHandler.sendEmptyMessage(MCS_BOUND); 880 } 881 } 882 } 883 } else { 884 // Should never happen ideally. 885 Slog.w(TAG, "Empty queue"); 886 } 887 break; 888 } 889 case MCS_RECONNECT: { 890 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 891 if (mPendingInstalls.size() > 0) { 892 if (mBound) { 893 disconnectService(); 894 } 895 if (!connectToService()) { 896 Slog.e(TAG, "Failed to bind to media container service"); 897 for (HandlerParams params : mPendingInstalls) { 898 // Indicate service bind error 899 params.serviceError(); 900 } 901 mPendingInstalls.clear(); 902 } 903 } 904 break; 905 } 906 case MCS_UNBIND: { 907 // If there is no actual work left, then time to unbind. 908 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 909 910 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 911 if (mBound) { 912 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 913 914 disconnectService(); 915 } 916 } else if (mPendingInstalls.size() > 0) { 917 // There are more pending requests in queue. 918 // Just post MCS_BOUND message to trigger processing 919 // of next pending install. 920 mHandler.sendEmptyMessage(MCS_BOUND); 921 } 922 923 break; 924 } 925 case MCS_GIVE_UP: { 926 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 927 mPendingInstalls.remove(0); 928 break; 929 } 930 case SEND_PENDING_BROADCAST: { 931 String packages[]; 932 ArrayList<String> components[]; 933 int size = 0; 934 int uids[]; 935 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 936 synchronized (mPackages) { 937 if (mPendingBroadcasts == null) { 938 return; 939 } 940 size = mPendingBroadcasts.size(); 941 if (size <= 0) { 942 // Nothing to be done. Just return 943 return; 944 } 945 packages = new String[size]; 946 components = new ArrayList[size]; 947 uids = new int[size]; 948 int i = 0; // filling out the above arrays 949 950 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 951 int packageUserId = mPendingBroadcasts.userIdAt(n); 952 Iterator<Map.Entry<String, ArrayList<String>>> it 953 = mPendingBroadcasts.packagesForUserId(packageUserId) 954 .entrySet().iterator(); 955 while (it.hasNext() && i < size) { 956 Map.Entry<String, ArrayList<String>> ent = it.next(); 957 packages[i] = ent.getKey(); 958 components[i] = ent.getValue(); 959 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 960 uids[i] = (ps != null) 961 ? UserHandle.getUid(packageUserId, ps.appId) 962 : -1; 963 i++; 964 } 965 } 966 size = i; 967 mPendingBroadcasts.clear(); 968 } 969 // Send broadcasts 970 for (int i = 0; i < size; i++) { 971 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 972 } 973 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 974 break; 975 } 976 case START_CLEANING_PACKAGE: { 977 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 978 final String packageName = (String)msg.obj; 979 final int userId = msg.arg1; 980 final boolean andCode = msg.arg2 != 0; 981 synchronized (mPackages) { 982 if (userId == UserHandle.USER_ALL) { 983 int[] users = sUserManager.getUserIds(); 984 for (int user : users) { 985 mSettings.addPackageToCleanLPw( 986 new PackageCleanItem(user, packageName, andCode)); 987 } 988 } else { 989 mSettings.addPackageToCleanLPw( 990 new PackageCleanItem(userId, packageName, andCode)); 991 } 992 } 993 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 994 startCleaningPackages(); 995 } break; 996 case POST_INSTALL: { 997 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 998 PostInstallData data = mRunningInstalls.get(msg.arg1); 999 mRunningInstalls.delete(msg.arg1); 1000 boolean deleteOld = false; 1001 1002 if (data != null) { 1003 InstallArgs args = data.args; 1004 PackageInstalledInfo res = data.res; 1005 1006 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1007 res.removedInfo.sendBroadcast(false, true, false); 1008 Bundle extras = new Bundle(1); 1009 extras.putInt(Intent.EXTRA_UID, res.uid); 1010 // Determine the set of users who are adding this 1011 // package for the first time vs. those who are seeing 1012 // an update. 1013 int[] firstUsers; 1014 int[] updateUsers = new int[0]; 1015 if (res.origUsers == null || res.origUsers.length == 0) { 1016 firstUsers = res.newUsers; 1017 } else { 1018 firstUsers = new int[0]; 1019 for (int i=0; i<res.newUsers.length; i++) { 1020 int user = res.newUsers[i]; 1021 boolean isNew = true; 1022 for (int j=0; j<res.origUsers.length; j++) { 1023 if (res.origUsers[j] == user) { 1024 isNew = false; 1025 break; 1026 } 1027 } 1028 if (isNew) { 1029 int[] newFirst = new int[firstUsers.length+1]; 1030 System.arraycopy(firstUsers, 0, newFirst, 0, 1031 firstUsers.length); 1032 newFirst[firstUsers.length] = user; 1033 firstUsers = newFirst; 1034 } else { 1035 int[] newUpdate = new int[updateUsers.length+1]; 1036 System.arraycopy(updateUsers, 0, newUpdate, 0, 1037 updateUsers.length); 1038 newUpdate[updateUsers.length] = user; 1039 updateUsers = newUpdate; 1040 } 1041 } 1042 } 1043 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1044 res.pkg.applicationInfo.packageName, 1045 extras, null, null, firstUsers); 1046 final boolean update = res.removedInfo.removedPackage != null; 1047 if (update) { 1048 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1049 } 1050 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1051 res.pkg.applicationInfo.packageName, 1052 extras, null, null, updateUsers); 1053 if (update) { 1054 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1055 res.pkg.applicationInfo.packageName, 1056 extras, null, null, updateUsers); 1057 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1058 null, null, 1059 res.pkg.applicationInfo.packageName, null, updateUsers); 1060 1061 // treat asec-hosted packages like removable media on upgrade 1062 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1063 if (DEBUG_INSTALL) { 1064 Slog.i(TAG, "upgrading pkg " + res.pkg 1065 + " is ASEC-hosted -> AVAILABLE"); 1066 } 1067 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1068 ArrayList<String> pkgList = new ArrayList<String>(1); 1069 pkgList.add(res.pkg.applicationInfo.packageName); 1070 sendResourcesChangedBroadcast(true, true, 1071 pkgList,uidArray, null); 1072 } 1073 } 1074 if (res.removedInfo.args != null) { 1075 // Remove the replaced package's older resources safely now 1076 deleteOld = true; 1077 } 1078 1079 // Log current value of "unknown sources" setting 1080 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1081 getUnknownSourcesSettings()); 1082 } 1083 // Force a gc to clear up things 1084 Runtime.getRuntime().gc(); 1085 // We delete after a gc for applications on sdcard. 1086 if (deleteOld) { 1087 synchronized (mInstallLock) { 1088 res.removedInfo.args.doPostDeleteLI(true); 1089 } 1090 } 1091 if (args.observer != null) { 1092 try { 1093 Bundle extras = extrasForInstallResult(res); 1094 args.observer.packageInstalled(res.name, extras, res.returnCode, 1095 res.returnMsg); 1096 } catch (RemoteException e) { 1097 Slog.i(TAG, "Observer no longer exists."); 1098 } 1099 } 1100 } else { 1101 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1102 } 1103 } break; 1104 case UPDATED_MEDIA_STATUS: { 1105 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1106 boolean reportStatus = msg.arg1 == 1; 1107 boolean doGc = msg.arg2 == 1; 1108 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1109 if (doGc) { 1110 // Force a gc to clear up stale containers. 1111 Runtime.getRuntime().gc(); 1112 } 1113 if (msg.obj != null) { 1114 @SuppressWarnings("unchecked") 1115 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1116 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1117 // Unload containers 1118 unloadAllContainers(args); 1119 } 1120 if (reportStatus) { 1121 try { 1122 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1123 PackageHelper.getMountService().finishMediaUpdate(); 1124 } catch (RemoteException e) { 1125 Log.e(TAG, "MountService not running?"); 1126 } 1127 } 1128 } break; 1129 case WRITE_SETTINGS: { 1130 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1131 synchronized (mPackages) { 1132 removeMessages(WRITE_SETTINGS); 1133 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1134 mSettings.writeLPr(); 1135 mDirtyUsers.clear(); 1136 } 1137 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1138 } break; 1139 case WRITE_PACKAGE_RESTRICTIONS: { 1140 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1141 synchronized (mPackages) { 1142 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1143 for (int userId : mDirtyUsers) { 1144 mSettings.writePackageRestrictionsLPr(userId); 1145 } 1146 mDirtyUsers.clear(); 1147 } 1148 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1149 } break; 1150 case CHECK_PENDING_VERIFICATION: { 1151 final int verificationId = msg.arg1; 1152 final PackageVerificationState state = mPendingVerification.get(verificationId); 1153 1154 if ((state != null) && !state.timeoutExtended()) { 1155 final InstallArgs args = state.getInstallArgs(); 1156 final Uri originUri = Uri.fromFile(args.originFile); 1157 1158 Slog.i(TAG, "Verification timed out for " + originUri); 1159 mPendingVerification.remove(verificationId); 1160 1161 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1162 1163 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1164 Slog.i(TAG, "Continuing with installation of " + originUri); 1165 state.setVerifierResponse(Binder.getCallingUid(), 1166 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1167 broadcastPackageVerified(verificationId, originUri, 1168 PackageManager.VERIFICATION_ALLOW, 1169 state.getInstallArgs().getUser()); 1170 try { 1171 ret = args.copyApk(mContainerService, true); 1172 } catch (RemoteException e) { 1173 Slog.e(TAG, "Could not contact the ContainerService"); 1174 } 1175 } else { 1176 broadcastPackageVerified(verificationId, originUri, 1177 PackageManager.VERIFICATION_REJECT, 1178 state.getInstallArgs().getUser()); 1179 } 1180 1181 processPendingInstall(args, ret); 1182 mHandler.sendEmptyMessage(MCS_UNBIND); 1183 } 1184 break; 1185 } 1186 case PACKAGE_VERIFIED: { 1187 final int verificationId = msg.arg1; 1188 1189 final PackageVerificationState state = mPendingVerification.get(verificationId); 1190 if (state == null) { 1191 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1192 break; 1193 } 1194 1195 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1196 1197 state.setVerifierResponse(response.callerUid, response.code); 1198 1199 if (state.isVerificationComplete()) { 1200 mPendingVerification.remove(verificationId); 1201 1202 final InstallArgs args = state.getInstallArgs(); 1203 final Uri originUri = Uri.fromFile(args.originFile); 1204 1205 int ret; 1206 if (state.isInstallAllowed()) { 1207 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1208 broadcastPackageVerified(verificationId, originUri, 1209 response.code, state.getInstallArgs().getUser()); 1210 try { 1211 ret = args.copyApk(mContainerService, true); 1212 } catch (RemoteException e) { 1213 Slog.e(TAG, "Could not contact the ContainerService"); 1214 } 1215 } else { 1216 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1217 } 1218 1219 processPendingInstall(args, ret); 1220 1221 mHandler.sendEmptyMessage(MCS_UNBIND); 1222 } 1223 1224 break; 1225 } 1226 } 1227 } 1228 } 1229 1230 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1231 Bundle extras = null; 1232 switch (res.returnCode) { 1233 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1234 extras = new Bundle(); 1235 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1236 res.origPermission); 1237 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1238 res.origPackage); 1239 break; 1240 } 1241 } 1242 return extras; 1243 } 1244 1245 void scheduleWriteSettingsLocked() { 1246 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1247 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1248 } 1249 } 1250 1251 void scheduleWritePackageRestrictionsLocked(int userId) { 1252 if (!sUserManager.exists(userId)) return; 1253 mDirtyUsers.add(userId); 1254 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1255 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1256 } 1257 } 1258 1259 public static final PackageManagerService main(Context context, Installer installer, 1260 boolean factoryTest, boolean onlyCore) { 1261 PackageManagerService m = new PackageManagerService(context, installer, 1262 factoryTest, onlyCore); 1263 ServiceManager.addService("package", m); 1264 return m; 1265 } 1266 1267 static String[] splitString(String str, char sep) { 1268 int count = 1; 1269 int i = 0; 1270 while ((i=str.indexOf(sep, i)) >= 0) { 1271 count++; 1272 i++; 1273 } 1274 1275 String[] res = new String[count]; 1276 i=0; 1277 count = 0; 1278 int lastI=0; 1279 while ((i=str.indexOf(sep, i)) >= 0) { 1280 res[count] = str.substring(lastI, i); 1281 count++; 1282 i++; 1283 lastI = i; 1284 } 1285 res[count] = str.substring(lastI, str.length()); 1286 return res; 1287 } 1288 1289 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1290 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1291 Context.DISPLAY_SERVICE); 1292 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1293 } 1294 1295 public PackageManagerService(Context context, Installer installer, 1296 boolean factoryTest, boolean onlyCore) { 1297 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1298 SystemClock.uptimeMillis()); 1299 1300 if (mSdkVersion <= 0) { 1301 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1302 } 1303 1304 mContext = context; 1305 mFactoryTest = factoryTest; 1306 mOnlyCore = onlyCore; 1307 mMetrics = new DisplayMetrics(); 1308 mSettings = new Settings(context); 1309 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1310 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1311 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1312 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1313 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1314 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1315 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1316 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1317 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1318 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1319 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1320 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1321 1322 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1323 if (separateProcesses != null && separateProcesses.length() > 0) { 1324 if ("*".equals(separateProcesses)) { 1325 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1326 mSeparateProcesses = null; 1327 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1328 } else { 1329 mDefParseFlags = 0; 1330 mSeparateProcesses = separateProcesses.split(","); 1331 Slog.w(TAG, "Running with debug.separate_processes: " 1332 + separateProcesses); 1333 } 1334 } else { 1335 mDefParseFlags = 0; 1336 mSeparateProcesses = null; 1337 } 1338 1339 mInstaller = installer; 1340 1341 getDefaultDisplayMetrics(context, mMetrics); 1342 1343 SystemConfig systemConfig = SystemConfig.getInstance(); 1344 mGlobalGids = systemConfig.getGlobalGids(); 1345 mSystemPermissions = systemConfig.getSystemPermissions(); 1346 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1347 1348 synchronized (mInstallLock) { 1349 // writer 1350 synchronized (mPackages) { 1351 mHandlerThread = new ServiceThread(TAG, 1352 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1353 mHandlerThread.start(); 1354 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1355 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1356 1357 File dataDir = Environment.getDataDirectory(); 1358 mAppDataDir = new File(dataDir, "data"); 1359 mAppInstallDir = new File(dataDir, "app"); 1360 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1361 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1362 mUserAppDataDir = new File(dataDir, "user"); 1363 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1364 1365 sUserManager = new UserManagerService(context, this, 1366 mInstallLock, mPackages); 1367 1368 // Propagate permission configuration in to package manager. 1369 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1370 = systemConfig.getPermissions(); 1371 for (int i=0; i<permConfig.size(); i++) { 1372 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1373 BasePermission bp = mSettings.mPermissions.get(perm.name); 1374 if (bp == null) { 1375 bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN); 1376 mSettings.mPermissions.put(perm.name, bp); 1377 } 1378 if (perm.gids != null) { 1379 bp.gids = appendInts(bp.gids, perm.gids); 1380 } 1381 } 1382 1383 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1384 for (int i=0; i<libConfig.size(); i++) { 1385 mSharedLibraries.put(libConfig.keyAt(i), 1386 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1387 } 1388 1389 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1390 1391 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1392 mSdkVersion, mOnlyCore); 1393 1394 String customResolverActivity = Resources.getSystem().getString( 1395 R.string.config_customResolverActivity); 1396 if (TextUtils.isEmpty(customResolverActivity)) { 1397 customResolverActivity = null; 1398 } else { 1399 mCustomResolverComponentName = ComponentName.unflattenFromString( 1400 customResolverActivity); 1401 } 1402 1403 long startTime = SystemClock.uptimeMillis(); 1404 1405 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1406 startTime); 1407 1408 // Set flag to monitor and not change apk file paths when 1409 // scanning install directories. 1410 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1411 1412 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1413 1414 /** 1415 * Add everything in the in the boot class path to the 1416 * list of process files because dexopt will have been run 1417 * if necessary during zygote startup. 1418 */ 1419 String bootClassPath = System.getProperty("java.boot.class.path"); 1420 if (bootClassPath != null) { 1421 String[] paths = splitString(bootClassPath, ':'); 1422 for (int i=0; i<paths.length; i++) { 1423 alreadyDexOpted.add(paths[i]); 1424 } 1425 } else { 1426 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1427 } 1428 1429 boolean didDexOptLibraryOrTool = false; 1430 1431 final List<String> instructionSets = getAllInstructionSets(); 1432 1433 /** 1434 * Ensure all external libraries have had dexopt run on them. 1435 */ 1436 if (mSharedLibraries.size() > 0) { 1437 // NOTE: For now, we're compiling these system "shared libraries" 1438 // (and framework jars) into all available architectures. It's possible 1439 // to compile them only when we come across an app that uses them (there's 1440 // already logic for that in scanPackageLI) but that adds some complexity. 1441 for (String instructionSet : instructionSets) { 1442 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1443 final String lib = libEntry.path; 1444 if (lib == null) { 1445 continue; 1446 } 1447 1448 try { 1449 if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) { 1450 alreadyDexOpted.add(lib); 1451 1452 // The list of "shared libraries" we have at this point is 1453 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet); 1454 didDexOptLibraryOrTool = true; 1455 } 1456 } catch (FileNotFoundException e) { 1457 Slog.w(TAG, "Library not found: " + lib); 1458 } catch (IOException e) { 1459 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1460 + e.getMessage()); 1461 } 1462 } 1463 } 1464 } 1465 1466 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1467 1468 // Gross hack for now: we know this file doesn't contain any 1469 // code, so don't dexopt it to avoid the resulting log spew. 1470 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1471 1472 // Gross hack for now: we know this file is only part of 1473 // the boot class path for art, so don't dexopt it to 1474 // avoid the resulting log spew. 1475 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1476 1477 /** 1478 * And there are a number of commands implemented in Java, which 1479 * we currently need to do the dexopt on so that they can be 1480 * run from a non-root shell. 1481 */ 1482 String[] frameworkFiles = frameworkDir.list(); 1483 if (frameworkFiles != null) { 1484 // TODO: We could compile these only for the most preferred ABI. We should 1485 // first double check that the dex files for these commands are not referenced 1486 // by other system apps. 1487 for (String instructionSet : instructionSets) { 1488 for (int i=0; i<frameworkFiles.length; i++) { 1489 File libPath = new File(frameworkDir, frameworkFiles[i]); 1490 String path = libPath.getPath(); 1491 // Skip the file if we already did it. 1492 if (alreadyDexOpted.contains(path)) { 1493 continue; 1494 } 1495 // Skip the file if it is not a type we want to dexopt. 1496 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1497 continue; 1498 } 1499 try { 1500 if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) { 1501 mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet); 1502 didDexOptLibraryOrTool = true; 1503 } 1504 } catch (FileNotFoundException e) { 1505 Slog.w(TAG, "Jar not found: " + path); 1506 } catch (IOException e) { 1507 Slog.w(TAG, "Exception reading jar: " + path, e); 1508 } 1509 } 1510 } 1511 } 1512 1513 if (didDexOptLibraryOrTool) { 1514 // If we dexopted a library or tool, then something on the system has 1515 // changed. Consider this significant, and wipe away all other 1516 // existing dexopt files to ensure we don't leave any dangling around. 1517 // 1518 // TODO: This should be revisited because it isn't as good an indicator 1519 // as it used to be. It used to include the boot classpath but at some point 1520 // DexFile.isDexOptNeeded started returning false for the boot 1521 // class path files in all cases. It is very possible in a 1522 // small maintenance release update that the library and tool 1523 // jars may be unchanged but APK could be removed resulting in 1524 // unused dalvik-cache files. 1525 for (String instructionSet : instructionSets) { 1526 mInstaller.pruneDexCache(instructionSet); 1527 } 1528 1529 // Additionally, delete all dex files from the root directory 1530 // since there shouldn't be any there anyway, unless we're upgrading 1531 // from an older OS version or a build that contained the "old" style 1532 // flat scheme. 1533 mInstaller.pruneDexCache("."); 1534 } 1535 1536 // Collect vendor overlay packages. 1537 // (Do this before scanning any apps.) 1538 // For security and version matching reason, only consider 1539 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1540 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1541 mVendorOverlayInstallObserver = new AppDirObserver( 1542 vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false); 1543 mVendorOverlayInstallObserver.startWatching(); 1544 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1545 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1546 1547 // Find base frameworks (resource packages without code). 1548 mFrameworkInstallObserver = new AppDirObserver( 1549 frameworkDir.getPath(), OBSERVER_EVENTS, true, false); 1550 mFrameworkInstallObserver.startWatching(); 1551 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1552 | PackageParser.PARSE_IS_SYSTEM_DIR 1553 | PackageParser.PARSE_IS_PRIVILEGED, 1554 scanMode | SCAN_NO_DEX, 0); 1555 1556 // Collected privileged system packages. 1557 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1558 mPrivilegedInstallObserver = new AppDirObserver( 1559 privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true); 1560 mPrivilegedInstallObserver.startWatching(); 1561 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1562 | PackageParser.PARSE_IS_SYSTEM_DIR 1563 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1564 1565 // Collect ordinary system packages. 1566 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1567 mSystemInstallObserver = new AppDirObserver( 1568 systemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1569 mSystemInstallObserver.startWatching(); 1570 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1571 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1572 1573 // Collect all vendor packages. 1574 File vendorAppDir = new File("/vendor/app"); 1575 try { 1576 vendorAppDir = vendorAppDir.getCanonicalFile(); 1577 } catch (IOException e) { 1578 // failed to look up canonical path, continue with original one 1579 } 1580 mVendorInstallObserver = new AppDirObserver( 1581 vendorAppDir.getPath(), OBSERVER_EVENTS, true, false); 1582 mVendorInstallObserver.startWatching(); 1583 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1584 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1585 1586 // Collect all OEM packages. 1587 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1588 mOemInstallObserver = new AppDirObserver( 1589 oemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1590 mOemInstallObserver.startWatching(); 1591 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1592 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1593 1594 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1595 mInstaller.moveFiles(); 1596 1597 // Prune any system packages that no longer exist. 1598 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1599 if (!mOnlyCore) { 1600 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1601 while (psit.hasNext()) { 1602 PackageSetting ps = psit.next(); 1603 1604 /* 1605 * If this is not a system app, it can't be a 1606 * disable system app. 1607 */ 1608 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1609 continue; 1610 } 1611 1612 /* 1613 * If the package is scanned, it's not erased. 1614 */ 1615 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1616 if (scannedPkg != null) { 1617 /* 1618 * If the system app is both scanned and in the 1619 * disabled packages list, then it must have been 1620 * added via OTA. Remove it from the currently 1621 * scanned package so the previously user-installed 1622 * application can be scanned. 1623 */ 1624 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1625 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1626 + "; removing system app"); 1627 removePackageLI(ps, true); 1628 } 1629 1630 continue; 1631 } 1632 1633 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1634 psit.remove(); 1635 String msg = "System package " + ps.name 1636 + " no longer exists; wiping its data"; 1637 reportSettingsProblem(Log.WARN, msg); 1638 removeDataDirsLI(ps.name); 1639 } else { 1640 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1641 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1642 possiblyDeletedUpdatedSystemApps.add(ps.name); 1643 } 1644 } 1645 } 1646 } 1647 1648 //look for any incomplete package installations 1649 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1650 //clean up list 1651 for(int i = 0; i < deletePkgsList.size(); i++) { 1652 //clean up here 1653 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1654 } 1655 //delete tmp files 1656 deleteTempPackageFiles(); 1657 1658 // Remove any shared userIDs that have no associated packages 1659 mSettings.pruneSharedUsersLPw(); 1660 1661 if (!mOnlyCore) { 1662 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1663 SystemClock.uptimeMillis()); 1664 mAppInstallObserver = new AppDirObserver( 1665 mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1666 mAppInstallObserver.startWatching(); 1667 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1668 1669 mDrmAppInstallObserver = new AppDirObserver( 1670 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1671 mDrmAppInstallObserver.startWatching(); 1672 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1673 scanMode, 0); 1674 1675 /** 1676 * Remove disable package settings for any updated system 1677 * apps that were removed via an OTA. If they're not a 1678 * previously-updated app, remove them completely. 1679 * Otherwise, just revoke their system-level permissions. 1680 */ 1681 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1682 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1683 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1684 1685 String msg; 1686 if (deletedPkg == null) { 1687 msg = "Updated system package " + deletedAppName 1688 + " no longer exists; wiping its data"; 1689 removeDataDirsLI(deletedAppName); 1690 } else { 1691 msg = "Updated system app + " + deletedAppName 1692 + " no longer present; removing system privileges for " 1693 + deletedAppName; 1694 1695 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1696 1697 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1698 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1699 } 1700 reportSettingsProblem(Log.WARN, msg); 1701 } 1702 } else { 1703 mAppInstallObserver = null; 1704 mDrmAppInstallObserver = null; 1705 } 1706 1707 // Now that we know all of the shared libraries, update all clients to have 1708 // the correct library paths. 1709 updateAllSharedLibrariesLPw(); 1710 1711 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1712 // NOTE: We ignore potential failures here during a system scan (like 1713 // the rest of the commands above) because there's precious little we 1714 // can do about it. A settings error is reported, though. 1715 adjustCpuAbisForSharedUserLPw(setting.packages, null, 1716 false /* force dexopt */, false /* defer dexopt */); 1717 } 1718 1719 // Now that we know all the packages we are keeping, 1720 // read and update their last usage times. 1721 mPackageUsage.readLP(); 1722 1723 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1724 SystemClock.uptimeMillis()); 1725 Slog.i(TAG, "Time to scan packages: " 1726 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1727 + " seconds"); 1728 1729 // If the platform SDK has changed since the last time we booted, 1730 // we need to re-grant app permission to catch any new ones that 1731 // appear. This is really a hack, and means that apps can in some 1732 // cases get permissions that the user didn't initially explicitly 1733 // allow... it would be nice to have some better way to handle 1734 // this situation. 1735 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1736 != mSdkVersion; 1737 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1738 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1739 + "; regranting permissions for internal storage"); 1740 mSettings.mInternalSdkPlatform = mSdkVersion; 1741 1742 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1743 | (regrantPermissions 1744 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1745 : 0)); 1746 1747 // If this is the first boot, and it is a normal boot, then 1748 // we need to initialize the default preferred apps. 1749 if (!mRestoredSettings && !onlyCore) { 1750 mSettings.readDefaultPreferredAppsLPw(this, 0); 1751 } 1752 1753 // All the changes are done during package scanning. 1754 mSettings.updateInternalDatabaseVersion(); 1755 1756 // can downgrade to reader 1757 mSettings.writeLPr(); 1758 1759 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1760 SystemClock.uptimeMillis()); 1761 1762 1763 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1764 } // synchronized (mPackages) 1765 } // synchronized (mInstallLock) 1766 1767 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1768 1769 // Now after opening every single application zip, make sure they 1770 // are all flushed. Not really needed, but keeps things nice and 1771 // tidy. 1772 Runtime.getRuntime().gc(); 1773 } 1774 1775 @Override 1776 public boolean isFirstBoot() { 1777 return !mRestoredSettings; 1778 } 1779 1780 @Override 1781 public boolean isOnlyCoreApps() { 1782 return mOnlyCore; 1783 } 1784 1785 private String getRequiredVerifierLPr() { 1786 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1787 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1788 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1789 1790 String requiredVerifier = null; 1791 1792 final int N = receivers.size(); 1793 for (int i = 0; i < N; i++) { 1794 final ResolveInfo info = receivers.get(i); 1795 1796 if (info.activityInfo == null) { 1797 continue; 1798 } 1799 1800 final String packageName = info.activityInfo.packageName; 1801 1802 final PackageSetting ps = mSettings.mPackages.get(packageName); 1803 if (ps == null) { 1804 continue; 1805 } 1806 1807 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1808 if (!gp.grantedPermissions 1809 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1810 continue; 1811 } 1812 1813 if (requiredVerifier != null) { 1814 throw new RuntimeException("There can be only one required verifier"); 1815 } 1816 1817 requiredVerifier = packageName; 1818 } 1819 1820 return requiredVerifier; 1821 } 1822 1823 @Override 1824 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1825 throws RemoteException { 1826 try { 1827 return super.onTransact(code, data, reply, flags); 1828 } catch (RuntimeException e) { 1829 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1830 Slog.wtf(TAG, "Package Manager Crash", e); 1831 } 1832 throw e; 1833 } 1834 } 1835 1836 void cleanupInstallFailedPackage(PackageSetting ps) { 1837 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1838 removeDataDirsLI(ps.name); 1839 1840 // TODO: try cleaning up codePath directory contents first, since it 1841 // might be a cluster 1842 1843 if (ps.codePath != null) { 1844 if (!ps.codePath.delete()) { 1845 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1846 } 1847 } 1848 if (ps.resourcePath != null) { 1849 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1850 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1851 } 1852 } 1853 mSettings.removePackageLPw(ps.name); 1854 } 1855 1856 static int[] appendInts(int[] cur, int[] add) { 1857 if (add == null) return cur; 1858 if (cur == null) return add; 1859 final int N = add.length; 1860 for (int i=0; i<N; i++) { 1861 cur = appendInt(cur, add[i]); 1862 } 1863 return cur; 1864 } 1865 1866 static int[] removeInts(int[] cur, int[] rem) { 1867 if (rem == null) return cur; 1868 if (cur == null) return cur; 1869 final int N = rem.length; 1870 for (int i=0; i<N; i++) { 1871 cur = removeInt(cur, rem[i]); 1872 } 1873 return cur; 1874 } 1875 1876 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1877 if (!sUserManager.exists(userId)) return null; 1878 final PackageSetting ps = (PackageSetting) p.mExtras; 1879 if (ps == null) { 1880 return null; 1881 } 1882 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1883 final PackageUserState state = ps.readUserState(userId); 1884 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1885 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1886 state, userId); 1887 } 1888 1889 @Override 1890 public boolean isPackageAvailable(String packageName, int userId) { 1891 if (!sUserManager.exists(userId)) return false; 1892 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1893 synchronized (mPackages) { 1894 PackageParser.Package p = mPackages.get(packageName); 1895 if (p != null) { 1896 final PackageSetting ps = (PackageSetting) p.mExtras; 1897 if (ps != null) { 1898 final PackageUserState state = ps.readUserState(userId); 1899 if (state != null) { 1900 return PackageParser.isAvailable(state); 1901 } 1902 } 1903 } 1904 } 1905 return false; 1906 } 1907 1908 @Override 1909 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1910 if (!sUserManager.exists(userId)) return null; 1911 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1912 // reader 1913 synchronized (mPackages) { 1914 PackageParser.Package p = mPackages.get(packageName); 1915 if (DEBUG_PACKAGE_INFO) 1916 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1917 if (p != null) { 1918 return generatePackageInfo(p, flags, userId); 1919 } 1920 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1921 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1922 } 1923 } 1924 return null; 1925 } 1926 1927 @Override 1928 public String[] currentToCanonicalPackageNames(String[] names) { 1929 String[] out = new String[names.length]; 1930 // reader 1931 synchronized (mPackages) { 1932 for (int i=names.length-1; i>=0; i--) { 1933 PackageSetting ps = mSettings.mPackages.get(names[i]); 1934 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1935 } 1936 } 1937 return out; 1938 } 1939 1940 @Override 1941 public String[] canonicalToCurrentPackageNames(String[] names) { 1942 String[] out = new String[names.length]; 1943 // reader 1944 synchronized (mPackages) { 1945 for (int i=names.length-1; i>=0; i--) { 1946 String cur = mSettings.mRenamedPackages.get(names[i]); 1947 out[i] = cur != null ? cur : names[i]; 1948 } 1949 } 1950 return out; 1951 } 1952 1953 @Override 1954 public int getPackageUid(String packageName, int userId) { 1955 if (!sUserManager.exists(userId)) return -1; 1956 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1957 // reader 1958 synchronized (mPackages) { 1959 PackageParser.Package p = mPackages.get(packageName); 1960 if(p != null) { 1961 return UserHandle.getUid(userId, p.applicationInfo.uid); 1962 } 1963 PackageSetting ps = mSettings.mPackages.get(packageName); 1964 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1965 return -1; 1966 } 1967 p = ps.pkg; 1968 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1969 } 1970 } 1971 1972 @Override 1973 public int[] getPackageGids(String packageName) { 1974 // reader 1975 synchronized (mPackages) { 1976 PackageParser.Package p = mPackages.get(packageName); 1977 if (DEBUG_PACKAGE_INFO) 1978 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1979 if (p != null) { 1980 final PackageSetting ps = (PackageSetting)p.mExtras; 1981 return ps.getGids(); 1982 } 1983 } 1984 // stupid thing to indicate an error. 1985 return new int[0]; 1986 } 1987 1988 static final PermissionInfo generatePermissionInfo( 1989 BasePermission bp, int flags) { 1990 if (bp.perm != null) { 1991 return PackageParser.generatePermissionInfo(bp.perm, flags); 1992 } 1993 PermissionInfo pi = new PermissionInfo(); 1994 pi.name = bp.name; 1995 pi.packageName = bp.sourcePackage; 1996 pi.nonLocalizedLabel = bp.name; 1997 pi.protectionLevel = bp.protectionLevel; 1998 return pi; 1999 } 2000 2001 @Override 2002 public PermissionInfo getPermissionInfo(String name, int flags) { 2003 // reader 2004 synchronized (mPackages) { 2005 final BasePermission p = mSettings.mPermissions.get(name); 2006 if (p != null) { 2007 return generatePermissionInfo(p, flags); 2008 } 2009 return null; 2010 } 2011 } 2012 2013 @Override 2014 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2015 // reader 2016 synchronized (mPackages) { 2017 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2018 for (BasePermission p : mSettings.mPermissions.values()) { 2019 if (group == null) { 2020 if (p.perm == null || p.perm.info.group == null) { 2021 out.add(generatePermissionInfo(p, flags)); 2022 } 2023 } else { 2024 if (p.perm != null && group.equals(p.perm.info.group)) { 2025 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2026 } 2027 } 2028 } 2029 2030 if (out.size() > 0) { 2031 return out; 2032 } 2033 return mPermissionGroups.containsKey(group) ? out : null; 2034 } 2035 } 2036 2037 @Override 2038 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2039 // reader 2040 synchronized (mPackages) { 2041 return PackageParser.generatePermissionGroupInfo( 2042 mPermissionGroups.get(name), flags); 2043 } 2044 } 2045 2046 @Override 2047 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2048 // reader 2049 synchronized (mPackages) { 2050 final int N = mPermissionGroups.size(); 2051 ArrayList<PermissionGroupInfo> out 2052 = new ArrayList<PermissionGroupInfo>(N); 2053 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2054 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2055 } 2056 return out; 2057 } 2058 } 2059 2060 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2061 int userId) { 2062 if (!sUserManager.exists(userId)) return null; 2063 PackageSetting ps = mSettings.mPackages.get(packageName); 2064 if (ps != null) { 2065 if (ps.pkg == null) { 2066 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2067 flags, userId); 2068 if (pInfo != null) { 2069 return pInfo.applicationInfo; 2070 } 2071 return null; 2072 } 2073 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2074 ps.readUserState(userId), userId); 2075 } 2076 return null; 2077 } 2078 2079 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2080 int userId) { 2081 if (!sUserManager.exists(userId)) return null; 2082 PackageSetting ps = mSettings.mPackages.get(packageName); 2083 if (ps != null) { 2084 PackageParser.Package pkg = ps.pkg; 2085 if (pkg == null) { 2086 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2087 return null; 2088 } 2089 // Only data remains, so we aren't worried about code paths 2090 pkg = new PackageParser.Package(packageName); 2091 pkg.applicationInfo.packageName = packageName; 2092 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2093 pkg.applicationInfo.dataDir = 2094 getDataPathForPackage(packageName, 0).getPath(); 2095 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2096 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2097 } 2098 return generatePackageInfo(pkg, flags, userId); 2099 } 2100 return null; 2101 } 2102 2103 @Override 2104 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2105 if (!sUserManager.exists(userId)) return null; 2106 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2107 // writer 2108 synchronized (mPackages) { 2109 PackageParser.Package p = mPackages.get(packageName); 2110 if (DEBUG_PACKAGE_INFO) Log.v( 2111 TAG, "getApplicationInfo " + packageName 2112 + ": " + p); 2113 if (p != null) { 2114 PackageSetting ps = mSettings.mPackages.get(packageName); 2115 if (ps == null) return null; 2116 // Note: isEnabledLP() does not apply here - always return info 2117 return PackageParser.generateApplicationInfo( 2118 p, flags, ps.readUserState(userId), userId); 2119 } 2120 if ("android".equals(packageName)||"system".equals(packageName)) { 2121 return mAndroidApplication; 2122 } 2123 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2124 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2125 } 2126 } 2127 return null; 2128 } 2129 2130 2131 @Override 2132 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2133 mContext.enforceCallingOrSelfPermission( 2134 android.Manifest.permission.CLEAR_APP_CACHE, null); 2135 // Queue up an async operation since clearing cache may take a little while. 2136 mHandler.post(new Runnable() { 2137 public void run() { 2138 mHandler.removeCallbacks(this); 2139 int retCode = -1; 2140 synchronized (mInstallLock) { 2141 retCode = mInstaller.freeCache(freeStorageSize); 2142 if (retCode < 0) { 2143 Slog.w(TAG, "Couldn't clear application caches"); 2144 } 2145 } 2146 if (observer != null) { 2147 try { 2148 observer.onRemoveCompleted(null, (retCode >= 0)); 2149 } catch (RemoteException e) { 2150 Slog.w(TAG, "RemoveException when invoking call back"); 2151 } 2152 } 2153 } 2154 }); 2155 } 2156 2157 @Override 2158 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2159 mContext.enforceCallingOrSelfPermission( 2160 android.Manifest.permission.CLEAR_APP_CACHE, null); 2161 // Queue up an async operation since clearing cache may take a little while. 2162 mHandler.post(new Runnable() { 2163 public void run() { 2164 mHandler.removeCallbacks(this); 2165 int retCode = -1; 2166 synchronized (mInstallLock) { 2167 retCode = mInstaller.freeCache(freeStorageSize); 2168 if (retCode < 0) { 2169 Slog.w(TAG, "Couldn't clear application caches"); 2170 } 2171 } 2172 if(pi != null) { 2173 try { 2174 // Callback via pending intent 2175 int code = (retCode >= 0) ? 1 : 0; 2176 pi.sendIntent(null, code, null, 2177 null, null); 2178 } catch (SendIntentException e1) { 2179 Slog.i(TAG, "Failed to send pending intent"); 2180 } 2181 } 2182 } 2183 }); 2184 } 2185 2186 void freeStorage(long freeStorageSize) throws IOException { 2187 synchronized (mInstallLock) { 2188 if (mInstaller.freeCache(freeStorageSize) < 0) { 2189 throw new IOException("Failed to free enough space"); 2190 } 2191 } 2192 } 2193 2194 @Override 2195 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2196 if (!sUserManager.exists(userId)) return null; 2197 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2198 synchronized (mPackages) { 2199 PackageParser.Activity a = mActivities.mActivities.get(component); 2200 2201 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2202 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2203 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2204 if (ps == null) return null; 2205 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2206 userId); 2207 } 2208 if (mResolveComponentName.equals(component)) { 2209 return mResolveActivity; 2210 } 2211 } 2212 return null; 2213 } 2214 2215 @Override 2216 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2217 String resolvedType) { 2218 synchronized (mPackages) { 2219 PackageParser.Activity a = mActivities.mActivities.get(component); 2220 if (a == null) { 2221 return false; 2222 } 2223 for (int i=0; i<a.intents.size(); i++) { 2224 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2225 intent.getData(), intent.getCategories(), TAG) >= 0) { 2226 return true; 2227 } 2228 } 2229 return false; 2230 } 2231 } 2232 2233 @Override 2234 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2235 if (!sUserManager.exists(userId)) return null; 2236 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2237 synchronized (mPackages) { 2238 PackageParser.Activity a = mReceivers.mActivities.get(component); 2239 if (DEBUG_PACKAGE_INFO) Log.v( 2240 TAG, "getReceiverInfo " + component + ": " + a); 2241 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2242 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2243 if (ps == null) return null; 2244 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2245 userId); 2246 } 2247 } 2248 return null; 2249 } 2250 2251 @Override 2252 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2253 if (!sUserManager.exists(userId)) return null; 2254 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2255 synchronized (mPackages) { 2256 PackageParser.Service s = mServices.mServices.get(component); 2257 if (DEBUG_PACKAGE_INFO) Log.v( 2258 TAG, "getServiceInfo " + component + ": " + s); 2259 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2260 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2261 if (ps == null) return null; 2262 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2263 userId); 2264 } 2265 } 2266 return null; 2267 } 2268 2269 @Override 2270 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2271 if (!sUserManager.exists(userId)) return null; 2272 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2273 synchronized (mPackages) { 2274 PackageParser.Provider p = mProviders.mProviders.get(component); 2275 if (DEBUG_PACKAGE_INFO) Log.v( 2276 TAG, "getProviderInfo " + component + ": " + p); 2277 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2278 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2279 if (ps == null) return null; 2280 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2281 userId); 2282 } 2283 } 2284 return null; 2285 } 2286 2287 @Override 2288 public String[] getSystemSharedLibraryNames() { 2289 Set<String> libSet; 2290 synchronized (mPackages) { 2291 libSet = mSharedLibraries.keySet(); 2292 int size = libSet.size(); 2293 if (size > 0) { 2294 String[] libs = new String[size]; 2295 libSet.toArray(libs); 2296 return libs; 2297 } 2298 } 2299 return null; 2300 } 2301 2302 @Override 2303 public FeatureInfo[] getSystemAvailableFeatures() { 2304 Collection<FeatureInfo> featSet; 2305 synchronized (mPackages) { 2306 featSet = mAvailableFeatures.values(); 2307 int size = featSet.size(); 2308 if (size > 0) { 2309 FeatureInfo[] features = new FeatureInfo[size+1]; 2310 featSet.toArray(features); 2311 FeatureInfo fi = new FeatureInfo(); 2312 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2313 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2314 features[size] = fi; 2315 return features; 2316 } 2317 } 2318 return null; 2319 } 2320 2321 @Override 2322 public boolean hasSystemFeature(String name) { 2323 synchronized (mPackages) { 2324 return mAvailableFeatures.containsKey(name); 2325 } 2326 } 2327 2328 private void checkValidCaller(int uid, int userId) { 2329 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2330 return; 2331 2332 throw new SecurityException("Caller uid=" + uid 2333 + " is not privileged to communicate with user=" + userId); 2334 } 2335 2336 @Override 2337 public int checkPermission(String permName, String pkgName) { 2338 synchronized (mPackages) { 2339 PackageParser.Package p = mPackages.get(pkgName); 2340 if (p != null && p.mExtras != null) { 2341 PackageSetting ps = (PackageSetting)p.mExtras; 2342 if (ps.sharedUser != null) { 2343 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2344 return PackageManager.PERMISSION_GRANTED; 2345 } 2346 } else if (ps.grantedPermissions.contains(permName)) { 2347 return PackageManager.PERMISSION_GRANTED; 2348 } 2349 } 2350 } 2351 return PackageManager.PERMISSION_DENIED; 2352 } 2353 2354 @Override 2355 public int checkUidPermission(String permName, int uid) { 2356 synchronized (mPackages) { 2357 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2358 if (obj != null) { 2359 GrantedPermissions gp = (GrantedPermissions)obj; 2360 if (gp.grantedPermissions.contains(permName)) { 2361 return PackageManager.PERMISSION_GRANTED; 2362 } 2363 } else { 2364 HashSet<String> perms = mSystemPermissions.get(uid); 2365 if (perms != null && perms.contains(permName)) { 2366 return PackageManager.PERMISSION_GRANTED; 2367 } 2368 } 2369 } 2370 return PackageManager.PERMISSION_DENIED; 2371 } 2372 2373 /** 2374 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2375 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2376 * @param message the message to log on security exception 2377 */ 2378 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2379 String message) { 2380 if (userId < 0) { 2381 throw new IllegalArgumentException("Invalid userId " + userId); 2382 } 2383 if (userId == UserHandle.getUserId(callingUid)) return; 2384 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2385 if (requireFullPermission) { 2386 mContext.enforceCallingOrSelfPermission( 2387 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2388 } else { 2389 try { 2390 mContext.enforceCallingOrSelfPermission( 2391 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2392 } catch (SecurityException se) { 2393 mContext.enforceCallingOrSelfPermission( 2394 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2395 } 2396 } 2397 } 2398 } 2399 2400 private BasePermission findPermissionTreeLP(String permName) { 2401 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2402 if (permName.startsWith(bp.name) && 2403 permName.length() > bp.name.length() && 2404 permName.charAt(bp.name.length()) == '.') { 2405 return bp; 2406 } 2407 } 2408 return null; 2409 } 2410 2411 private BasePermission checkPermissionTreeLP(String permName) { 2412 if (permName != null) { 2413 BasePermission bp = findPermissionTreeLP(permName); 2414 if (bp != null) { 2415 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2416 return bp; 2417 } 2418 throw new SecurityException("Calling uid " 2419 + Binder.getCallingUid() 2420 + " is not allowed to add to permission tree " 2421 + bp.name + " owned by uid " + bp.uid); 2422 } 2423 } 2424 throw new SecurityException("No permission tree found for " + permName); 2425 } 2426 2427 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2428 if (s1 == null) { 2429 return s2 == null; 2430 } 2431 if (s2 == null) { 2432 return false; 2433 } 2434 if (s1.getClass() != s2.getClass()) { 2435 return false; 2436 } 2437 return s1.equals(s2); 2438 } 2439 2440 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2441 if (pi1.icon != pi2.icon) return false; 2442 if (pi1.logo != pi2.logo) return false; 2443 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2444 if (!compareStrings(pi1.name, pi2.name)) return false; 2445 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2446 // We'll take care of setting this one. 2447 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2448 // These are not currently stored in settings. 2449 //if (!compareStrings(pi1.group, pi2.group)) return false; 2450 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2451 //if (pi1.labelRes != pi2.labelRes) return false; 2452 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2453 return true; 2454 } 2455 2456 int permissionInfoFootprint(PermissionInfo info) { 2457 int size = info.name.length(); 2458 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2459 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2460 return size; 2461 } 2462 2463 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2464 int size = 0; 2465 for (BasePermission perm : mSettings.mPermissions.values()) { 2466 if (perm.uid == tree.uid) { 2467 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2468 } 2469 } 2470 return size; 2471 } 2472 2473 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2474 // We calculate the max size of permissions defined by this uid and throw 2475 // if that plus the size of 'info' would exceed our stated maximum. 2476 if (tree.uid != Process.SYSTEM_UID) { 2477 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2478 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2479 throw new SecurityException("Permission tree size cap exceeded"); 2480 } 2481 } 2482 } 2483 2484 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2485 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2486 throw new SecurityException("Label must be specified in permission"); 2487 } 2488 BasePermission tree = checkPermissionTreeLP(info.name); 2489 BasePermission bp = mSettings.mPermissions.get(info.name); 2490 boolean added = bp == null; 2491 boolean changed = true; 2492 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2493 if (added) { 2494 enforcePermissionCapLocked(info, tree); 2495 bp = new BasePermission(info.name, tree.sourcePackage, 2496 BasePermission.TYPE_DYNAMIC); 2497 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2498 throw new SecurityException( 2499 "Not allowed to modify non-dynamic permission " 2500 + info.name); 2501 } else { 2502 if (bp.protectionLevel == fixedLevel 2503 && bp.perm.owner.equals(tree.perm.owner) 2504 && bp.uid == tree.uid 2505 && comparePermissionInfos(bp.perm.info, info)) { 2506 changed = false; 2507 } 2508 } 2509 bp.protectionLevel = fixedLevel; 2510 info = new PermissionInfo(info); 2511 info.protectionLevel = fixedLevel; 2512 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2513 bp.perm.info.packageName = tree.perm.info.packageName; 2514 bp.uid = tree.uid; 2515 if (added) { 2516 mSettings.mPermissions.put(info.name, bp); 2517 } 2518 if (changed) { 2519 if (!async) { 2520 mSettings.writeLPr(); 2521 } else { 2522 scheduleWriteSettingsLocked(); 2523 } 2524 } 2525 return added; 2526 } 2527 2528 @Override 2529 public boolean addPermission(PermissionInfo info) { 2530 synchronized (mPackages) { 2531 return addPermissionLocked(info, false); 2532 } 2533 } 2534 2535 @Override 2536 public boolean addPermissionAsync(PermissionInfo info) { 2537 synchronized (mPackages) { 2538 return addPermissionLocked(info, true); 2539 } 2540 } 2541 2542 @Override 2543 public void removePermission(String name) { 2544 synchronized (mPackages) { 2545 checkPermissionTreeLP(name); 2546 BasePermission bp = mSettings.mPermissions.get(name); 2547 if (bp != null) { 2548 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2549 throw new SecurityException( 2550 "Not allowed to modify non-dynamic permission " 2551 + name); 2552 } 2553 mSettings.mPermissions.remove(name); 2554 mSettings.writeLPr(); 2555 } 2556 } 2557 } 2558 2559 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2560 int index = pkg.requestedPermissions.indexOf(bp.name); 2561 if (index == -1) { 2562 throw new SecurityException("Package " + pkg.packageName 2563 + " has not requested permission " + bp.name); 2564 } 2565 boolean isNormal = 2566 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2567 == PermissionInfo.PROTECTION_NORMAL); 2568 boolean isDangerous = 2569 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2570 == PermissionInfo.PROTECTION_DANGEROUS); 2571 boolean isDevelopment = 2572 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2573 2574 if (!isNormal && !isDangerous && !isDevelopment) { 2575 throw new SecurityException("Permission " + bp.name 2576 + " is not a changeable permission type"); 2577 } 2578 2579 if (isNormal || isDangerous) { 2580 if (pkg.requestedPermissionsRequired.get(index)) { 2581 throw new SecurityException("Can't change " + bp.name 2582 + ". It is required by the application"); 2583 } 2584 } 2585 } 2586 2587 @Override 2588 public void grantPermission(String packageName, String permissionName) { 2589 mContext.enforceCallingOrSelfPermission( 2590 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2591 synchronized (mPackages) { 2592 final PackageParser.Package pkg = mPackages.get(packageName); 2593 if (pkg == null) { 2594 throw new IllegalArgumentException("Unknown package: " + packageName); 2595 } 2596 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2597 if (bp == null) { 2598 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2599 } 2600 2601 checkGrantRevokePermissions(pkg, bp); 2602 2603 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2604 if (ps == null) { 2605 return; 2606 } 2607 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2608 if (gp.grantedPermissions.add(permissionName)) { 2609 if (ps.haveGids) { 2610 gp.gids = appendInts(gp.gids, bp.gids); 2611 } 2612 mSettings.writeLPr(); 2613 } 2614 } 2615 } 2616 2617 @Override 2618 public void revokePermission(String packageName, String permissionName) { 2619 int changedAppId = -1; 2620 2621 synchronized (mPackages) { 2622 final PackageParser.Package pkg = mPackages.get(packageName); 2623 if (pkg == null) { 2624 throw new IllegalArgumentException("Unknown package: " + packageName); 2625 } 2626 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2627 mContext.enforceCallingOrSelfPermission( 2628 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2629 } 2630 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2631 if (bp == null) { 2632 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2633 } 2634 2635 checkGrantRevokePermissions(pkg, bp); 2636 2637 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2638 if (ps == null) { 2639 return; 2640 } 2641 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2642 if (gp.grantedPermissions.remove(permissionName)) { 2643 gp.grantedPermissions.remove(permissionName); 2644 if (ps.haveGids) { 2645 gp.gids = removeInts(gp.gids, bp.gids); 2646 } 2647 mSettings.writeLPr(); 2648 changedAppId = ps.appId; 2649 } 2650 } 2651 2652 if (changedAppId >= 0) { 2653 // We changed the perm on someone, kill its processes. 2654 IActivityManager am = ActivityManagerNative.getDefault(); 2655 if (am != null) { 2656 final int callingUserId = UserHandle.getCallingUserId(); 2657 final long ident = Binder.clearCallingIdentity(); 2658 try { 2659 //XXX we should only revoke for the calling user's app permissions, 2660 // but for now we impact all users. 2661 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2662 // "revoke " + permissionName); 2663 int[] users = sUserManager.getUserIds(); 2664 for (int user : users) { 2665 am.killUid(UserHandle.getUid(user, changedAppId), 2666 "revoke " + permissionName); 2667 } 2668 } catch (RemoteException e) { 2669 } finally { 2670 Binder.restoreCallingIdentity(ident); 2671 } 2672 } 2673 } 2674 } 2675 2676 @Override 2677 public boolean isProtectedBroadcast(String actionName) { 2678 synchronized (mPackages) { 2679 return mProtectedBroadcasts.contains(actionName); 2680 } 2681 } 2682 2683 @Override 2684 public int checkSignatures(String pkg1, String pkg2) { 2685 synchronized (mPackages) { 2686 final PackageParser.Package p1 = mPackages.get(pkg1); 2687 final PackageParser.Package p2 = mPackages.get(pkg2); 2688 if (p1 == null || p1.mExtras == null 2689 || p2 == null || p2.mExtras == null) { 2690 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2691 } 2692 return compareSignatures(p1.mSignatures, p2.mSignatures); 2693 } 2694 } 2695 2696 @Override 2697 public int checkUidSignatures(int uid1, int uid2) { 2698 // Map to base uids. 2699 uid1 = UserHandle.getAppId(uid1); 2700 uid2 = UserHandle.getAppId(uid2); 2701 // reader 2702 synchronized (mPackages) { 2703 Signature[] s1; 2704 Signature[] s2; 2705 Object obj = mSettings.getUserIdLPr(uid1); 2706 if (obj != null) { 2707 if (obj instanceof SharedUserSetting) { 2708 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2709 } else if (obj instanceof PackageSetting) { 2710 s1 = ((PackageSetting)obj).signatures.mSignatures; 2711 } else { 2712 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2713 } 2714 } else { 2715 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2716 } 2717 obj = mSettings.getUserIdLPr(uid2); 2718 if (obj != null) { 2719 if (obj instanceof SharedUserSetting) { 2720 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2721 } else if (obj instanceof PackageSetting) { 2722 s2 = ((PackageSetting)obj).signatures.mSignatures; 2723 } else { 2724 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2725 } 2726 } else { 2727 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2728 } 2729 return compareSignatures(s1, s2); 2730 } 2731 } 2732 2733 /** 2734 * Compares two sets of signatures. Returns: 2735 * <br /> 2736 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2737 * <br /> 2738 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2739 * <br /> 2740 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2741 * <br /> 2742 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2743 * <br /> 2744 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2745 */ 2746 static int compareSignatures(Signature[] s1, Signature[] s2) { 2747 if (s1 == null) { 2748 return s2 == null 2749 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2750 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2751 } 2752 2753 if (s2 == null) { 2754 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2755 } 2756 2757 if (s1.length != s2.length) { 2758 return PackageManager.SIGNATURE_NO_MATCH; 2759 } 2760 2761 // Since both signature sets are of size 1, we can compare without HashSets. 2762 if (s1.length == 1) { 2763 return s1[0].equals(s2[0]) ? 2764 PackageManager.SIGNATURE_MATCH : 2765 PackageManager.SIGNATURE_NO_MATCH; 2766 } 2767 2768 HashSet<Signature> set1 = new HashSet<Signature>(); 2769 for (Signature sig : s1) { 2770 set1.add(sig); 2771 } 2772 HashSet<Signature> set2 = new HashSet<Signature>(); 2773 for (Signature sig : s2) { 2774 set2.add(sig); 2775 } 2776 // Make sure s2 contains all signatures in s1. 2777 if (set1.equals(set2)) { 2778 return PackageManager.SIGNATURE_MATCH; 2779 } 2780 return PackageManager.SIGNATURE_NO_MATCH; 2781 } 2782 2783 /** 2784 * If the database version for this type of package (internal storage or 2785 * external storage) is less than the version where package signatures 2786 * were updated, return true. 2787 */ 2788 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2789 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2790 DatabaseVersion.SIGNATURE_END_ENTITY)) 2791 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2792 DatabaseVersion.SIGNATURE_END_ENTITY)); 2793 } 2794 2795 /** 2796 * Used for backward compatibility to make sure any packages with 2797 * certificate chains get upgraded to the new style. {@code existingSigs} 2798 * will be in the old format (since they were stored on disk from before the 2799 * system upgrade) and {@code scannedSigs} will be in the newer format. 2800 */ 2801 private int compareSignaturesCompat(PackageSignatures existingSigs, 2802 PackageParser.Package scannedPkg) { 2803 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2804 return PackageManager.SIGNATURE_NO_MATCH; 2805 } 2806 2807 HashSet<Signature> existingSet = new HashSet<Signature>(); 2808 for (Signature sig : existingSigs.mSignatures) { 2809 existingSet.add(sig); 2810 } 2811 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2812 for (Signature sig : scannedPkg.mSignatures) { 2813 try { 2814 Signature[] chainSignatures = sig.getChainSignatures(); 2815 for (Signature chainSig : chainSignatures) { 2816 scannedCompatSet.add(chainSig); 2817 } 2818 } catch (CertificateEncodingException e) { 2819 scannedCompatSet.add(sig); 2820 } 2821 } 2822 /* 2823 * Make sure the expanded scanned set contains all signatures in the 2824 * existing one. 2825 */ 2826 if (scannedCompatSet.equals(existingSet)) { 2827 // Migrate the old signatures to the new scheme. 2828 existingSigs.assignSignatures(scannedPkg.mSignatures); 2829 // The new KeySets will be re-added later in the scanning process. 2830 synchronized (mPackages) { 2831 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2832 } 2833 return PackageManager.SIGNATURE_MATCH; 2834 } 2835 return PackageManager.SIGNATURE_NO_MATCH; 2836 } 2837 2838 @Override 2839 public String[] getPackagesForUid(int uid) { 2840 uid = UserHandle.getAppId(uid); 2841 // reader 2842 synchronized (mPackages) { 2843 Object obj = mSettings.getUserIdLPr(uid); 2844 if (obj instanceof SharedUserSetting) { 2845 final SharedUserSetting sus = (SharedUserSetting) obj; 2846 final int N = sus.packages.size(); 2847 final String[] res = new String[N]; 2848 final Iterator<PackageSetting> it = sus.packages.iterator(); 2849 int i = 0; 2850 while (it.hasNext()) { 2851 res[i++] = it.next().name; 2852 } 2853 return res; 2854 } else if (obj instanceof PackageSetting) { 2855 final PackageSetting ps = (PackageSetting) obj; 2856 return new String[] { ps.name }; 2857 } 2858 } 2859 return null; 2860 } 2861 2862 @Override 2863 public String getNameForUid(int uid) { 2864 // reader 2865 synchronized (mPackages) { 2866 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2867 if (obj instanceof SharedUserSetting) { 2868 final SharedUserSetting sus = (SharedUserSetting) obj; 2869 return sus.name + ":" + sus.userId; 2870 } else if (obj instanceof PackageSetting) { 2871 final PackageSetting ps = (PackageSetting) obj; 2872 return ps.name; 2873 } 2874 } 2875 return null; 2876 } 2877 2878 @Override 2879 public int getUidForSharedUser(String sharedUserName) { 2880 if(sharedUserName == null) { 2881 return -1; 2882 } 2883 // reader 2884 synchronized (mPackages) { 2885 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2886 if (suid == null) { 2887 return -1; 2888 } 2889 return suid.userId; 2890 } 2891 } 2892 2893 @Override 2894 public int getFlagsForUid(int uid) { 2895 synchronized (mPackages) { 2896 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2897 if (obj instanceof SharedUserSetting) { 2898 final SharedUserSetting sus = (SharedUserSetting) obj; 2899 return sus.pkgFlags; 2900 } else if (obj instanceof PackageSetting) { 2901 final PackageSetting ps = (PackageSetting) obj; 2902 return ps.pkgFlags; 2903 } 2904 } 2905 return 0; 2906 } 2907 2908 @Override 2909 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2910 int flags, int userId) { 2911 if (!sUserManager.exists(userId)) return null; 2912 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2913 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2914 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2915 } 2916 2917 @Override 2918 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2919 IntentFilter filter, int match, ComponentName activity) { 2920 final int userId = UserHandle.getCallingUserId(); 2921 if (DEBUG_PREFERRED) { 2922 Log.v(TAG, "setLastChosenActivity intent=" + intent 2923 + " resolvedType=" + resolvedType 2924 + " flags=" + flags 2925 + " filter=" + filter 2926 + " match=" + match 2927 + " activity=" + activity); 2928 filter.dump(new PrintStreamPrinter(System.out), " "); 2929 } 2930 intent.setComponent(null); 2931 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2932 // Find any earlier preferred or last chosen entries and nuke them 2933 findPreferredActivity(intent, resolvedType, 2934 flags, query, 0, false, true, false, userId); 2935 // Add the new activity as the last chosen for this filter 2936 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2937 } 2938 2939 @Override 2940 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2941 final int userId = UserHandle.getCallingUserId(); 2942 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2943 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2944 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2945 false, false, false, userId); 2946 } 2947 2948 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2949 int flags, List<ResolveInfo> query, int userId) { 2950 if (query != null) { 2951 final int N = query.size(); 2952 if (N == 1) { 2953 return query.get(0); 2954 } else if (N > 1) { 2955 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2956 // If there is more than one activity with the same priority, 2957 // then let the user decide between them. 2958 ResolveInfo r0 = query.get(0); 2959 ResolveInfo r1 = query.get(1); 2960 if (DEBUG_INTENT_MATCHING || debug) { 2961 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2962 + r1.activityInfo.name + "=" + r1.priority); 2963 } 2964 // If the first activity has a higher priority, or a different 2965 // default, then it is always desireable to pick it. 2966 if (r0.priority != r1.priority 2967 || r0.preferredOrder != r1.preferredOrder 2968 || r0.isDefault != r1.isDefault) { 2969 return query.get(0); 2970 } 2971 // If we have saved a preference for a preferred activity for 2972 // this Intent, use that. 2973 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2974 flags, query, r0.priority, true, false, debug, userId); 2975 if (ri != null) { 2976 return ri; 2977 } 2978 if (userId != 0) { 2979 ri = new ResolveInfo(mResolveInfo); 2980 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2981 ri.activityInfo.applicationInfo = new ApplicationInfo( 2982 ri.activityInfo.applicationInfo); 2983 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2984 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2985 return ri; 2986 } 2987 return mResolveInfo; 2988 } 2989 } 2990 return null; 2991 } 2992 2993 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2994 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2995 final int N = query.size(); 2996 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2997 .get(userId); 2998 // Get the list of persistent preferred activities that handle the intent 2999 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3000 List<PersistentPreferredActivity> pprefs = ppir != null 3001 ? ppir.queryIntent(intent, resolvedType, 3002 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3003 : null; 3004 if (pprefs != null && pprefs.size() > 0) { 3005 final int M = pprefs.size(); 3006 for (int i=0; i<M; i++) { 3007 final PersistentPreferredActivity ppa = pprefs.get(i); 3008 if (DEBUG_PREFERRED || debug) { 3009 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3010 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3011 + "\n component=" + ppa.mComponent); 3012 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3013 } 3014 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3015 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3016 if (DEBUG_PREFERRED || debug) { 3017 Slog.v(TAG, "Found persistent preferred activity:"); 3018 if (ai != null) { 3019 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3020 } else { 3021 Slog.v(TAG, " null"); 3022 } 3023 } 3024 if (ai == null) { 3025 // This previously registered persistent preferred activity 3026 // component is no longer known. Ignore it and do NOT remove it. 3027 continue; 3028 } 3029 for (int j=0; j<N; j++) { 3030 final ResolveInfo ri = query.get(j); 3031 if (!ri.activityInfo.applicationInfo.packageName 3032 .equals(ai.applicationInfo.packageName)) { 3033 continue; 3034 } 3035 if (!ri.activityInfo.name.equals(ai.name)) { 3036 continue; 3037 } 3038 // Found a persistent preference that can handle the intent. 3039 if (DEBUG_PREFERRED || debug) { 3040 Slog.v(TAG, "Returning persistent preferred activity: " + 3041 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3042 } 3043 return ri; 3044 } 3045 } 3046 } 3047 return null; 3048 } 3049 3050 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3051 List<ResolveInfo> query, int priority, boolean always, 3052 boolean removeMatches, boolean debug, int userId) { 3053 if (!sUserManager.exists(userId)) return null; 3054 // writer 3055 synchronized (mPackages) { 3056 if (intent.getSelector() != null) { 3057 intent = intent.getSelector(); 3058 } 3059 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3060 3061 // Try to find a matching persistent preferred activity. 3062 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3063 debug, userId); 3064 3065 // If a persistent preferred activity matched, use it. 3066 if (pri != null) { 3067 return pri; 3068 } 3069 3070 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3071 // Get the list of preferred activities that handle the intent 3072 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3073 List<PreferredActivity> prefs = pir != null 3074 ? pir.queryIntent(intent, resolvedType, 3075 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3076 : null; 3077 if (prefs != null && prefs.size() > 0) { 3078 // First figure out how good the original match set is. 3079 // We will only allow preferred activities that came 3080 // from the same match quality. 3081 int match = 0; 3082 3083 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3084 3085 final int N = query.size(); 3086 for (int j=0; j<N; j++) { 3087 final ResolveInfo ri = query.get(j); 3088 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3089 + ": 0x" + Integer.toHexString(match)); 3090 if (ri.match > match) { 3091 match = ri.match; 3092 } 3093 } 3094 3095 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3096 + Integer.toHexString(match)); 3097 3098 match &= IntentFilter.MATCH_CATEGORY_MASK; 3099 final int M = prefs.size(); 3100 for (int i=0; i<M; i++) { 3101 final PreferredActivity pa = prefs.get(i); 3102 if (DEBUG_PREFERRED || debug) { 3103 Slog.v(TAG, "Checking PreferredActivity ds=" 3104 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3105 + "\n component=" + pa.mPref.mComponent); 3106 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3107 } 3108 if (pa.mPref.mMatch != match) { 3109 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3110 + Integer.toHexString(pa.mPref.mMatch)); 3111 continue; 3112 } 3113 // If it's not an "always" type preferred activity and that's what we're 3114 // looking for, skip it. 3115 if (always && !pa.mPref.mAlways) { 3116 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3117 continue; 3118 } 3119 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3120 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3121 if (DEBUG_PREFERRED || debug) { 3122 Slog.v(TAG, "Found preferred activity:"); 3123 if (ai != null) { 3124 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3125 } else { 3126 Slog.v(TAG, " null"); 3127 } 3128 } 3129 if (ai == null) { 3130 // This previously registered preferred activity 3131 // component is no longer known. Most likely an update 3132 // to the app was installed and in the new version this 3133 // component no longer exists. Clean it up by removing 3134 // it from the preferred activities list, and skip it. 3135 Slog.w(TAG, "Removing dangling preferred activity: " 3136 + pa.mPref.mComponent); 3137 pir.removeFilter(pa); 3138 continue; 3139 } 3140 for (int j=0; j<N; j++) { 3141 final ResolveInfo ri = query.get(j); 3142 if (!ri.activityInfo.applicationInfo.packageName 3143 .equals(ai.applicationInfo.packageName)) { 3144 continue; 3145 } 3146 if (!ri.activityInfo.name.equals(ai.name)) { 3147 continue; 3148 } 3149 3150 if (removeMatches) { 3151 pir.removeFilter(pa); 3152 if (DEBUG_PREFERRED) { 3153 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3154 } 3155 break; 3156 } 3157 3158 // Okay we found a previously set preferred or last chosen app. 3159 // If the result set is different from when this 3160 // was created, we need to clear it and re-ask the 3161 // user their preference, if we're looking for an "always" type entry. 3162 if (always && !pa.mPref.sameSet(query, priority)) { 3163 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3164 + intent + " type " + resolvedType); 3165 if (DEBUG_PREFERRED) { 3166 Slog.v(TAG, "Removing preferred activity since set changed " 3167 + pa.mPref.mComponent); 3168 } 3169 pir.removeFilter(pa); 3170 // Re-add the filter as a "last chosen" entry (!always) 3171 PreferredActivity lastChosen = new PreferredActivity( 3172 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3173 pir.addFilter(lastChosen); 3174 mSettings.writePackageRestrictionsLPr(userId); 3175 return null; 3176 } 3177 3178 // Yay! Either the set matched or we're looking for the last chosen 3179 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3180 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3181 mSettings.writePackageRestrictionsLPr(userId); 3182 return ri; 3183 } 3184 } 3185 } 3186 mSettings.writePackageRestrictionsLPr(userId); 3187 } 3188 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3189 return null; 3190 } 3191 3192 /* 3193 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3194 */ 3195 @Override 3196 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3197 int targetUserId) { 3198 mContext.enforceCallingOrSelfPermission( 3199 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3200 List<CrossProfileIntentFilter> matches = 3201 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3202 if (matches != null) { 3203 int size = matches.size(); 3204 for (int i = 0; i < size; i++) { 3205 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3206 } 3207 } 3208 3209 ArrayList<String> packageNames = null; 3210 SparseArray<ArrayList<String>> fromSource = 3211 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3212 if (fromSource != null) { 3213 packageNames = fromSource.get(targetUserId); 3214 } 3215 if (packageNames.contains(intent.getPackage())) { 3216 return true; 3217 } 3218 // We need the package name, so we try to resolve with the loosest flags possible 3219 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3220 intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3221 int count = resolveInfos.size(); 3222 for (int i = 0; i < count; i++) { 3223 ResolveInfo resolveInfo = resolveInfos.get(i); 3224 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3225 return true; 3226 } 3227 } 3228 return false; 3229 } 3230 3231 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3232 String resolvedType, int userId) { 3233 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3234 if (resolver != null) { 3235 return resolver.queryIntent(intent, resolvedType, false, userId); 3236 } 3237 return null; 3238 } 3239 3240 @Override 3241 public List<ResolveInfo> queryIntentActivities(Intent intent, 3242 String resolvedType, int flags, int userId) { 3243 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3244 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3245 ComponentName comp = intent.getComponent(); 3246 if (comp == null) { 3247 if (intent.getSelector() != null) { 3248 intent = intent.getSelector(); 3249 comp = intent.getComponent(); 3250 } 3251 } 3252 3253 if (comp != null) { 3254 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3255 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3256 if (ai != null) { 3257 final ResolveInfo ri = new ResolveInfo(); 3258 ri.activityInfo = ai; 3259 list.add(ri); 3260 } 3261 return list; 3262 } 3263 3264 // reader 3265 synchronized (mPackages) { 3266 final String pkgName = intent.getPackage(); 3267 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3268 if (pkgName == null) { 3269 ResolveInfo resolveInfo = null; 3270 if (queryCrossProfile) { 3271 // Check if the intent needs to be forwarded to another user for this package 3272 ArrayList<ResolveInfo> crossProfileResult = 3273 queryIntentActivitiesCrossProfilePackage( 3274 intent, resolvedType, flags, userId); 3275 if (!crossProfileResult.isEmpty()) { 3276 // Skip the current profile 3277 return crossProfileResult; 3278 } 3279 List<CrossProfileIntentFilter> matchingFilters = 3280 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3281 // Check for results that need to skip the current profile. 3282 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3283 resolvedType, flags, userId); 3284 if (resolveInfo != null) { 3285 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3286 result.add(resolveInfo); 3287 return result; 3288 } 3289 // Check for cross profile results. 3290 resolveInfo = queryCrossProfileIntents( 3291 matchingFilters, intent, resolvedType, flags, userId); 3292 } 3293 // Check for results in the current profile. 3294 List<ResolveInfo> result = mActivities.queryIntent( 3295 intent, resolvedType, flags, userId); 3296 if (resolveInfo != null) { 3297 result.add(resolveInfo); 3298 } 3299 return result; 3300 } 3301 final PackageParser.Package pkg = mPackages.get(pkgName); 3302 if (pkg != null) { 3303 if (queryCrossProfile) { 3304 ArrayList<ResolveInfo> crossProfileResult = 3305 queryIntentActivitiesCrossProfilePackage( 3306 intent, resolvedType, flags, userId, pkg, pkgName); 3307 if (!crossProfileResult.isEmpty()) { 3308 // Skip the current profile 3309 return crossProfileResult; 3310 } 3311 } 3312 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3313 pkg.activities, userId); 3314 } 3315 return new ArrayList<ResolveInfo>(); 3316 } 3317 } 3318 3319 private ResolveInfo querySkipCurrentProfileIntents( 3320 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3321 int flags, int sourceUserId) { 3322 if (matchingFilters != null) { 3323 int size = matchingFilters.size(); 3324 for (int i = 0; i < size; i ++) { 3325 CrossProfileIntentFilter filter = matchingFilters.get(i); 3326 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3327 // Checking if there are activities in the target user that can handle the 3328 // intent. 3329 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3330 flags, sourceUserId); 3331 if (resolveInfo != null) { 3332 return resolveInfo; 3333 } 3334 } 3335 } 3336 } 3337 return null; 3338 } 3339 3340 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3341 Intent intent, String resolvedType, int flags, int userId) { 3342 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3343 SparseArray<ArrayList<String>> sourceForwardingInfo = 3344 mSettings.mCrossProfilePackageInfo.get(userId); 3345 if (sourceForwardingInfo != null) { 3346 int NI = sourceForwardingInfo.size(); 3347 for (int i = 0; i < NI; i++) { 3348 int targetUserId = sourceForwardingInfo.keyAt(i); 3349 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3350 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3351 intent, resolvedType, flags, targetUserId); 3352 int NJ = resolveInfos.size(); 3353 for (int j = 0; j < NJ; j++) { 3354 ResolveInfo resolveInfo = resolveInfos.get(j); 3355 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3356 matchingResolveInfos.add(createForwardingResolveInfo( 3357 resolveInfo.filter, userId, targetUserId)); 3358 } 3359 } 3360 } 3361 } 3362 return matchingResolveInfos; 3363 } 3364 3365 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3366 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3367 String packageName) { 3368 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3369 SparseArray<ArrayList<String>> sourceForwardingInfo = 3370 mSettings.mCrossProfilePackageInfo.get(userId); 3371 if (sourceForwardingInfo != null) { 3372 int NI = sourceForwardingInfo.size(); 3373 for (int i = 0; i < NI; i++) { 3374 int targetUserId = sourceForwardingInfo.keyAt(i); 3375 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3376 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3377 intent, resolvedType, flags, pkg.activities, targetUserId); 3378 int NJ = resolveInfos.size(); 3379 for (int j = 0; j < NJ; j++) { 3380 ResolveInfo resolveInfo = resolveInfos.get(j); 3381 matchingResolveInfos.add(createForwardingResolveInfo( 3382 resolveInfo.filter, userId, targetUserId)); 3383 } 3384 } 3385 } 3386 } 3387 return matchingResolveInfos; 3388 } 3389 3390 // Return matching ResolveInfo if any for skip current profile intent filters. 3391 private ResolveInfo queryCrossProfileIntents( 3392 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3393 int flags, int sourceUserId) { 3394 if (matchingFilters != null) { 3395 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3396 // match the same intent. For performance reasons, it is better not to 3397 // run queryIntent twice for the same userId 3398 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3399 int size = matchingFilters.size(); 3400 for (int i = 0; i < size; i++) { 3401 CrossProfileIntentFilter filter = matchingFilters.get(i); 3402 int targetUserId = filter.getTargetUserId(); 3403 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3404 && !alreadyTriedUserIds.get(targetUserId)) { 3405 // Checking if there are activities in the target user that can handle the 3406 // intent. 3407 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3408 flags, sourceUserId); 3409 if (resolveInfo != null) return resolveInfo; 3410 alreadyTriedUserIds.put(targetUserId, true); 3411 } 3412 } 3413 } 3414 return null; 3415 } 3416 3417 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3418 String resolvedType, int flags, int sourceUserId) { 3419 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3420 resolvedType, flags, filter.getTargetUserId()); 3421 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3422 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3423 } 3424 return null; 3425 } 3426 3427 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3428 int sourceUserId, int targetUserId) { 3429 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3430 String className; 3431 if (targetUserId == UserHandle.USER_OWNER) { 3432 className = FORWARD_INTENT_TO_USER_OWNER; 3433 } else { 3434 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3435 } 3436 ComponentName forwardingActivityComponentName = new ComponentName( 3437 mAndroidApplication.packageName, className); 3438 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3439 sourceUserId); 3440 if (targetUserId == UserHandle.USER_OWNER) { 3441 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3442 forwardingResolveInfo.noResourceId = true; 3443 } 3444 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3445 forwardingResolveInfo.priority = 0; 3446 forwardingResolveInfo.preferredOrder = 0; 3447 forwardingResolveInfo.match = 0; 3448 forwardingResolveInfo.isDefault = true; 3449 forwardingResolveInfo.filter = filter; 3450 forwardingResolveInfo.targetUserId = targetUserId; 3451 return forwardingResolveInfo; 3452 } 3453 3454 @Override 3455 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3456 Intent[] specifics, String[] specificTypes, Intent intent, 3457 String resolvedType, int flags, int userId) { 3458 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3459 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3460 "query intent activity options"); 3461 final String resultsAction = intent.getAction(); 3462 3463 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3464 | PackageManager.GET_RESOLVED_FILTER, userId); 3465 3466 if (DEBUG_INTENT_MATCHING) { 3467 Log.v(TAG, "Query " + intent + ": " + results); 3468 } 3469 3470 int specificsPos = 0; 3471 int N; 3472 3473 // todo: note that the algorithm used here is O(N^2). This 3474 // isn't a problem in our current environment, but if we start running 3475 // into situations where we have more than 5 or 10 matches then this 3476 // should probably be changed to something smarter... 3477 3478 // First we go through and resolve each of the specific items 3479 // that were supplied, taking care of removing any corresponding 3480 // duplicate items in the generic resolve list. 3481 if (specifics != null) { 3482 for (int i=0; i<specifics.length; i++) { 3483 final Intent sintent = specifics[i]; 3484 if (sintent == null) { 3485 continue; 3486 } 3487 3488 if (DEBUG_INTENT_MATCHING) { 3489 Log.v(TAG, "Specific #" + i + ": " + sintent); 3490 } 3491 3492 String action = sintent.getAction(); 3493 if (resultsAction != null && resultsAction.equals(action)) { 3494 // If this action was explicitly requested, then don't 3495 // remove things that have it. 3496 action = null; 3497 } 3498 3499 ResolveInfo ri = null; 3500 ActivityInfo ai = null; 3501 3502 ComponentName comp = sintent.getComponent(); 3503 if (comp == null) { 3504 ri = resolveIntent( 3505 sintent, 3506 specificTypes != null ? specificTypes[i] : null, 3507 flags, userId); 3508 if (ri == null) { 3509 continue; 3510 } 3511 if (ri == mResolveInfo) { 3512 // ACK! Must do something better with this. 3513 } 3514 ai = ri.activityInfo; 3515 comp = new ComponentName(ai.applicationInfo.packageName, 3516 ai.name); 3517 } else { 3518 ai = getActivityInfo(comp, flags, userId); 3519 if (ai == null) { 3520 continue; 3521 } 3522 } 3523 3524 // Look for any generic query activities that are duplicates 3525 // of this specific one, and remove them from the results. 3526 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3527 N = results.size(); 3528 int j; 3529 for (j=specificsPos; j<N; j++) { 3530 ResolveInfo sri = results.get(j); 3531 if ((sri.activityInfo.name.equals(comp.getClassName()) 3532 && sri.activityInfo.applicationInfo.packageName.equals( 3533 comp.getPackageName())) 3534 || (action != null && sri.filter.matchAction(action))) { 3535 results.remove(j); 3536 if (DEBUG_INTENT_MATCHING) Log.v( 3537 TAG, "Removing duplicate item from " + j 3538 + " due to specific " + specificsPos); 3539 if (ri == null) { 3540 ri = sri; 3541 } 3542 j--; 3543 N--; 3544 } 3545 } 3546 3547 // Add this specific item to its proper place. 3548 if (ri == null) { 3549 ri = new ResolveInfo(); 3550 ri.activityInfo = ai; 3551 } 3552 results.add(specificsPos, ri); 3553 ri.specificIndex = i; 3554 specificsPos++; 3555 } 3556 } 3557 3558 // Now we go through the remaining generic results and remove any 3559 // duplicate actions that are found here. 3560 N = results.size(); 3561 for (int i=specificsPos; i<N-1; i++) { 3562 final ResolveInfo rii = results.get(i); 3563 if (rii.filter == null) { 3564 continue; 3565 } 3566 3567 // Iterate over all of the actions of this result's intent 3568 // filter... typically this should be just one. 3569 final Iterator<String> it = rii.filter.actionsIterator(); 3570 if (it == null) { 3571 continue; 3572 } 3573 while (it.hasNext()) { 3574 final String action = it.next(); 3575 if (resultsAction != null && resultsAction.equals(action)) { 3576 // If this action was explicitly requested, then don't 3577 // remove things that have it. 3578 continue; 3579 } 3580 for (int j=i+1; j<N; j++) { 3581 final ResolveInfo rij = results.get(j); 3582 if (rij.filter != null && rij.filter.hasAction(action)) { 3583 results.remove(j); 3584 if (DEBUG_INTENT_MATCHING) Log.v( 3585 TAG, "Removing duplicate item from " + j 3586 + " due to action " + action + " at " + i); 3587 j--; 3588 N--; 3589 } 3590 } 3591 } 3592 3593 // If the caller didn't request filter information, drop it now 3594 // so we don't have to marshall/unmarshall it. 3595 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3596 rii.filter = null; 3597 } 3598 } 3599 3600 // Filter out the caller activity if so requested. 3601 if (caller != null) { 3602 N = results.size(); 3603 for (int i=0; i<N; i++) { 3604 ActivityInfo ainfo = results.get(i).activityInfo; 3605 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3606 && caller.getClassName().equals(ainfo.name)) { 3607 results.remove(i); 3608 break; 3609 } 3610 } 3611 } 3612 3613 // If the caller didn't request filter information, 3614 // drop them now so we don't have to 3615 // marshall/unmarshall it. 3616 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3617 N = results.size(); 3618 for (int i=0; i<N; i++) { 3619 results.get(i).filter = null; 3620 } 3621 } 3622 3623 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3624 return results; 3625 } 3626 3627 @Override 3628 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3629 int userId) { 3630 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3631 ComponentName comp = intent.getComponent(); 3632 if (comp == null) { 3633 if (intent.getSelector() != null) { 3634 intent = intent.getSelector(); 3635 comp = intent.getComponent(); 3636 } 3637 } 3638 if (comp != null) { 3639 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3640 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3641 if (ai != null) { 3642 ResolveInfo ri = new ResolveInfo(); 3643 ri.activityInfo = ai; 3644 list.add(ri); 3645 } 3646 return list; 3647 } 3648 3649 // reader 3650 synchronized (mPackages) { 3651 String pkgName = intent.getPackage(); 3652 if (pkgName == null) { 3653 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3654 } 3655 final PackageParser.Package pkg = mPackages.get(pkgName); 3656 if (pkg != null) { 3657 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3658 userId); 3659 } 3660 return null; 3661 } 3662 } 3663 3664 @Override 3665 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3666 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3667 if (!sUserManager.exists(userId)) return null; 3668 if (query != null) { 3669 if (query.size() >= 1) { 3670 // If there is more than one service with the same priority, 3671 // just arbitrarily pick the first one. 3672 return query.get(0); 3673 } 3674 } 3675 return null; 3676 } 3677 3678 @Override 3679 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3680 int userId) { 3681 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3682 ComponentName comp = intent.getComponent(); 3683 if (comp == null) { 3684 if (intent.getSelector() != null) { 3685 intent = intent.getSelector(); 3686 comp = intent.getComponent(); 3687 } 3688 } 3689 if (comp != null) { 3690 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3691 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3692 if (si != null) { 3693 final ResolveInfo ri = new ResolveInfo(); 3694 ri.serviceInfo = si; 3695 list.add(ri); 3696 } 3697 return list; 3698 } 3699 3700 // reader 3701 synchronized (mPackages) { 3702 String pkgName = intent.getPackage(); 3703 if (pkgName == null) { 3704 return mServices.queryIntent(intent, resolvedType, flags, userId); 3705 } 3706 final PackageParser.Package pkg = mPackages.get(pkgName); 3707 if (pkg != null) { 3708 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3709 userId); 3710 } 3711 return null; 3712 } 3713 } 3714 3715 @Override 3716 public List<ResolveInfo> queryIntentContentProviders( 3717 Intent intent, String resolvedType, int flags, int userId) { 3718 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3719 ComponentName comp = intent.getComponent(); 3720 if (comp == null) { 3721 if (intent.getSelector() != null) { 3722 intent = intent.getSelector(); 3723 comp = intent.getComponent(); 3724 } 3725 } 3726 if (comp != null) { 3727 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3728 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3729 if (pi != null) { 3730 final ResolveInfo ri = new ResolveInfo(); 3731 ri.providerInfo = pi; 3732 list.add(ri); 3733 } 3734 return list; 3735 } 3736 3737 // reader 3738 synchronized (mPackages) { 3739 String pkgName = intent.getPackage(); 3740 if (pkgName == null) { 3741 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3742 } 3743 final PackageParser.Package pkg = mPackages.get(pkgName); 3744 if (pkg != null) { 3745 return mProviders.queryIntentForPackage( 3746 intent, resolvedType, flags, pkg.providers, userId); 3747 } 3748 return null; 3749 } 3750 } 3751 3752 @Override 3753 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3754 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3755 3756 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3757 3758 // writer 3759 synchronized (mPackages) { 3760 ArrayList<PackageInfo> list; 3761 if (listUninstalled) { 3762 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3763 for (PackageSetting ps : mSettings.mPackages.values()) { 3764 PackageInfo pi; 3765 if (ps.pkg != null) { 3766 pi = generatePackageInfo(ps.pkg, flags, userId); 3767 } else { 3768 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3769 } 3770 if (pi != null) { 3771 list.add(pi); 3772 } 3773 } 3774 } else { 3775 list = new ArrayList<PackageInfo>(mPackages.size()); 3776 for (PackageParser.Package p : mPackages.values()) { 3777 PackageInfo pi = generatePackageInfo(p, flags, userId); 3778 if (pi != null) { 3779 list.add(pi); 3780 } 3781 } 3782 } 3783 3784 return new ParceledListSlice<PackageInfo>(list); 3785 } 3786 } 3787 3788 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3789 String[] permissions, boolean[] tmp, int flags, int userId) { 3790 int numMatch = 0; 3791 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3792 for (int i=0; i<permissions.length; i++) { 3793 if (gp.grantedPermissions.contains(permissions[i])) { 3794 tmp[i] = true; 3795 numMatch++; 3796 } else { 3797 tmp[i] = false; 3798 } 3799 } 3800 if (numMatch == 0) { 3801 return; 3802 } 3803 PackageInfo pi; 3804 if (ps.pkg != null) { 3805 pi = generatePackageInfo(ps.pkg, flags, userId); 3806 } else { 3807 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3808 } 3809 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3810 if (numMatch == permissions.length) { 3811 pi.requestedPermissions = permissions; 3812 } else { 3813 pi.requestedPermissions = new String[numMatch]; 3814 numMatch = 0; 3815 for (int i=0; i<permissions.length; i++) { 3816 if (tmp[i]) { 3817 pi.requestedPermissions[numMatch] = permissions[i]; 3818 numMatch++; 3819 } 3820 } 3821 } 3822 } 3823 list.add(pi); 3824 } 3825 3826 @Override 3827 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3828 String[] permissions, int flags, int userId) { 3829 if (!sUserManager.exists(userId)) return null; 3830 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3831 3832 // writer 3833 synchronized (mPackages) { 3834 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3835 boolean[] tmpBools = new boolean[permissions.length]; 3836 if (listUninstalled) { 3837 for (PackageSetting ps : mSettings.mPackages.values()) { 3838 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3839 } 3840 } else { 3841 for (PackageParser.Package pkg : mPackages.values()) { 3842 PackageSetting ps = (PackageSetting)pkg.mExtras; 3843 if (ps != null) { 3844 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3845 userId); 3846 } 3847 } 3848 } 3849 3850 return new ParceledListSlice<PackageInfo>(list); 3851 } 3852 } 3853 3854 @Override 3855 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3856 if (!sUserManager.exists(userId)) return null; 3857 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3858 3859 // writer 3860 synchronized (mPackages) { 3861 ArrayList<ApplicationInfo> list; 3862 if (listUninstalled) { 3863 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3864 for (PackageSetting ps : mSettings.mPackages.values()) { 3865 ApplicationInfo ai; 3866 if (ps.pkg != null) { 3867 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3868 ps.readUserState(userId), userId); 3869 } else { 3870 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3871 } 3872 if (ai != null) { 3873 list.add(ai); 3874 } 3875 } 3876 } else { 3877 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3878 for (PackageParser.Package p : mPackages.values()) { 3879 if (p.mExtras != null) { 3880 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3881 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3882 if (ai != null) { 3883 list.add(ai); 3884 } 3885 } 3886 } 3887 } 3888 3889 return new ParceledListSlice<ApplicationInfo>(list); 3890 } 3891 } 3892 3893 public List<ApplicationInfo> getPersistentApplications(int flags) { 3894 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3895 3896 // reader 3897 synchronized (mPackages) { 3898 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3899 final int userId = UserHandle.getCallingUserId(); 3900 while (i.hasNext()) { 3901 final PackageParser.Package p = i.next(); 3902 if (p.applicationInfo != null 3903 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3904 && (!mSafeMode || isSystemApp(p))) { 3905 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3906 if (ps != null) { 3907 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3908 ps.readUserState(userId), userId); 3909 if (ai != null) { 3910 finalList.add(ai); 3911 } 3912 } 3913 } 3914 } 3915 } 3916 3917 return finalList; 3918 } 3919 3920 @Override 3921 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3922 if (!sUserManager.exists(userId)) return null; 3923 // reader 3924 synchronized (mPackages) { 3925 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3926 PackageSetting ps = provider != null 3927 ? mSettings.mPackages.get(provider.owner.packageName) 3928 : null; 3929 return ps != null 3930 && mSettings.isEnabledLPr(provider.info, flags, userId) 3931 && (!mSafeMode || (provider.info.applicationInfo.flags 3932 &ApplicationInfo.FLAG_SYSTEM) != 0) 3933 ? PackageParser.generateProviderInfo(provider, flags, 3934 ps.readUserState(userId), userId) 3935 : null; 3936 } 3937 } 3938 3939 /** 3940 * @deprecated 3941 */ 3942 @Deprecated 3943 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3944 // reader 3945 synchronized (mPackages) { 3946 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3947 .entrySet().iterator(); 3948 final int userId = UserHandle.getCallingUserId(); 3949 while (i.hasNext()) { 3950 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3951 PackageParser.Provider p = entry.getValue(); 3952 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3953 3954 if (ps != null && p.syncable 3955 && (!mSafeMode || (p.info.applicationInfo.flags 3956 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3957 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3958 ps.readUserState(userId), userId); 3959 if (info != null) { 3960 outNames.add(entry.getKey()); 3961 outInfo.add(info); 3962 } 3963 } 3964 } 3965 } 3966 } 3967 3968 @Override 3969 public List<ProviderInfo> queryContentProviders(String processName, 3970 int uid, int flags) { 3971 ArrayList<ProviderInfo> finalList = null; 3972 // reader 3973 synchronized (mPackages) { 3974 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3975 final int userId = processName != null ? 3976 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3977 while (i.hasNext()) { 3978 final PackageParser.Provider p = i.next(); 3979 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3980 if (ps != null && p.info.authority != null 3981 && (processName == null 3982 || (p.info.processName.equals(processName) 3983 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3984 && mSettings.isEnabledLPr(p.info, flags, userId) 3985 && (!mSafeMode 3986 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3987 if (finalList == null) { 3988 finalList = new ArrayList<ProviderInfo>(3); 3989 } 3990 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3991 ps.readUserState(userId), userId); 3992 if (info != null) { 3993 finalList.add(info); 3994 } 3995 } 3996 } 3997 } 3998 3999 if (finalList != null) { 4000 Collections.sort(finalList, mProviderInitOrderSorter); 4001 } 4002 4003 return finalList; 4004 } 4005 4006 @Override 4007 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4008 int flags) { 4009 // reader 4010 synchronized (mPackages) { 4011 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4012 return PackageParser.generateInstrumentationInfo(i, flags); 4013 } 4014 } 4015 4016 @Override 4017 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4018 int flags) { 4019 ArrayList<InstrumentationInfo> finalList = 4020 new ArrayList<InstrumentationInfo>(); 4021 4022 // reader 4023 synchronized (mPackages) { 4024 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4025 while (i.hasNext()) { 4026 final PackageParser.Instrumentation p = i.next(); 4027 if (targetPackage == null 4028 || targetPackage.equals(p.info.targetPackage)) { 4029 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4030 flags); 4031 if (ii != null) { 4032 finalList.add(ii); 4033 } 4034 } 4035 } 4036 } 4037 4038 return finalList; 4039 } 4040 4041 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4042 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4043 if (overlays == null) { 4044 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4045 return; 4046 } 4047 for (PackageParser.Package opkg : overlays.values()) { 4048 // Not much to do if idmap fails: we already logged the error 4049 // and we certainly don't want to abort installation of pkg simply 4050 // because an overlay didn't fit properly. For these reasons, 4051 // ignore the return value of createIdmapForPackagePairLI. 4052 createIdmapForPackagePairLI(pkg, opkg); 4053 } 4054 } 4055 4056 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4057 PackageParser.Package opkg) { 4058 if (!opkg.mTrustedOverlay) { 4059 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4060 opkg.baseCodePath + ": overlay not trusted"); 4061 return false; 4062 } 4063 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4064 if (overlaySet == null) { 4065 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4066 opkg.baseCodePath + " but target package has no known overlays"); 4067 return false; 4068 } 4069 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4070 // TODO: generate idmap for split APKs 4071 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4072 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4073 + opkg.baseCodePath); 4074 return false; 4075 } 4076 PackageParser.Package[] overlayArray = 4077 overlaySet.values().toArray(new PackageParser.Package[0]); 4078 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4079 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4080 return p1.mOverlayPriority - p2.mOverlayPriority; 4081 } 4082 }; 4083 Arrays.sort(overlayArray, cmp); 4084 4085 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4086 int i = 0; 4087 for (PackageParser.Package p : overlayArray) { 4088 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4089 } 4090 return true; 4091 } 4092 4093 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4094 final File[] files = dir.listFiles(); 4095 if (ArrayUtils.isEmpty(files)) { 4096 Log.d(TAG, "No files in app dir " + dir); 4097 return; 4098 } 4099 4100 if (DEBUG_PACKAGE_SCANNING) { 4101 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4102 + " flags=0x" + Integer.toHexString(flags)); 4103 } 4104 4105 for (File file : files) { 4106 final boolean isPackage = isApkFile(file) || file.isDirectory(); 4107 if (!isPackage) { 4108 // Ignore entries which are not apk's 4109 continue; 4110 } 4111 try { 4112 scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, 4113 null, null); 4114 } catch (PackageManagerException e) { 4115 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4116 4117 // Don't mess around with apps in system partition. 4118 if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4119 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4120 // Delete the apk 4121 Slog.w(TAG, "Cleaning up failed install of " + file); 4122 file.delete(); 4123 } 4124 } 4125 } 4126 } 4127 4128 private static File getSettingsProblemFile() { 4129 File dataDir = Environment.getDataDirectory(); 4130 File systemDir = new File(dataDir, "system"); 4131 File fname = new File(systemDir, "uiderrors.txt"); 4132 return fname; 4133 } 4134 4135 static void reportSettingsProblem(int priority, String msg) { 4136 try { 4137 File fname = getSettingsProblemFile(); 4138 FileOutputStream out = new FileOutputStream(fname, true); 4139 PrintWriter pw = new FastPrintWriter(out); 4140 SimpleDateFormat formatter = new SimpleDateFormat(); 4141 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4142 pw.println(dateString + ": " + msg); 4143 pw.close(); 4144 FileUtils.setPermissions( 4145 fname.toString(), 4146 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4147 -1, -1); 4148 } catch (java.io.IOException e) { 4149 } 4150 Slog.println(priority, TAG, msg); 4151 } 4152 4153 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4154 PackageParser.Package pkg, File srcFile, int parseFlags) 4155 throws PackageManagerException { 4156 if (ps != null 4157 && ps.codePath.equals(srcFile) 4158 && ps.timeStamp == srcFile.lastModified() 4159 && !isCompatSignatureUpdateNeeded(pkg)) { 4160 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4161 if (ps.signatures.mSignatures != null 4162 && ps.signatures.mSignatures.length != 0 4163 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4164 // Optimization: reuse the existing cached certificates 4165 // if the package appears to be unchanged. 4166 pkg.mSignatures = ps.signatures.mSignatures; 4167 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4168 synchronized (mPackages) { 4169 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4170 } 4171 return; 4172 } 4173 4174 Slog.w(TAG, "PackageSetting for " + ps.name 4175 + " is missing signatures. Collecting certs again to recover them."); 4176 } else { 4177 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4178 } 4179 4180 try { 4181 pp.collectCertificates(pkg, parseFlags); 4182 pp.collectManifestDigest(pkg); 4183 } catch (PackageParserException e) { 4184 throw new PackageManagerException(e.error, "Failed to collect certificates for " 4185 + pkg.packageName + ": " + e.getMessage()); 4186 } 4187 } 4188 4189 /* 4190 * Scan a package and return the newly parsed package. 4191 * Returns null in case of errors and the error code is stored in mLastScanError 4192 */ 4193 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode, 4194 long currentTime, UserHandle user, String abiOverride) throws PackageManagerException { 4195 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4196 parseFlags |= mDefParseFlags; 4197 PackageParser pp = new PackageParser(); 4198 pp.setSeparateProcesses(mSeparateProcesses); 4199 pp.setOnlyCoreApps(mOnlyCore); 4200 pp.setDisplayMetrics(mMetrics); 4201 4202 if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) { 4203 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4204 } 4205 4206 final PackageParser.Package pkg; 4207 try { 4208 pkg = pp.parsePackage(scanFile, parseFlags); 4209 } catch (PackageParserException e) { 4210 throw new PackageManagerException(e.error, 4211 "Failed to scan " + scanFile + ": " + e.getMessage()); 4212 } 4213 4214 PackageSetting ps = null; 4215 PackageSetting updatedPkg; 4216 // reader 4217 synchronized (mPackages) { 4218 // Look to see if we already know about this package. 4219 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4220 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4221 // This package has been renamed to its original name. Let's 4222 // use that. 4223 ps = mSettings.peekPackageLPr(oldName); 4224 } 4225 // If there was no original package, see one for the real package name. 4226 if (ps == null) { 4227 ps = mSettings.peekPackageLPr(pkg.packageName); 4228 } 4229 // Check to see if this package could be hiding/updating a system 4230 // package. Must look for it either under the original or real 4231 // package name depending on our state. 4232 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4233 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4234 } 4235 boolean updatedPkgBetter = false; 4236 // First check if this is a system package that may involve an update 4237 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4238 if (ps != null && !ps.codePath.equals(scanFile)) { 4239 // The path has changed from what was last scanned... check the 4240 // version of the new path against what we have stored to determine 4241 // what to do. 4242 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4243 if (pkg.mVersionCode < ps.versionCode) { 4244 // The system package has been updated and the code path does not match 4245 // Ignore entry. Skip it. 4246 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4247 + " ignored: updated version " + ps.versionCode 4248 + " better than this " + pkg.mVersionCode); 4249 if (!updatedPkg.codePath.equals(scanFile)) { 4250 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4251 + ps.name + " changing from " + updatedPkg.codePathString 4252 + " to " + scanFile); 4253 updatedPkg.codePath = scanFile; 4254 updatedPkg.codePathString = scanFile.toString(); 4255 // This is the point at which we know that the system-disk APK 4256 // for this package has moved during a reboot (e.g. due to an OTA), 4257 // so we need to reevaluate it for privilege policy. 4258 if (locationIsPrivileged(scanFile)) { 4259 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4260 } 4261 } 4262 updatedPkg.pkg = pkg; 4263 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4264 } else { 4265 // The current app on the system partition is better than 4266 // what we have updated to on the data partition; switch 4267 // back to the system partition version. 4268 // At this point, its safely assumed that package installation for 4269 // apps in system partition will go through. If not there won't be a working 4270 // version of the app 4271 // writer 4272 synchronized (mPackages) { 4273 // Just remove the loaded entries from package lists. 4274 mPackages.remove(ps.name); 4275 } 4276 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4277 + "reverting from " + ps.codePathString 4278 + ": new version " + pkg.mVersionCode 4279 + " better than installed " + ps.versionCode); 4280 4281 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4282 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4283 getAppDexInstructionSets(ps), isMultiArch(ps)); 4284 synchronized (mInstallLock) { 4285 args.cleanUpResourcesLI(); 4286 } 4287 synchronized (mPackages) { 4288 mSettings.enableSystemPackageLPw(ps.name); 4289 } 4290 updatedPkgBetter = true; 4291 } 4292 } 4293 } 4294 4295 if (updatedPkg != null) { 4296 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4297 // initially 4298 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4299 4300 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4301 // flag set initially 4302 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4303 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4304 } 4305 } 4306 4307 // Verify certificates against what was last scanned 4308 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4309 4310 /* 4311 * A new system app appeared, but we already had a non-system one of the 4312 * same name installed earlier. 4313 */ 4314 boolean shouldHideSystemApp = false; 4315 if (updatedPkg == null && ps != null 4316 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4317 /* 4318 * Check to make sure the signatures match first. If they don't, 4319 * wipe the installed application and its data. 4320 */ 4321 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4322 != PackageManager.SIGNATURE_MATCH) { 4323 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4324 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4325 ps = null; 4326 } else { 4327 /* 4328 * If the newly-added system app is an older version than the 4329 * already installed version, hide it. It will be scanned later 4330 * and re-added like an update. 4331 */ 4332 if (pkg.mVersionCode < ps.versionCode) { 4333 shouldHideSystemApp = true; 4334 } else { 4335 /* 4336 * The newly found system app is a newer version that the 4337 * one previously installed. Simply remove the 4338 * already-installed application and replace it with our own 4339 * while keeping the application data. 4340 */ 4341 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4342 + ps.codePathString + ": new version " + pkg.mVersionCode 4343 + " better than installed " + ps.versionCode); 4344 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4345 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4346 getAppDexInstructionSets(ps), isMultiArch(ps)); 4347 synchronized (mInstallLock) { 4348 args.cleanUpResourcesLI(); 4349 } 4350 } 4351 } 4352 } 4353 4354 // The apk is forward locked (not public) if its code and resources 4355 // are kept in different files. (except for app in either system or 4356 // vendor path). 4357 // TODO grab this value from PackageSettings 4358 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4359 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4360 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4361 } 4362 } 4363 4364 // TODO: extend to support forward-locked splits 4365 String resourcePath = null; 4366 String baseResourcePath = null; 4367 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4368 if (ps != null && ps.resourcePathString != null) { 4369 resourcePath = ps.resourcePathString; 4370 baseResourcePath = ps.resourcePathString; 4371 } else { 4372 // Should not happen at all. Just log an error. 4373 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4374 } 4375 } else { 4376 resourcePath = pkg.codePath; 4377 baseResourcePath = pkg.baseCodePath; 4378 } 4379 4380 // Set application objects path explicitly. 4381 pkg.applicationInfo.setCodePath(pkg.codePath); 4382 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4383 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4384 pkg.applicationInfo.setResourcePath(resourcePath); 4385 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4386 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4387 4388 // Note that we invoke the following method only if we are about to unpack an application 4389 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4390 | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride); 4391 4392 /* 4393 * If the system app should be overridden by a previously installed 4394 * data, hide the system app now and let the /data/app scan pick it up 4395 * again. 4396 */ 4397 if (shouldHideSystemApp) { 4398 synchronized (mPackages) { 4399 /* 4400 * We have to grant systems permissions before we hide, because 4401 * grantPermissions will assume the package update is trying to 4402 * expand its permissions. 4403 */ 4404 grantPermissionsLPw(pkg, true); 4405 mSettings.disableSystemPackageLPw(pkg.packageName); 4406 } 4407 } 4408 4409 return scannedPkg; 4410 } 4411 4412 private static String fixProcessName(String defProcessName, 4413 String processName, int uid) { 4414 if (processName == null) { 4415 return defProcessName; 4416 } 4417 return processName; 4418 } 4419 4420 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4421 throws PackageManagerException { 4422 if (pkgSetting.signatures.mSignatures != null) { 4423 // Already existing package. Make sure signatures match 4424 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4425 == PackageManager.SIGNATURE_MATCH; 4426 if (!match) { 4427 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4428 == PackageManager.SIGNATURE_MATCH; 4429 } 4430 if (!match) { 4431 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4432 + pkg.packageName + " signatures do not match the " 4433 + "previously installed version; ignoring!"); 4434 } 4435 } 4436 4437 // Check for shared user signatures 4438 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4439 // Already existing package. Make sure signatures match 4440 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4441 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4442 if (!match) { 4443 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4444 == PackageManager.SIGNATURE_MATCH; 4445 } 4446 if (!match) { 4447 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4448 "Package " + pkg.packageName 4449 + " has no signatures that match those in shared user " 4450 + pkgSetting.sharedUser.name + "; ignoring!"); 4451 } 4452 } 4453 } 4454 4455 /** 4456 * Enforces that only the system UID or root's UID can call a method exposed 4457 * via Binder. 4458 * 4459 * @param message used as message if SecurityException is thrown 4460 * @throws SecurityException if the caller is not system or root 4461 */ 4462 private static final void enforceSystemOrRoot(String message) { 4463 final int uid = Binder.getCallingUid(); 4464 if (uid != Process.SYSTEM_UID && uid != 0) { 4465 throw new SecurityException(message); 4466 } 4467 } 4468 4469 @Override 4470 public void performBootDexOpt() { 4471 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4472 4473 final HashSet<PackageParser.Package> pkgs; 4474 synchronized (mPackages) { 4475 pkgs = mDeferredDexOpt; 4476 mDeferredDexOpt = null; 4477 } 4478 4479 if (pkgs != null) { 4480 // Filter out packages that aren't recently used. 4481 // 4482 // The exception is first boot of a non-eng device, which 4483 // should do a full dexopt. 4484 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4485 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4486 // TODO: add a property to control this? 4487 long dexOptLRUThresholdInMinutes; 4488 if (eng) { 4489 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4490 } else { 4491 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4492 } 4493 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4494 4495 int total = pkgs.size(); 4496 int skipped = 0; 4497 long now = System.currentTimeMillis(); 4498 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4499 PackageParser.Package pkg = i.next(); 4500 long then = pkg.mLastPackageUsageTimeInMills; 4501 if (then + dexOptLRUThresholdInMills < now) { 4502 if (DEBUG_DEXOPT) { 4503 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4504 ((then == 0) ? "never" : new Date(then))); 4505 } 4506 i.remove(); 4507 skipped++; 4508 } 4509 } 4510 if (DEBUG_DEXOPT) { 4511 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4512 } 4513 } 4514 4515 int i = 0; 4516 for (PackageParser.Package pkg : pkgs) { 4517 i++; 4518 if (DEBUG_DEXOPT) { 4519 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4520 + ": " + pkg.packageName); 4521 } 4522 if (!isFirstBoot()) { 4523 try { 4524 ActivityManagerNative.getDefault().showBootMessage( 4525 mContext.getResources().getString( 4526 R.string.android_upgrading_apk, 4527 i, pkgs.size()), true); 4528 } catch (RemoteException e) { 4529 } 4530 } 4531 PackageParser.Package p = pkg; 4532 synchronized (mInstallLock) { 4533 if (p.mDexOptNeeded) { 4534 performDexOptLI(p, false /* force dex */, false /* defer */, 4535 true /* include dependencies */); 4536 } 4537 } 4538 } 4539 } 4540 } 4541 4542 @Override 4543 public boolean performDexOpt(String packageName) { 4544 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4545 return performDexOpt(packageName, true); 4546 } 4547 4548 public boolean performDexOpt(String packageName, boolean updateUsage) { 4549 4550 PackageParser.Package p; 4551 synchronized (mPackages) { 4552 p = mPackages.get(packageName); 4553 if (p == null) { 4554 return false; 4555 } 4556 if (updateUsage) { 4557 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4558 } 4559 mPackageUsage.write(false); 4560 if (!p.mDexOptNeeded) { 4561 return false; 4562 } 4563 } 4564 4565 synchronized (mInstallLock) { 4566 return performDexOptLI(p, false /* force dex */, false /* defer */, 4567 true /* include dependencies */) == DEX_OPT_PERFORMED; 4568 } 4569 } 4570 4571 public HashSet<String> getPackagesThatNeedDexOpt() { 4572 HashSet<String> pkgs = null; 4573 synchronized (mPackages) { 4574 for (PackageParser.Package p : mPackages.values()) { 4575 if (DEBUG_DEXOPT) { 4576 Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded); 4577 } 4578 if (!p.mDexOptNeeded) { 4579 continue; 4580 } 4581 if (pkgs == null) { 4582 pkgs = new HashSet<String>(); 4583 } 4584 pkgs.add(p.packageName); 4585 } 4586 } 4587 return pkgs; 4588 } 4589 4590 public void shutdown() { 4591 mPackageUsage.write(true); 4592 } 4593 4594 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4595 boolean forceDex, boolean defer, HashSet<String> done) { 4596 for (int i=0; i<libs.size(); i++) { 4597 PackageParser.Package libPkg; 4598 String libName; 4599 synchronized (mPackages) { 4600 libName = libs.get(i); 4601 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4602 if (lib != null && lib.apk != null) { 4603 libPkg = mPackages.get(lib.apk); 4604 } else { 4605 libPkg = null; 4606 } 4607 } 4608 if (libPkg != null && !done.contains(libName)) { 4609 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4610 } 4611 } 4612 } 4613 4614 static final int DEX_OPT_SKIPPED = 0; 4615 static final int DEX_OPT_PERFORMED = 1; 4616 static final int DEX_OPT_DEFERRED = 2; 4617 static final int DEX_OPT_FAILED = -1; 4618 4619 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4620 boolean forceDex, boolean defer, HashSet<String> done) { 4621 final String[] instructionSets = targetInstructionSets != null ? 4622 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4623 4624 if (done != null) { 4625 done.add(pkg.packageName); 4626 if (pkg.usesLibraries != null) { 4627 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4628 } 4629 if (pkg.usesOptionalLibraries != null) { 4630 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4631 } 4632 } 4633 4634 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4635 return DEX_OPT_SKIPPED; 4636 } 4637 4638 final Collection<String> paths = pkg.getAllCodePaths(); 4639 boolean performedDexOpt = false; 4640 // There are three basic cases here: 4641 // 1.) we need to dexopt, either because we are forced or it is needed 4642 // 2.) we are defering a needed dexopt 4643 // 3.) we are skipping an unneeded dexopt 4644 for (String path : paths) { 4645 for (String instructionSet : instructionSets) { 4646 try { 4647 final boolean isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4648 pkg.packageName, instructionSet, defer); 4649 if (forceDex || (!defer && isDexOptNeeded)) { 4650 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName + " isa=" + instructionSet); 4651 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4652 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4653 pkg.packageName, instructionSet); 4654 4655 if (ret < 0) { 4656 // Don't bother running dexopt again if we failed, it will probably 4657 // just result in an error again. Also, don't bother dexopting for other 4658 // paths & ISAs. 4659 pkg.mDexOptNeeded = false; 4660 return DEX_OPT_FAILED; 4661 } else { 4662 performedDexOpt = true; 4663 } 4664 } 4665 4666 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4667 // paths and instruction sets. We'll deal with them all together when we process 4668 // our list of deferred dexopts. 4669 if (defer && isDexOptNeeded) { 4670 if (mDeferredDexOpt == null) { 4671 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4672 } 4673 mDeferredDexOpt.add(pkg); 4674 return DEX_OPT_DEFERRED; 4675 } 4676 } catch (FileNotFoundException e) { 4677 Slog.w(TAG, "Apk not found for dexopt: " + path); 4678 return DEX_OPT_FAILED; 4679 } catch (IOException e) { 4680 Slog.w(TAG, "IOException reading apk: " + path, e); 4681 return DEX_OPT_FAILED; 4682 } catch (StaleDexCacheError e) { 4683 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4684 return DEX_OPT_FAILED; 4685 } catch (Exception e) { 4686 Slog.w(TAG, "Exception when doing dexopt : ", e); 4687 return DEX_OPT_FAILED; 4688 } 4689 } 4690 } 4691 4692 // If we've gotten here, we're sure that no error occurred and that we haven't 4693 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4694 // we've skipped all of them because they are up to date. In both cases this 4695 // package doesn't need dexopt any longer. 4696 pkg.mDexOptNeeded = false; 4697 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4698 } 4699 4700 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4701 if (info.primaryCpuAbi != null) { 4702 if (info.secondaryCpuAbi != null) { 4703 return new String[] { 4704 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4705 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4706 } else { 4707 return new String[] { 4708 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4709 } 4710 } 4711 4712 return new String[] { getPreferredInstructionSet() }; 4713 } 4714 4715 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4716 if (ps.primaryCpuAbiString != null) { 4717 if (ps.secondaryCpuAbiString != null) { 4718 return new String[] { 4719 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4720 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4721 } else { 4722 return new String[] { 4723 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4724 } 4725 } 4726 4727 return new String[] { getPreferredInstructionSet() }; 4728 } 4729 4730 private static String getPreferredInstructionSet() { 4731 if (sPreferredInstructionSet == null) { 4732 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4733 } 4734 4735 return sPreferredInstructionSet; 4736 } 4737 4738 private static List<String> getAllInstructionSets() { 4739 final String[] allAbis = Build.SUPPORTED_ABIS; 4740 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4741 4742 for (String abi : allAbis) { 4743 final String instructionSet = VMRuntime.getInstructionSet(abi); 4744 if (!allInstructionSets.contains(instructionSet)) { 4745 allInstructionSets.add(instructionSet); 4746 } 4747 } 4748 4749 return allInstructionSets; 4750 } 4751 4752 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer, 4753 boolean inclDependencies) { 4754 HashSet<String> done; 4755 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4756 done = new HashSet<String>(); 4757 done.add(pkg.packageName); 4758 } else { 4759 done = null; 4760 } 4761 return performDexOptLI(pkg, null /* target instruction sets */, forceDex, defer, done); 4762 } 4763 4764 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4765 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4766 Slog.w(TAG, "Unable to update from " + oldPkg.name 4767 + " to " + newPkg.packageName 4768 + ": old package not in system partition"); 4769 return false; 4770 } else if (mPackages.get(oldPkg.name) != null) { 4771 Slog.w(TAG, "Unable to update from " + oldPkg.name 4772 + " to " + newPkg.packageName 4773 + ": old package still exists"); 4774 return false; 4775 } 4776 return true; 4777 } 4778 4779 File getDataPathForUser(int userId) { 4780 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4781 } 4782 4783 private File getDataPathForPackage(String packageName, int userId) { 4784 /* 4785 * Until we fully support multiple users, return the directory we 4786 * previously would have. The PackageManagerTests will need to be 4787 * revised when this is changed back.. 4788 */ 4789 if (userId == 0) { 4790 return new File(mAppDataDir, packageName); 4791 } else { 4792 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4793 + File.separator + packageName); 4794 } 4795 } 4796 4797 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4798 int[] users = sUserManager.getUserIds(); 4799 int res = mInstaller.install(packageName, uid, uid, seinfo); 4800 if (res < 0) { 4801 return res; 4802 } 4803 for (int user : users) { 4804 if (user != 0) { 4805 res = mInstaller.createUserData(packageName, 4806 UserHandle.getUid(user, uid), user, seinfo); 4807 if (res < 0) { 4808 return res; 4809 } 4810 } 4811 } 4812 return res; 4813 } 4814 4815 private int removeDataDirsLI(String packageName) { 4816 int[] users = sUserManager.getUserIds(); 4817 int res = 0; 4818 for (int user : users) { 4819 int resInner = mInstaller.remove(packageName, user); 4820 if (resInner < 0) { 4821 res = resInner; 4822 } 4823 } 4824 4825 return res; 4826 } 4827 4828 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4829 PackageParser.Package changingLib) { 4830 if (file.path != null) { 4831 usesLibraryFiles.add(file.path); 4832 return; 4833 } 4834 PackageParser.Package p = mPackages.get(file.apk); 4835 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4836 // If we are doing this while in the middle of updating a library apk, 4837 // then we need to make sure to use that new apk for determining the 4838 // dependencies here. (We haven't yet finished committing the new apk 4839 // to the package manager state.) 4840 if (p == null || p.packageName.equals(changingLib.packageName)) { 4841 p = changingLib; 4842 } 4843 } 4844 if (p != null) { 4845 usesLibraryFiles.addAll(p.getAllCodePaths()); 4846 } 4847 } 4848 4849 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4850 PackageParser.Package changingLib) throws PackageManagerException { 4851 // We might be upgrading from a version of the platform that did not 4852 // provide per-package native library directories for system apps. 4853 // Fix that up here. 4854 if (isSystemApp(pkg)) { 4855 PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName); 4856 if (!isUpdatedSystemApp(pkg)) { 4857 setBundledAppAbisAndRoots(pkg, ps); 4858 } 4859 } 4860 4861 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4862 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4863 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4864 for (int i=0; i<N; i++) { 4865 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4866 if (file == null) { 4867 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4868 "Package " + pkg.packageName + " requires unavailable shared library " 4869 + pkg.usesLibraries.get(i) + "; failing!"); 4870 } 4871 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4872 } 4873 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4874 for (int i=0; i<N; i++) { 4875 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4876 if (file == null) { 4877 Slog.w(TAG, "Package " + pkg.packageName 4878 + " desires unavailable shared library " 4879 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4880 } else { 4881 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4882 } 4883 } 4884 N = usesLibraryFiles.size(); 4885 if (N > 0) { 4886 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4887 } else { 4888 pkg.usesLibraryFiles = null; 4889 } 4890 } 4891 } 4892 4893 private static boolean hasString(List<String> list, List<String> which) { 4894 if (list == null) { 4895 return false; 4896 } 4897 for (int i=list.size()-1; i>=0; i--) { 4898 for (int j=which.size()-1; j>=0; j--) { 4899 if (which.get(j).equals(list.get(i))) { 4900 return true; 4901 } 4902 } 4903 } 4904 return false; 4905 } 4906 4907 private void updateAllSharedLibrariesLPw() { 4908 for (PackageParser.Package pkg : mPackages.values()) { 4909 try { 4910 updateSharedLibrariesLPw(pkg, null); 4911 } catch (PackageManagerException e) { 4912 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4913 } 4914 } 4915 } 4916 4917 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4918 PackageParser.Package changingPkg) { 4919 ArrayList<PackageParser.Package> res = null; 4920 for (PackageParser.Package pkg : mPackages.values()) { 4921 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4922 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4923 if (res == null) { 4924 res = new ArrayList<PackageParser.Package>(); 4925 } 4926 res.add(pkg); 4927 try { 4928 updateSharedLibrariesLPw(pkg, changingPkg); 4929 } catch (PackageManagerException e) { 4930 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4931 } 4932 } 4933 } 4934 return res; 4935 } 4936 4937 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 4938 int scanMode, long currentTime, UserHandle user, String abiOverride) 4939 throws PackageManagerException { 4940 final File scanFile = new File(pkg.codePath); 4941 if (pkg.applicationInfo.getCodePath() == null || 4942 pkg.applicationInfo.getResourcePath() == null) { 4943 // Bail out. The resource and code paths haven't been set. 4944 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 4945 "Code and resource paths haven't been set correctly"); 4946 } 4947 4948 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4949 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4950 } 4951 4952 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4953 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4954 } 4955 4956 if (mCustomResolverComponentName != null && 4957 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4958 setUpCustomResolverActivity(pkg); 4959 } 4960 4961 if (pkg.packageName.equals("android")) { 4962 synchronized (mPackages) { 4963 if (mAndroidApplication != null) { 4964 Slog.w(TAG, "*************************************************"); 4965 Slog.w(TAG, "Core android package being redefined. Skipping."); 4966 Slog.w(TAG, " file=" + scanFile); 4967 Slog.w(TAG, "*************************************************"); 4968 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 4969 "Core android package being redefined. Skipping."); 4970 } 4971 4972 // Set up information for our fall-back user intent resolution activity. 4973 mPlatformPackage = pkg; 4974 pkg.mVersionCode = mSdkVersion; 4975 mAndroidApplication = pkg.applicationInfo; 4976 4977 if (!mResolverReplaced) { 4978 mResolveActivity.applicationInfo = mAndroidApplication; 4979 mResolveActivity.name = ResolverActivity.class.getName(); 4980 mResolveActivity.packageName = mAndroidApplication.packageName; 4981 mResolveActivity.processName = "system:ui"; 4982 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 4983 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 4984 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 4985 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 4986 mResolveActivity.exported = true; 4987 mResolveActivity.enabled = true; 4988 mResolveInfo.activityInfo = mResolveActivity; 4989 mResolveInfo.priority = 0; 4990 mResolveInfo.preferredOrder = 0; 4991 mResolveInfo.match = 0; 4992 mResolveComponentName = new ComponentName( 4993 mAndroidApplication.packageName, mResolveActivity.name); 4994 } 4995 } 4996 } 4997 4998 if (DEBUG_PACKAGE_SCANNING) { 4999 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5000 Log.d(TAG, "Scanning package " + pkg.packageName); 5001 } 5002 5003 if (mPackages.containsKey(pkg.packageName) 5004 || mSharedLibraries.containsKey(pkg.packageName)) { 5005 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5006 "Application package " + pkg.packageName 5007 + " already installed. Skipping duplicate."); 5008 } 5009 5010 // Initialize package source and resource directories 5011 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5012 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5013 5014 SharedUserSetting suid = null; 5015 PackageSetting pkgSetting = null; 5016 5017 if (!isSystemApp(pkg)) { 5018 // Only system apps can use these features. 5019 pkg.mOriginalPackages = null; 5020 pkg.mRealPackage = null; 5021 pkg.mAdoptPermissions = null; 5022 } 5023 5024 // writer 5025 synchronized (mPackages) { 5026 if (pkg.mSharedUserId != null) { 5027 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5028 if (suid == null) { 5029 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5030 "Creating application package " + pkg.packageName 5031 + " for shared user failed"); 5032 } 5033 if (DEBUG_PACKAGE_SCANNING) { 5034 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5035 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5036 + "): packages=" + suid.packages); 5037 } 5038 } 5039 5040 // Check if we are renaming from an original package name. 5041 PackageSetting origPackage = null; 5042 String realName = null; 5043 if (pkg.mOriginalPackages != null) { 5044 // This package may need to be renamed to a previously 5045 // installed name. Let's check on that... 5046 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5047 if (pkg.mOriginalPackages.contains(renamed)) { 5048 // This package had originally been installed as the 5049 // original name, and we have already taken care of 5050 // transitioning to the new one. Just update the new 5051 // one to continue using the old name. 5052 realName = pkg.mRealPackage; 5053 if (!pkg.packageName.equals(renamed)) { 5054 // Callers into this function may have already taken 5055 // care of renaming the package; only do it here if 5056 // it is not already done. 5057 pkg.setPackageName(renamed); 5058 } 5059 5060 } else { 5061 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5062 if ((origPackage = mSettings.peekPackageLPr( 5063 pkg.mOriginalPackages.get(i))) != null) { 5064 // We do have the package already installed under its 5065 // original name... should we use it? 5066 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5067 // New package is not compatible with original. 5068 origPackage = null; 5069 continue; 5070 } else if (origPackage.sharedUser != null) { 5071 // Make sure uid is compatible between packages. 5072 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5073 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5074 + " to " + pkg.packageName + ": old uid " 5075 + origPackage.sharedUser.name 5076 + " differs from " + pkg.mSharedUserId); 5077 origPackage = null; 5078 continue; 5079 } 5080 } else { 5081 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5082 + pkg.packageName + " to old name " + origPackage.name); 5083 } 5084 break; 5085 } 5086 } 5087 } 5088 } 5089 5090 if (mTransferedPackages.contains(pkg.packageName)) { 5091 Slog.w(TAG, "Package " + pkg.packageName 5092 + " was transferred to another, but its .apk remains"); 5093 } 5094 5095 // Just create the setting, don't add it yet. For already existing packages 5096 // the PkgSetting exists already and doesn't have to be created. 5097 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5098 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5099 pkg.applicationInfo.primaryCpuAbi, 5100 pkg.applicationInfo.secondaryCpuAbi, 5101 pkg.applicationInfo.flags, user, false); 5102 if (pkgSetting == null) { 5103 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5104 "Creating application package " + pkg.packageName + " failed"); 5105 } 5106 5107 if (pkgSetting.origPackage != null) { 5108 // If we are first transitioning from an original package, 5109 // fix up the new package's name now. We need to do this after 5110 // looking up the package under its new name, so getPackageLP 5111 // can take care of fiddling things correctly. 5112 pkg.setPackageName(origPackage.name); 5113 5114 // File a report about this. 5115 String msg = "New package " + pkgSetting.realName 5116 + " renamed to replace old package " + pkgSetting.name; 5117 reportSettingsProblem(Log.WARN, msg); 5118 5119 // Make a note of it. 5120 mTransferedPackages.add(origPackage.name); 5121 5122 // No longer need to retain this. 5123 pkgSetting.origPackage = null; 5124 } 5125 5126 if (realName != null) { 5127 // Make a note of it. 5128 mTransferedPackages.add(pkg.packageName); 5129 } 5130 5131 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5132 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5133 } 5134 5135 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5136 // Check all shared libraries and map to their actual file path. 5137 // We only do this here for apps not on a system dir, because those 5138 // are the only ones that can fail an install due to this. We 5139 // will take care of the system apps by updating all of their 5140 // library paths after the scan is done. 5141 updateSharedLibrariesLPw(pkg, null); 5142 } 5143 5144 if (mFoundPolicyFile) { 5145 SELinuxMMAC.assignSeinfoValue(pkg); 5146 } 5147 5148 pkg.applicationInfo.uid = pkgSetting.appId; 5149 pkg.mExtras = pkgSetting; 5150 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5151 try { 5152 verifySignaturesLP(pkgSetting, pkg); 5153 } catch (PackageManagerException e) { 5154 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5155 throw e; 5156 } 5157 // The signature has changed, but this package is in the system 5158 // image... let's recover! 5159 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5160 // However... if this package is part of a shared user, but it 5161 // doesn't match the signature of the shared user, let's fail. 5162 // What this means is that you can't change the signatures 5163 // associated with an overall shared user, which doesn't seem all 5164 // that unreasonable. 5165 if (pkgSetting.sharedUser != null) { 5166 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5167 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5168 throw new PackageManagerException( 5169 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5170 "Signature mismatch for shared user : " 5171 + pkgSetting.sharedUser); 5172 } 5173 } 5174 // File a report about this. 5175 String msg = "System package " + pkg.packageName 5176 + " signature changed; retaining data."; 5177 reportSettingsProblem(Log.WARN, msg); 5178 } 5179 } else { 5180 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5181 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5182 + pkg.packageName + " upgrade keys do not match the " 5183 + "previously installed version"); 5184 } else { 5185 // signatures may have changed as result of upgrade 5186 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5187 } 5188 } 5189 // Verify that this new package doesn't have any content providers 5190 // that conflict with existing packages. Only do this if the 5191 // package isn't already installed, since we don't want to break 5192 // things that are installed. 5193 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5194 final int N = pkg.providers.size(); 5195 int i; 5196 for (i=0; i<N; i++) { 5197 PackageParser.Provider p = pkg.providers.get(i); 5198 if (p.info.authority != null) { 5199 String names[] = p.info.authority.split(";"); 5200 for (int j = 0; j < names.length; j++) { 5201 if (mProvidersByAuthority.containsKey(names[j])) { 5202 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5203 final String otherPackageName = 5204 ((other != null && other.getComponentName() != null) ? 5205 other.getComponentName().getPackageName() : "?"); 5206 throw new PackageManagerException( 5207 INSTALL_FAILED_CONFLICTING_PROVIDER, 5208 "Can't install because provider name " + names[j] 5209 + " (in package " + pkg.applicationInfo.packageName 5210 + ") is already used by " + otherPackageName); 5211 } 5212 } 5213 } 5214 } 5215 } 5216 5217 if (pkg.mAdoptPermissions != null) { 5218 // This package wants to adopt ownership of permissions from 5219 // another package. 5220 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5221 final String origName = pkg.mAdoptPermissions.get(i); 5222 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5223 if (orig != null) { 5224 if (verifyPackageUpdateLPr(orig, pkg)) { 5225 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5226 + pkg.packageName); 5227 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5228 } 5229 } 5230 } 5231 } 5232 } 5233 5234 final String pkgName = pkg.packageName; 5235 5236 final long scanFileTime = scanFile.lastModified(); 5237 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5238 pkg.applicationInfo.processName = fixProcessName( 5239 pkg.applicationInfo.packageName, 5240 pkg.applicationInfo.processName, 5241 pkg.applicationInfo.uid); 5242 5243 File dataPath; 5244 if (mPlatformPackage == pkg) { 5245 // The system package is special. 5246 dataPath = new File (Environment.getDataDirectory(), "system"); 5247 pkg.applicationInfo.dataDir = dataPath.getPath(); 5248 } else { 5249 // This is a normal package, need to make its data directory. 5250 dataPath = getDataPathForPackage(pkg.packageName, 0); 5251 5252 boolean uidError = false; 5253 5254 if (dataPath.exists()) { 5255 int currentUid = 0; 5256 try { 5257 StructStat stat = Os.stat(dataPath.getPath()); 5258 currentUid = stat.st_uid; 5259 } catch (ErrnoException e) { 5260 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5261 } 5262 5263 // If we have mismatched owners for the data path, we have a problem. 5264 if (currentUid != pkg.applicationInfo.uid) { 5265 boolean recovered = false; 5266 if (currentUid == 0) { 5267 // The directory somehow became owned by root. Wow. 5268 // This is probably because the system was stopped while 5269 // installd was in the middle of messing with its libs 5270 // directory. Ask installd to fix that. 5271 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5272 pkg.applicationInfo.uid); 5273 if (ret >= 0) { 5274 recovered = true; 5275 String msg = "Package " + pkg.packageName 5276 + " unexpectedly changed to uid 0; recovered to " + 5277 + pkg.applicationInfo.uid; 5278 reportSettingsProblem(Log.WARN, msg); 5279 } 5280 } 5281 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5282 || (scanMode&SCAN_BOOTING) != 0)) { 5283 // If this is a system app, we can at least delete its 5284 // current data so the application will still work. 5285 int ret = removeDataDirsLI(pkgName); 5286 if (ret >= 0) { 5287 // TODO: Kill the processes first 5288 // Old data gone! 5289 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5290 ? "System package " : "Third party package "; 5291 String msg = prefix + pkg.packageName 5292 + " has changed from uid: " 5293 + currentUid + " to " 5294 + pkg.applicationInfo.uid + "; old data erased"; 5295 reportSettingsProblem(Log.WARN, msg); 5296 recovered = true; 5297 5298 // And now re-install the app. 5299 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5300 pkg.applicationInfo.seinfo); 5301 if (ret == -1) { 5302 // Ack should not happen! 5303 msg = prefix + pkg.packageName 5304 + " could not have data directory re-created after delete."; 5305 reportSettingsProblem(Log.WARN, msg); 5306 throw new PackageManagerException( 5307 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5308 } 5309 } 5310 if (!recovered) { 5311 mHasSystemUidErrors = true; 5312 } 5313 } else if (!recovered) { 5314 // If we allow this install to proceed, we will be broken. 5315 // Abort, abort! 5316 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5317 "scanPackageLI"); 5318 } 5319 if (!recovered) { 5320 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5321 + pkg.applicationInfo.uid + "/fs_" 5322 + currentUid; 5323 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5324 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5325 String msg = "Package " + pkg.packageName 5326 + " has mismatched uid: " 5327 + currentUid + " on disk, " 5328 + pkg.applicationInfo.uid + " in settings"; 5329 // writer 5330 synchronized (mPackages) { 5331 mSettings.mReadMessages.append(msg); 5332 mSettings.mReadMessages.append('\n'); 5333 uidError = true; 5334 if (!pkgSetting.uidError) { 5335 reportSettingsProblem(Log.ERROR, msg); 5336 } 5337 } 5338 } 5339 } 5340 pkg.applicationInfo.dataDir = dataPath.getPath(); 5341 if (mShouldRestoreconData) { 5342 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5343 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5344 pkg.applicationInfo.uid); 5345 } 5346 } else { 5347 if (DEBUG_PACKAGE_SCANNING) { 5348 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5349 Log.v(TAG, "Want this data dir: " + dataPath); 5350 } 5351 //invoke installer to do the actual installation 5352 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5353 pkg.applicationInfo.seinfo); 5354 if (ret < 0) { 5355 // Error from installer 5356 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5357 "Unable to create data dirs [errorCode=" + ret + "]"); 5358 } 5359 5360 if (dataPath.exists()) { 5361 pkg.applicationInfo.dataDir = dataPath.getPath(); 5362 } else { 5363 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5364 pkg.applicationInfo.dataDir = null; 5365 } 5366 } 5367 5368 pkgSetting.uidError = uidError; 5369 } 5370 5371 final String path = scanFile.getPath(); 5372 final String codePath = pkg.applicationInfo.getCodePath(); 5373 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5374 // For the case where we had previously uninstalled an update, get rid 5375 // of any native binaries we might have unpackaged. Note that this assumes 5376 // that system app updates were not installed via ASEC. 5377 // 5378 // TODO(multiArch): Is this cleanup really necessary ? 5379 NativeLibraryHelper.removeNativeBinariesFromDirLI( 5380 new File(codePath, LIB_DIR_NAME), false /* delete dirs */); 5381 setBundledAppAbisAndRoots(pkg, pkgSetting); 5382 setNativeLibraryPaths(pkg); 5383 } else { 5384 // TODO: We can probably be smarter about this stuff. For installed apps, 5385 // we can calculate this information at install time once and for all. For 5386 // system apps, we can probably assume that this information doesn't change 5387 // after the first boot scan. As things stand, we do lots of unnecessary work. 5388 5389 // Give ourselves some initial paths; we'll come back for another 5390 // pass once we've determined ABI below. 5391 setNativeLibraryPaths(pkg); 5392 5393 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5394 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5395 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5396 5397 NativeLibraryHelper.Handle handle = null; 5398 try { 5399 handle = NativeLibraryHelper.Handle.create(scanFile); 5400 // TODO(multiArch): This can be null for apps that didn't go through the 5401 // usual installation process. We can calculate it again, like we 5402 // do during install time. 5403 // 5404 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5405 // unnecessary. 5406 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5407 5408 // Null out the abis so that they can be recalculated. 5409 pkg.applicationInfo.primaryCpuAbi = null; 5410 pkg.applicationInfo.secondaryCpuAbi = null; 5411 if (isMultiArch(pkg.applicationInfo)) { 5412 // Warn if we've set an abiOverride for multi-lib packages.. 5413 // By definition, we need to copy both 32 and 64 bit libraries for 5414 // such packages. 5415 if (abiOverride != null) { 5416 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5417 } 5418 5419 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5420 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5421 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5422 if (isAsec) { 5423 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5424 } else { 5425 abi32 = copyNativeLibrariesForInternalApp(handle, 5426 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs); 5427 } 5428 } 5429 5430 if (abi32 < 0 && abi32 != PackageManager.NO_NATIVE_LIBRARIES) { 5431 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5432 "Error unpackaging 32 bit native libs for multiarch app, errorCode=" 5433 + abi32); 5434 } 5435 5436 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5437 if (isAsec) { 5438 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5439 } else { 5440 abi64 = copyNativeLibrariesForInternalApp(handle, 5441 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs); 5442 } 5443 } 5444 5445 if (abi64 < 0 && abi64 != PackageManager.NO_NATIVE_LIBRARIES) { 5446 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5447 "Error unpackaging 64 bit native libs for multiarch app, errorCode=" 5448 + abi32); 5449 } 5450 5451 if (abi64 >= 0) { 5452 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5453 } 5454 5455 if (abi32 >= 0) { 5456 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5457 if (abi64 >= 0) { 5458 pkg.applicationInfo.secondaryCpuAbi = abi; 5459 } else { 5460 pkg.applicationInfo.primaryCpuAbi = abi; 5461 } 5462 } 5463 } else { 5464 String[] abiList = (abiOverride != null) ? 5465 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 5466 5467 // Enable gross and lame hacks for apps that are built with old 5468 // SDK tools. We must scan their APKs for renderscript bitcode and 5469 // not launch them if it's present. Don't bother checking on devices 5470 // that don't have 64 bit support. 5471 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null && 5472 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5473 abiList = Build.SUPPORTED_32_BIT_ABIS; 5474 } 5475 5476 final int copyRet; 5477 if (isAsec) { 5478 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5479 } else { 5480 copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryRoot, abiList, 5481 useIsaSpecificSubdirs); 5482 } 5483 5484 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5485 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5486 "Error unpackaging native libs for app, errorCode=" + copyRet); 5487 } 5488 5489 if (copyRet >= 0) { 5490 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5491 } 5492 } 5493 } catch (IOException ioe) { 5494 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5495 } finally { 5496 IoUtils.closeQuietly(handle); 5497 } 5498 5499 // Now that we've calculated the ABIs and determined if it's an internal app, 5500 // we will go ahead and populate the nativeLibraryPath. 5501 setNativeLibraryPaths(pkg); 5502 5503 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5504 final int[] userIds = sUserManager.getUserIds(); 5505 synchronized (mInstallLock) { 5506 // Create a native library symlink only if we have native libraries 5507 // and if the native libraries are 32 bit libraries. We do not provide 5508 // this symlink for 64 bit libraries. 5509 if (pkg.applicationInfo.primaryCpuAbi != null && 5510 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5511 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5512 for (int userId : userIds) { 5513 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5514 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5515 "Failed linking native library dir (user=" + userId + ")"); 5516 } 5517 } 5518 } 5519 } 5520 5521 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5522 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5523 } 5524 5525 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5526 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5527 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5528 5529 // Push the derived path down into PackageSettings so we know what to 5530 // clean up at uninstall time. 5531 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5532 5533 if (DEBUG_ABI_SELECTION) { 5534 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5535 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5536 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5537 } 5538 5539 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5540 // We don't do this here during boot because we can do it all 5541 // at once after scanning all existing packages. 5542 // 5543 // We also do this *before* we perform dexopt on this package, so that 5544 // we can avoid redundant dexopts, and also to make sure we've got the 5545 // code and package path correct. 5546 if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5547 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) { 5548 throw new PackageManagerException(INSTALL_FAILED_CPU_ABI_INCOMPATIBLE, 5549 "scanPackageLI"); 5550 } 5551 } 5552 5553 if ((scanMode&SCAN_NO_DEX) == 0) { 5554 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5555 == DEX_OPT_FAILED) { 5556 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5557 removeDataDirsLI(pkg.packageName); 5558 } 5559 5560 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5561 } 5562 } 5563 5564 if (mFactoryTest && pkg.requestedPermissions.contains( 5565 android.Manifest.permission.FACTORY_TEST)) { 5566 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5567 } 5568 5569 ArrayList<PackageParser.Package> clientLibPkgs = null; 5570 5571 // writer 5572 synchronized (mPackages) { 5573 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5574 // Only system apps can add new shared libraries. 5575 if (pkg.libraryNames != null) { 5576 for (int i=0; i<pkg.libraryNames.size(); i++) { 5577 String name = pkg.libraryNames.get(i); 5578 boolean allowed = false; 5579 if (isUpdatedSystemApp(pkg)) { 5580 // New library entries can only be added through the 5581 // system image. This is important to get rid of a lot 5582 // of nasty edge cases: for example if we allowed a non- 5583 // system update of the app to add a library, then uninstalling 5584 // the update would make the library go away, and assumptions 5585 // we made such as through app install filtering would now 5586 // have allowed apps on the device which aren't compatible 5587 // with it. Better to just have the restriction here, be 5588 // conservative, and create many fewer cases that can negatively 5589 // impact the user experience. 5590 final PackageSetting sysPs = mSettings 5591 .getDisabledSystemPkgLPr(pkg.packageName); 5592 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5593 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5594 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5595 allowed = true; 5596 allowed = true; 5597 break; 5598 } 5599 } 5600 } 5601 } else { 5602 allowed = true; 5603 } 5604 if (allowed) { 5605 if (!mSharedLibraries.containsKey(name)) { 5606 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5607 } else if (!name.equals(pkg.packageName)) { 5608 Slog.w(TAG, "Package " + pkg.packageName + " library " 5609 + name + " already exists; skipping"); 5610 } 5611 } else { 5612 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5613 + name + " that is not declared on system image; skipping"); 5614 } 5615 } 5616 if ((scanMode&SCAN_BOOTING) == 0) { 5617 // If we are not booting, we need to update any applications 5618 // that are clients of our shared library. If we are booting, 5619 // this will all be done once the scan is complete. 5620 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5621 } 5622 } 5623 } 5624 } 5625 5626 // We also need to dexopt any apps that are dependent on this library. Note that 5627 // if these fail, we should abort the install since installing the library will 5628 // result in some apps being broken. 5629 if (clientLibPkgs != null) { 5630 if ((scanMode&SCAN_NO_DEX) == 0) { 5631 for (int i=0; i<clientLibPkgs.size(); i++) { 5632 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5633 if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5634 == DEX_OPT_FAILED) { 5635 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5636 removeDataDirsLI(pkg.packageName); 5637 } 5638 5639 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5640 "scanPackageLI failed to dexopt clientLibPkgs"); 5641 } 5642 } 5643 } 5644 } 5645 5646 // Request the ActivityManager to kill the process(only for existing packages) 5647 // so that we do not end up in a confused state while the user is still using the older 5648 // version of the application while the new one gets installed. 5649 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5650 // If the package lives in an asec, tell everyone that the container is going 5651 // away so they can clean up any references to its resources (which would prevent 5652 // vold from being able to unmount the asec) 5653 if (isForwardLocked(pkg) || isExternal(pkg)) { 5654 if (DEBUG_INSTALL) { 5655 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5656 } 5657 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5658 final ArrayList<String> pkgList = new ArrayList<String>(1); 5659 pkgList.add(pkg.applicationInfo.packageName); 5660 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5661 } 5662 5663 // Post the request that it be killed now that the going-away broadcast is en route 5664 killApplication(pkg.applicationInfo.packageName, 5665 pkg.applicationInfo.uid, "update pkg"); 5666 } 5667 5668 // Also need to kill any apps that are dependent on the library. 5669 if (clientLibPkgs != null) { 5670 for (int i=0; i<clientLibPkgs.size(); i++) { 5671 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5672 killApplication(clientPkg.applicationInfo.packageName, 5673 clientPkg.applicationInfo.uid, "update lib"); 5674 } 5675 } 5676 5677 // writer 5678 synchronized (mPackages) { 5679 // We don't expect installation to fail beyond this point, 5680 if ((scanMode&SCAN_MONITOR) != 0) { 5681 mAppDirs.put(pkg.codePath, pkg); 5682 } 5683 // Add the new setting to mSettings 5684 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5685 // Add the new setting to mPackages 5686 mPackages.put(pkg.applicationInfo.packageName, pkg); 5687 // Make sure we don't accidentally delete its data. 5688 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5689 while (iter.hasNext()) { 5690 PackageCleanItem item = iter.next(); 5691 if (pkgName.equals(item.packageName)) { 5692 iter.remove(); 5693 } 5694 } 5695 5696 // Take care of first install / last update times. 5697 if (currentTime != 0) { 5698 if (pkgSetting.firstInstallTime == 0) { 5699 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5700 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5701 pkgSetting.lastUpdateTime = currentTime; 5702 } 5703 } else if (pkgSetting.firstInstallTime == 0) { 5704 // We need *something*. Take time time stamp of the file. 5705 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5706 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5707 if (scanFileTime != pkgSetting.timeStamp) { 5708 // A package on the system image has changed; consider this 5709 // to be an update. 5710 pkgSetting.lastUpdateTime = scanFileTime; 5711 } 5712 } 5713 5714 // Add the package's KeySets to the global KeySetManagerService 5715 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5716 try { 5717 // Old KeySetData no longer valid. 5718 ksms.removeAppKeySetDataLPw(pkg.packageName); 5719 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5720 if (pkg.mKeySetMapping != null) { 5721 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5722 pkg.mKeySetMapping.entrySet()) { 5723 if (entry.getValue() != null) { 5724 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5725 entry.getValue(), entry.getKey()); 5726 } 5727 } 5728 if (pkg.mUpgradeKeySets != null) { 5729 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5730 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5731 } 5732 } 5733 } 5734 } catch (NullPointerException e) { 5735 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5736 } catch (IllegalArgumentException e) { 5737 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5738 } 5739 5740 int N = pkg.providers.size(); 5741 StringBuilder r = null; 5742 int i; 5743 for (i=0; i<N; i++) { 5744 PackageParser.Provider p = pkg.providers.get(i); 5745 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5746 p.info.processName, pkg.applicationInfo.uid); 5747 mProviders.addProvider(p); 5748 p.syncable = p.info.isSyncable; 5749 if (p.info.authority != null) { 5750 String names[] = p.info.authority.split(";"); 5751 p.info.authority = null; 5752 for (int j = 0; j < names.length; j++) { 5753 if (j == 1 && p.syncable) { 5754 // We only want the first authority for a provider to possibly be 5755 // syncable, so if we already added this provider using a different 5756 // authority clear the syncable flag. We copy the provider before 5757 // changing it because the mProviders object contains a reference 5758 // to a provider that we don't want to change. 5759 // Only do this for the second authority since the resulting provider 5760 // object can be the same for all future authorities for this provider. 5761 p = new PackageParser.Provider(p); 5762 p.syncable = false; 5763 } 5764 if (!mProvidersByAuthority.containsKey(names[j])) { 5765 mProvidersByAuthority.put(names[j], p); 5766 if (p.info.authority == null) { 5767 p.info.authority = names[j]; 5768 } else { 5769 p.info.authority = p.info.authority + ";" + names[j]; 5770 } 5771 if (DEBUG_PACKAGE_SCANNING) { 5772 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5773 Log.d(TAG, "Registered content provider: " + names[j] 5774 + ", className = " + p.info.name + ", isSyncable = " 5775 + p.info.isSyncable); 5776 } 5777 } else { 5778 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5779 Slog.w(TAG, "Skipping provider name " + names[j] + 5780 " (in package " + pkg.applicationInfo.packageName + 5781 "): name already used by " 5782 + ((other != null && other.getComponentName() != null) 5783 ? other.getComponentName().getPackageName() : "?")); 5784 } 5785 } 5786 } 5787 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5788 if (r == null) { 5789 r = new StringBuilder(256); 5790 } else { 5791 r.append(' '); 5792 } 5793 r.append(p.info.name); 5794 } 5795 } 5796 if (r != null) { 5797 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5798 } 5799 5800 N = pkg.services.size(); 5801 r = null; 5802 for (i=0; i<N; i++) { 5803 PackageParser.Service s = pkg.services.get(i); 5804 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5805 s.info.processName, pkg.applicationInfo.uid); 5806 mServices.addService(s); 5807 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5808 if (r == null) { 5809 r = new StringBuilder(256); 5810 } else { 5811 r.append(' '); 5812 } 5813 r.append(s.info.name); 5814 } 5815 } 5816 if (r != null) { 5817 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5818 } 5819 5820 N = pkg.receivers.size(); 5821 r = null; 5822 for (i=0; i<N; i++) { 5823 PackageParser.Activity a = pkg.receivers.get(i); 5824 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5825 a.info.processName, pkg.applicationInfo.uid); 5826 mReceivers.addActivity(a, "receiver"); 5827 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5828 if (r == null) { 5829 r = new StringBuilder(256); 5830 } else { 5831 r.append(' '); 5832 } 5833 r.append(a.info.name); 5834 } 5835 } 5836 if (r != null) { 5837 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5838 } 5839 5840 N = pkg.activities.size(); 5841 r = null; 5842 for (i=0; i<N; i++) { 5843 PackageParser.Activity a = pkg.activities.get(i); 5844 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5845 a.info.processName, pkg.applicationInfo.uid); 5846 mActivities.addActivity(a, "activity"); 5847 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5848 if (r == null) { 5849 r = new StringBuilder(256); 5850 } else { 5851 r.append(' '); 5852 } 5853 r.append(a.info.name); 5854 } 5855 } 5856 if (r != null) { 5857 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5858 } 5859 5860 N = pkg.permissionGroups.size(); 5861 r = null; 5862 for (i=0; i<N; i++) { 5863 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5864 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5865 if (cur == null) { 5866 mPermissionGroups.put(pg.info.name, pg); 5867 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5868 if (r == null) { 5869 r = new StringBuilder(256); 5870 } else { 5871 r.append(' '); 5872 } 5873 r.append(pg.info.name); 5874 } 5875 } else { 5876 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5877 + pg.info.packageName + " ignored: original from " 5878 + cur.info.packageName); 5879 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5880 if (r == null) { 5881 r = new StringBuilder(256); 5882 } else { 5883 r.append(' '); 5884 } 5885 r.append("DUP:"); 5886 r.append(pg.info.name); 5887 } 5888 } 5889 } 5890 if (r != null) { 5891 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5892 } 5893 5894 N = pkg.permissions.size(); 5895 r = null; 5896 for (i=0; i<N; i++) { 5897 PackageParser.Permission p = pkg.permissions.get(i); 5898 HashMap<String, BasePermission> permissionMap = 5899 p.tree ? mSettings.mPermissionTrees 5900 : mSettings.mPermissions; 5901 p.group = mPermissionGroups.get(p.info.group); 5902 if (p.info.group == null || p.group != null) { 5903 BasePermission bp = permissionMap.get(p.info.name); 5904 if (bp == null) { 5905 bp = new BasePermission(p.info.name, p.info.packageName, 5906 BasePermission.TYPE_NORMAL); 5907 permissionMap.put(p.info.name, bp); 5908 } 5909 if (bp.perm == null) { 5910 if (bp.sourcePackage != null 5911 && !bp.sourcePackage.equals(p.info.packageName)) { 5912 // If this is a permission that was formerly defined by a non-system 5913 // app, but is now defined by a system app (following an upgrade), 5914 // discard the previous declaration and consider the system's to be 5915 // canonical. 5916 if (isSystemApp(p.owner)) { 5917 String msg = "New decl " + p.owner + " of permission " 5918 + p.info.name + " is system"; 5919 reportSettingsProblem(Log.WARN, msg); 5920 bp.sourcePackage = null; 5921 } 5922 } 5923 if (bp.sourcePackage == null 5924 || bp.sourcePackage.equals(p.info.packageName)) { 5925 BasePermission tree = findPermissionTreeLP(p.info.name); 5926 if (tree == null 5927 || tree.sourcePackage.equals(p.info.packageName)) { 5928 bp.packageSetting = pkgSetting; 5929 bp.perm = p; 5930 bp.uid = pkg.applicationInfo.uid; 5931 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5932 if (r == null) { 5933 r = new StringBuilder(256); 5934 } else { 5935 r.append(' '); 5936 } 5937 r.append(p.info.name); 5938 } 5939 } else { 5940 Slog.w(TAG, "Permission " + p.info.name + " from package " 5941 + p.info.packageName + " ignored: base tree " 5942 + tree.name + " is from package " 5943 + tree.sourcePackage); 5944 } 5945 } else { 5946 Slog.w(TAG, "Permission " + p.info.name + " from package " 5947 + p.info.packageName + " ignored: original from " 5948 + bp.sourcePackage); 5949 } 5950 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5951 if (r == null) { 5952 r = new StringBuilder(256); 5953 } else { 5954 r.append(' '); 5955 } 5956 r.append("DUP:"); 5957 r.append(p.info.name); 5958 } 5959 if (bp.perm == p) { 5960 bp.protectionLevel = p.info.protectionLevel; 5961 } 5962 } else { 5963 Slog.w(TAG, "Permission " + p.info.name + " from package " 5964 + p.info.packageName + " ignored: no group " 5965 + p.group); 5966 } 5967 } 5968 if (r != null) { 5969 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 5970 } 5971 5972 N = pkg.instrumentation.size(); 5973 r = null; 5974 for (i=0; i<N; i++) { 5975 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5976 a.info.packageName = pkg.applicationInfo.packageName; 5977 a.info.sourceDir = pkg.applicationInfo.sourceDir; 5978 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 5979 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 5980 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 5981 a.info.dataDir = pkg.applicationInfo.dataDir; 5982 5983 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 5984 // need other information about the application, like the ABI and what not ? 5985 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 5986 mInstrumentation.put(a.getComponentName(), a); 5987 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5988 if (r == null) { 5989 r = new StringBuilder(256); 5990 } else { 5991 r.append(' '); 5992 } 5993 r.append(a.info.name); 5994 } 5995 } 5996 if (r != null) { 5997 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 5998 } 5999 6000 if (pkg.protectedBroadcasts != null) { 6001 N = pkg.protectedBroadcasts.size(); 6002 for (i=0; i<N; i++) { 6003 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6004 } 6005 } 6006 6007 pkgSetting.setTimeStamp(scanFileTime); 6008 6009 // Create idmap files for pairs of (packages, overlay packages). 6010 // Note: "android", ie framework-res.apk, is handled by native layers. 6011 if (pkg.mOverlayTarget != null) { 6012 // This is an overlay package. 6013 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6014 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6015 mOverlays.put(pkg.mOverlayTarget, 6016 new HashMap<String, PackageParser.Package>()); 6017 } 6018 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6019 map.put(pkg.packageName, pkg); 6020 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6021 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6022 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6023 "scanPackageLI failed to createIdmap"); 6024 } 6025 } 6026 } else if (mOverlays.containsKey(pkg.packageName) && 6027 !pkg.packageName.equals("android")) { 6028 // This is a regular package, with one or more known overlay packages. 6029 createIdmapsForPackageLI(pkg); 6030 } 6031 } 6032 6033 return pkg; 6034 } 6035 6036 /** 6037 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6038 * i.e, so that all packages can be run inside a single process if required. 6039 * 6040 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6041 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6042 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6043 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6044 * updating a package that belongs to a shared user. 6045 * 6046 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6047 * adds unnecessary complexity. 6048 */ 6049 private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6050 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6051 String requiredInstructionSet = null; 6052 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6053 requiredInstructionSet = VMRuntime.getInstructionSet( 6054 scannedPackage.applicationInfo.primaryCpuAbi); 6055 } 6056 6057 PackageSetting requirer = null; 6058 for (PackageSetting ps : packagesForUser) { 6059 // If packagesForUser contains scannedPackage, we skip it. This will happen 6060 // when scannedPackage is an update of an existing package. Without this check, 6061 // we will never be able to change the ABI of any package belonging to a shared 6062 // user, even if it's compatible with other packages. 6063 if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) { 6064 if (ps.primaryCpuAbiString == null) { 6065 continue; 6066 } 6067 6068 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6069 if (requiredInstructionSet != null) { 6070 if (!instructionSet.equals(requiredInstructionSet)) { 6071 // We have a mismatch between instruction sets (say arm vs arm64). 6072 // bail out. 6073 String errorMessage = "Instruction set mismatch, " 6074 + ((requirer == null) ? "[caller]" : requirer) 6075 + " requires " + requiredInstructionSet + " whereas " + ps 6076 + " requires " + instructionSet; 6077 Slog.e(TAG, errorMessage); 6078 6079 reportSettingsProblem(Log.WARN, errorMessage); 6080 // Give up, don't bother making any other changes to the package settings. 6081 return false; 6082 } 6083 } else { 6084 requiredInstructionSet = instructionSet; 6085 requirer = ps; 6086 } 6087 } 6088 } 6089 6090 if (requiredInstructionSet != null) { 6091 String adjustedAbi; 6092 if (requirer != null) { 6093 // requirer != null implies that either scannedPackage was null or that scannedPackage 6094 // did not require an ABI, in which case we have to adjust scannedPackage to match 6095 // the ABI of the set (which is the same as requirer's ABI) 6096 adjustedAbi = requirer.primaryCpuAbiString; 6097 if (scannedPackage != null) { 6098 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6099 } 6100 } else { 6101 // requirer == null implies that we're updating all ABIs in the set to 6102 // match scannedPackage. 6103 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6104 } 6105 6106 for (PackageSetting ps : packagesForUser) { 6107 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6108 if (ps.primaryCpuAbiString != null) { 6109 continue; 6110 } 6111 6112 ps.primaryCpuAbiString = adjustedAbi; 6113 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6114 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6115 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6116 6117 if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) { 6118 ps.primaryCpuAbiString = null; 6119 ps.pkg.applicationInfo.primaryCpuAbi = null; 6120 return false; 6121 } else { 6122 mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet()); 6123 } 6124 } 6125 } 6126 } 6127 } 6128 6129 return true; 6130 } 6131 6132 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6133 synchronized (mPackages) { 6134 mResolverReplaced = true; 6135 // Set up information for custom user intent resolution activity. 6136 mResolveActivity.applicationInfo = pkg.applicationInfo; 6137 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6138 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6139 mResolveActivity.processName = null; 6140 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6141 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6142 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6143 mResolveActivity.theme = 0; 6144 mResolveActivity.exported = true; 6145 mResolveActivity.enabled = true; 6146 mResolveInfo.activityInfo = mResolveActivity; 6147 mResolveInfo.priority = 0; 6148 mResolveInfo.preferredOrder = 0; 6149 mResolveInfo.match = 0; 6150 mResolveComponentName = mCustomResolverComponentName; 6151 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6152 mResolveComponentName); 6153 } 6154 } 6155 6156 private static String calculateApkRoot(final String codePathString) { 6157 final File codePath = new File(codePathString); 6158 final File codeRoot; 6159 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6160 codeRoot = Environment.getRootDirectory(); 6161 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6162 codeRoot = Environment.getOemDirectory(); 6163 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6164 codeRoot = Environment.getVendorDirectory(); 6165 } else { 6166 // Unrecognized code path; take its top real segment as the apk root: 6167 // e.g. /something/app/blah.apk => /something 6168 try { 6169 File f = codePath.getCanonicalFile(); 6170 File parent = f.getParentFile(); // non-null because codePath is a file 6171 File tmp; 6172 while ((tmp = parent.getParentFile()) != null) { 6173 f = parent; 6174 parent = tmp; 6175 } 6176 codeRoot = f; 6177 Slog.w(TAG, "Unrecognized code path " 6178 + codePath + " - using " + codeRoot); 6179 } catch (IOException e) { 6180 // Can't canonicalize the code path -- shenanigans? 6181 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6182 return Environment.getRootDirectory().getPath(); 6183 } 6184 } 6185 return codeRoot.getPath(); 6186 } 6187 6188 /** 6189 * Derive and set the location of native libraries for the given package, 6190 * which varies depending on where and how the package was installed. 6191 */ 6192 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6193 final ApplicationInfo info = pkg.applicationInfo; 6194 final String codePath = pkg.codePath; 6195 final File codeFile = new File(codePath); 6196 6197 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6198 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6199 6200 info.nativeLibraryRootDir = null; 6201 info.nativeLibraryRootRequiresIsa = false; 6202 info.nativeLibraryDir = null; 6203 6204 if (bundledApp) { 6205 // Monolithic bundled install 6206 // TODO: support cluster bundled installs? 6207 6208 final boolean is64Bit = (info.primaryCpuAbi != null) 6209 && VMRuntime.is64BitAbi(info.primaryCpuAbi); 6210 6211 // This is a bundled system app so choose the path based on the ABI. 6212 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6213 // is just the default path. 6214 final String apkName = deriveCodePathName(codePath); 6215 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6216 info.nativeLibraryRootDir = Environment.buildPath(new File(info.apkRoot), libDir, 6217 apkName).getAbsolutePath(); 6218 info.nativeLibraryRootRequiresIsa = false; 6219 6220 } else if (isApkFile(codeFile)) { 6221 // Monolithic install 6222 if (asecApp) { 6223 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6224 .getAbsolutePath(); 6225 info.nativeLibraryRootRequiresIsa = false; 6226 } else { 6227 final String apkName = deriveCodePathName(codePath); 6228 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6229 .getAbsolutePath(); 6230 info.nativeLibraryRootRequiresIsa = false; 6231 } 6232 } else { 6233 // Cluster install 6234 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6235 info.nativeLibraryRootRequiresIsa = true; 6236 } 6237 6238 if (info.nativeLibraryRootRequiresIsa) { 6239 if (info.primaryCpuAbi != null) { 6240 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6241 VMRuntime.getInstructionSet(info.primaryCpuAbi)).getAbsolutePath(); 6242 } else { 6243 Slog.w(TAG, "Package " + info.packageName 6244 + " missing ABI; unable to derive nativeLibraryDir"); 6245 } 6246 } else { 6247 info.nativeLibraryDir = info.nativeLibraryRootDir; 6248 } 6249 } 6250 6251 /** 6252 * Calculate the abis and roots for a bundled app. These can uniquely 6253 * be determined from the contents of the system partition, i.e whether 6254 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6255 * of this information, and instead assume that the system was built 6256 * sensibly. 6257 */ 6258 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6259 PackageSetting pkgSetting) { 6260 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6261 6262 // If "/system/lib64/apkname" exists, assume that is the per-package 6263 // native library directory to use; otherwise use "/system/lib/apkname". 6264 final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6265 pkg.applicationInfo.apkRoot = apkRoot; 6266 setBundledAppAbi(pkg, apkRoot, apkName); 6267 // pkgSetting might be null during rescan following uninstall of updates 6268 // to a bundled app, so accommodate that possibility. The settings in 6269 // that case will be established later from the parsed package. 6270 // 6271 // If the settings aren't null, sync them up with what we've just derived. 6272 // note that apkRoot isn't stored in the package settings. 6273 if (pkgSetting != null) { 6274 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6275 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6276 } 6277 } 6278 6279 /** 6280 * Deduces the ABI of a bundled app and sets the relevant fields on the 6281 * parsed pkg object. 6282 * 6283 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6284 * under which system libraries are installed. 6285 * @param apkName the name of the installed package. 6286 */ 6287 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6288 // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>" 6289 // or similar. 6290 final boolean has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6291 final boolean has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6292 6293 if (has64BitLibs && !has32BitLibs) { 6294 // The package has 64 bit libs, but not 32 bit libs. Its primary 6295 // ABI should be 64 bit. We can safely assume here that the bundled 6296 // native libraries correspond to the most preferred ABI in the list. 6297 6298 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6299 pkg.applicationInfo.secondaryCpuAbi = null; 6300 } else if (has32BitLibs && !has64BitLibs) { 6301 // The package has 32 bit libs but not 64 bit libs. Its primary 6302 // ABI should be 32 bit. 6303 6304 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6305 pkg.applicationInfo.secondaryCpuAbi = null; 6306 } else if (has32BitLibs && has64BitLibs) { 6307 // The application has both 64 and 32 bit bundled libraries. We check 6308 // here that the app declares multiArch support, and warn if it doesn't. 6309 // 6310 // We will be lenient here and record both ABIs. The primary will be the 6311 // ABI that's higher on the list, i.e, a device that's configured to prefer 6312 // 64 bit apps will see a 64 bit primary ABI, 6313 6314 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6315 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6316 } 6317 6318 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6319 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6320 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6321 } else { 6322 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6323 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6324 } 6325 } else { 6326 pkg.applicationInfo.primaryCpuAbi = null; 6327 pkg.applicationInfo.secondaryCpuAbi = null; 6328 } 6329 } 6330 6331 private static void createNativeLibrarySubdir(File path) throws IOException { 6332 if (!path.isDirectory()) { 6333 path.delete(); 6334 6335 if (!path.mkdir()) { 6336 throw new IOException("Cannot create " + path.getPath()); 6337 } 6338 6339 try { 6340 Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6341 } catch (ErrnoException e) { 6342 throw new IOException("Cannot chmod native library directory " 6343 + path.getPath(), e); 6344 } 6345 } else if (!SELinux.restorecon(path)) { 6346 throw new IOException("Cannot set SELinux context for " + path.getPath()); 6347 } 6348 } 6349 6350 private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle, 6351 final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException { 6352 createNativeLibrarySubdir(nativeLibraryRoot); 6353 6354 /* 6355 * If this is an internal application or our nativeLibraryPath points to 6356 * the app-lib directory, unpack the libraries if necessary. 6357 */ 6358 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6359 if (abi >= 0) { 6360 /* 6361 * If we have a matching instruction set, construct a subdir under the native 6362 * library root that corresponds to this instruction set. 6363 */ 6364 final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]); 6365 final File subDir; 6366 if (useIsaSubdir) { 6367 final File isaSubdir = new File(nativeLibraryRoot, instructionSet); 6368 createNativeLibrarySubdir(isaSubdir); 6369 subDir = isaSubdir; 6370 } else { 6371 subDir = nativeLibraryRoot; 6372 } 6373 6374 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, subDir, abiList[abi]); 6375 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6376 return copyRet; 6377 } 6378 } 6379 6380 return abi; 6381 } 6382 6383 private void killApplication(String pkgName, int appId, String reason) { 6384 // Request the ActivityManager to kill the process(only for existing packages) 6385 // so that we do not end up in a confused state while the user is still using the older 6386 // version of the application while the new one gets installed. 6387 IActivityManager am = ActivityManagerNative.getDefault(); 6388 if (am != null) { 6389 try { 6390 am.killApplicationWithAppId(pkgName, appId, reason); 6391 } catch (RemoteException e) { 6392 } 6393 } 6394 } 6395 6396 void removePackageLI(PackageSetting ps, boolean chatty) { 6397 if (DEBUG_INSTALL) { 6398 if (chatty) 6399 Log.d(TAG, "Removing package " + ps.name); 6400 } 6401 6402 // writer 6403 synchronized (mPackages) { 6404 mPackages.remove(ps.name); 6405 if (ps.codePathString != null) { 6406 mAppDirs.remove(ps.codePathString); 6407 } 6408 6409 final PackageParser.Package pkg = ps.pkg; 6410 if (pkg != null) { 6411 cleanPackageDataStructuresLILPw(pkg, chatty); 6412 } 6413 } 6414 } 6415 6416 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6417 if (DEBUG_INSTALL) { 6418 if (chatty) 6419 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6420 } 6421 6422 // writer 6423 synchronized (mPackages) { 6424 mPackages.remove(pkg.applicationInfo.packageName); 6425 if (pkg.codePath != null) { 6426 mAppDirs.remove(pkg.codePath); 6427 } 6428 cleanPackageDataStructuresLILPw(pkg, chatty); 6429 } 6430 } 6431 6432 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6433 int N = pkg.providers.size(); 6434 StringBuilder r = null; 6435 int i; 6436 for (i=0; i<N; i++) { 6437 PackageParser.Provider p = pkg.providers.get(i); 6438 mProviders.removeProvider(p); 6439 if (p.info.authority == null) { 6440 6441 /* There was another ContentProvider with this authority when 6442 * this app was installed so this authority is null, 6443 * Ignore it as we don't have to unregister the provider. 6444 */ 6445 continue; 6446 } 6447 String names[] = p.info.authority.split(";"); 6448 for (int j = 0; j < names.length; j++) { 6449 if (mProvidersByAuthority.get(names[j]) == p) { 6450 mProvidersByAuthority.remove(names[j]); 6451 if (DEBUG_REMOVE) { 6452 if (chatty) 6453 Log.d(TAG, "Unregistered content provider: " + names[j] 6454 + ", className = " + p.info.name + ", isSyncable = " 6455 + p.info.isSyncable); 6456 } 6457 } 6458 } 6459 if (DEBUG_REMOVE && chatty) { 6460 if (r == null) { 6461 r = new StringBuilder(256); 6462 } else { 6463 r.append(' '); 6464 } 6465 r.append(p.info.name); 6466 } 6467 } 6468 if (r != null) { 6469 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6470 } 6471 6472 N = pkg.services.size(); 6473 r = null; 6474 for (i=0; i<N; i++) { 6475 PackageParser.Service s = pkg.services.get(i); 6476 mServices.removeService(s); 6477 if (chatty) { 6478 if (r == null) { 6479 r = new StringBuilder(256); 6480 } else { 6481 r.append(' '); 6482 } 6483 r.append(s.info.name); 6484 } 6485 } 6486 if (r != null) { 6487 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6488 } 6489 6490 N = pkg.receivers.size(); 6491 r = null; 6492 for (i=0; i<N; i++) { 6493 PackageParser.Activity a = pkg.receivers.get(i); 6494 mReceivers.removeActivity(a, "receiver"); 6495 if (DEBUG_REMOVE && chatty) { 6496 if (r == null) { 6497 r = new StringBuilder(256); 6498 } else { 6499 r.append(' '); 6500 } 6501 r.append(a.info.name); 6502 } 6503 } 6504 if (r != null) { 6505 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6506 } 6507 6508 N = pkg.activities.size(); 6509 r = null; 6510 for (i=0; i<N; i++) { 6511 PackageParser.Activity a = pkg.activities.get(i); 6512 mActivities.removeActivity(a, "activity"); 6513 if (DEBUG_REMOVE && chatty) { 6514 if (r == null) { 6515 r = new StringBuilder(256); 6516 } else { 6517 r.append(' '); 6518 } 6519 r.append(a.info.name); 6520 } 6521 } 6522 if (r != null) { 6523 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6524 } 6525 6526 N = pkg.permissions.size(); 6527 r = null; 6528 for (i=0; i<N; i++) { 6529 PackageParser.Permission p = pkg.permissions.get(i); 6530 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6531 if (bp == null) { 6532 bp = mSettings.mPermissionTrees.get(p.info.name); 6533 } 6534 if (bp != null && bp.perm == p) { 6535 bp.perm = null; 6536 if (DEBUG_REMOVE && chatty) { 6537 if (r == null) { 6538 r = new StringBuilder(256); 6539 } else { 6540 r.append(' '); 6541 } 6542 r.append(p.info.name); 6543 } 6544 } 6545 } 6546 if (r != null) { 6547 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6548 } 6549 6550 N = pkg.instrumentation.size(); 6551 r = null; 6552 for (i=0; i<N; i++) { 6553 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6554 mInstrumentation.remove(a.getComponentName()); 6555 if (DEBUG_REMOVE && chatty) { 6556 if (r == null) { 6557 r = new StringBuilder(256); 6558 } else { 6559 r.append(' '); 6560 } 6561 r.append(a.info.name); 6562 } 6563 } 6564 if (r != null) { 6565 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6566 } 6567 6568 r = null; 6569 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6570 // Only system apps can hold shared libraries. 6571 if (pkg.libraryNames != null) { 6572 for (i=0; i<pkg.libraryNames.size(); i++) { 6573 String name = pkg.libraryNames.get(i); 6574 SharedLibraryEntry cur = mSharedLibraries.get(name); 6575 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6576 mSharedLibraries.remove(name); 6577 if (DEBUG_REMOVE && chatty) { 6578 if (r == null) { 6579 r = new StringBuilder(256); 6580 } else { 6581 r.append(' '); 6582 } 6583 r.append(name); 6584 } 6585 } 6586 } 6587 } 6588 } 6589 if (r != null) { 6590 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6591 } 6592 } 6593 6594 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6595 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6596 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6597 return true; 6598 } 6599 } 6600 return false; 6601 } 6602 6603 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6604 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6605 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6606 6607 private void updatePermissionsLPw(String changingPkg, 6608 PackageParser.Package pkgInfo, int flags) { 6609 // Make sure there are no dangling permission trees. 6610 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6611 while (it.hasNext()) { 6612 final BasePermission bp = it.next(); 6613 if (bp.packageSetting == null) { 6614 // We may not yet have parsed the package, so just see if 6615 // we still know about its settings. 6616 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6617 } 6618 if (bp.packageSetting == null) { 6619 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6620 + " from package " + bp.sourcePackage); 6621 it.remove(); 6622 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6623 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6624 Slog.i(TAG, "Removing old permission tree: " + bp.name 6625 + " from package " + bp.sourcePackage); 6626 flags |= UPDATE_PERMISSIONS_ALL; 6627 it.remove(); 6628 } 6629 } 6630 } 6631 6632 // Make sure all dynamic permissions have been assigned to a package, 6633 // and make sure there are no dangling permissions. 6634 it = mSettings.mPermissions.values().iterator(); 6635 while (it.hasNext()) { 6636 final BasePermission bp = it.next(); 6637 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6638 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6639 + bp.name + " pkg=" + bp.sourcePackage 6640 + " info=" + bp.pendingInfo); 6641 if (bp.packageSetting == null && bp.pendingInfo != null) { 6642 final BasePermission tree = findPermissionTreeLP(bp.name); 6643 if (tree != null && tree.perm != null) { 6644 bp.packageSetting = tree.packageSetting; 6645 bp.perm = new PackageParser.Permission(tree.perm.owner, 6646 new PermissionInfo(bp.pendingInfo)); 6647 bp.perm.info.packageName = tree.perm.info.packageName; 6648 bp.perm.info.name = bp.name; 6649 bp.uid = tree.uid; 6650 } 6651 } 6652 } 6653 if (bp.packageSetting == null) { 6654 // We may not yet have parsed the package, so just see if 6655 // we still know about its settings. 6656 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6657 } 6658 if (bp.packageSetting == null) { 6659 Slog.w(TAG, "Removing dangling permission: " + bp.name 6660 + " from package " + bp.sourcePackage); 6661 it.remove(); 6662 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6663 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6664 Slog.i(TAG, "Removing old permission: " + bp.name 6665 + " from package " + bp.sourcePackage); 6666 flags |= UPDATE_PERMISSIONS_ALL; 6667 it.remove(); 6668 } 6669 } 6670 } 6671 6672 // Now update the permissions for all packages, in particular 6673 // replace the granted permissions of the system packages. 6674 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6675 for (PackageParser.Package pkg : mPackages.values()) { 6676 if (pkg != pkgInfo) { 6677 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6678 } 6679 } 6680 } 6681 6682 if (pkgInfo != null) { 6683 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6684 } 6685 } 6686 6687 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6688 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6689 if (ps == null) { 6690 return; 6691 } 6692 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6693 HashSet<String> origPermissions = gp.grantedPermissions; 6694 boolean changedPermission = false; 6695 6696 if (replace) { 6697 ps.permissionsFixed = false; 6698 if (gp == ps) { 6699 origPermissions = new HashSet<String>(gp.grantedPermissions); 6700 gp.grantedPermissions.clear(); 6701 gp.gids = mGlobalGids; 6702 } 6703 } 6704 6705 if (gp.gids == null) { 6706 gp.gids = mGlobalGids; 6707 } 6708 6709 final int N = pkg.requestedPermissions.size(); 6710 for (int i=0; i<N; i++) { 6711 final String name = pkg.requestedPermissions.get(i); 6712 final boolean required = pkg.requestedPermissionsRequired.get(i); 6713 final BasePermission bp = mSettings.mPermissions.get(name); 6714 if (DEBUG_INSTALL) { 6715 if (gp != ps) { 6716 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6717 } 6718 } 6719 6720 if (bp == null || bp.packageSetting == null) { 6721 Slog.w(TAG, "Unknown permission " + name 6722 + " in package " + pkg.packageName); 6723 continue; 6724 } 6725 6726 final String perm = bp.name; 6727 boolean allowed; 6728 boolean allowedSig = false; 6729 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6730 if (level == PermissionInfo.PROTECTION_NORMAL 6731 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6732 // We grant a normal or dangerous permission if any of the following 6733 // are true: 6734 // 1) The permission is required 6735 // 2) The permission is optional, but was granted in the past 6736 // 3) The permission is optional, but was requested by an 6737 // app in /system (not /data) 6738 // 6739 // Otherwise, reject the permission. 6740 allowed = (required || origPermissions.contains(perm) 6741 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6742 } else if (bp.packageSetting == null) { 6743 // This permission is invalid; skip it. 6744 allowed = false; 6745 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6746 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6747 if (allowed) { 6748 allowedSig = true; 6749 } 6750 } else { 6751 allowed = false; 6752 } 6753 if (DEBUG_INSTALL) { 6754 if (gp != ps) { 6755 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6756 } 6757 } 6758 if (allowed) { 6759 if (!isSystemApp(ps) && ps.permissionsFixed) { 6760 // If this is an existing, non-system package, then 6761 // we can't add any new permissions to it. 6762 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6763 // Except... if this is a permission that was added 6764 // to the platform (note: need to only do this when 6765 // updating the platform). 6766 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6767 } 6768 } 6769 if (allowed) { 6770 if (!gp.grantedPermissions.contains(perm)) { 6771 changedPermission = true; 6772 gp.grantedPermissions.add(perm); 6773 gp.gids = appendInts(gp.gids, bp.gids); 6774 } else if (!ps.haveGids) { 6775 gp.gids = appendInts(gp.gids, bp.gids); 6776 } 6777 } else { 6778 Slog.w(TAG, "Not granting permission " + perm 6779 + " to package " + pkg.packageName 6780 + " because it was previously installed without"); 6781 } 6782 } else { 6783 if (gp.grantedPermissions.remove(perm)) { 6784 changedPermission = true; 6785 gp.gids = removeInts(gp.gids, bp.gids); 6786 Slog.i(TAG, "Un-granting permission " + perm 6787 + " from package " + pkg.packageName 6788 + " (protectionLevel=" + bp.protectionLevel 6789 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6790 + ")"); 6791 } else { 6792 Slog.w(TAG, "Not granting permission " + perm 6793 + " to package " + pkg.packageName 6794 + " (protectionLevel=" + bp.protectionLevel 6795 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6796 + ")"); 6797 } 6798 } 6799 } 6800 6801 if ((changedPermission || replace) && !ps.permissionsFixed && 6802 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6803 // This is the first that we have heard about this package, so the 6804 // permissions we have now selected are fixed until explicitly 6805 // changed. 6806 ps.permissionsFixed = true; 6807 } 6808 ps.haveGids = true; 6809 } 6810 6811 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6812 boolean allowed = false; 6813 final int NP = PackageParser.NEW_PERMISSIONS.length; 6814 for (int ip=0; ip<NP; ip++) { 6815 final PackageParser.NewPermissionInfo npi 6816 = PackageParser.NEW_PERMISSIONS[ip]; 6817 if (npi.name.equals(perm) 6818 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6819 allowed = true; 6820 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6821 + pkg.packageName); 6822 break; 6823 } 6824 } 6825 return allowed; 6826 } 6827 6828 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6829 BasePermission bp, HashSet<String> origPermissions) { 6830 boolean allowed; 6831 allowed = (compareSignatures( 6832 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6833 == PackageManager.SIGNATURE_MATCH) 6834 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6835 == PackageManager.SIGNATURE_MATCH); 6836 if (!allowed && (bp.protectionLevel 6837 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6838 if (isSystemApp(pkg)) { 6839 // For updated system applications, a system permission 6840 // is granted only if it had been defined by the original application. 6841 if (isUpdatedSystemApp(pkg)) { 6842 final PackageSetting sysPs = mSettings 6843 .getDisabledSystemPkgLPr(pkg.packageName); 6844 final GrantedPermissions origGp = sysPs.sharedUser != null 6845 ? sysPs.sharedUser : sysPs; 6846 6847 if (origGp.grantedPermissions.contains(perm)) { 6848 // If the original was granted this permission, we take 6849 // that grant decision as read and propagate it to the 6850 // update. 6851 allowed = true; 6852 } else { 6853 // The system apk may have been updated with an older 6854 // version of the one on the data partition, but which 6855 // granted a new system permission that it didn't have 6856 // before. In this case we do want to allow the app to 6857 // now get the new permission if the ancestral apk is 6858 // privileged to get it. 6859 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6860 for (int j=0; 6861 j<sysPs.pkg.requestedPermissions.size(); j++) { 6862 if (perm.equals( 6863 sysPs.pkg.requestedPermissions.get(j))) { 6864 allowed = true; 6865 break; 6866 } 6867 } 6868 } 6869 } 6870 } else { 6871 allowed = isPrivilegedApp(pkg); 6872 } 6873 } 6874 } 6875 if (!allowed && (bp.protectionLevel 6876 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6877 // For development permissions, a development permission 6878 // is granted only if it was already granted. 6879 allowed = origPermissions.contains(perm); 6880 } 6881 return allowed; 6882 } 6883 6884 final class ActivityIntentResolver 6885 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6886 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6887 boolean defaultOnly, int userId) { 6888 if (!sUserManager.exists(userId)) return null; 6889 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6890 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6891 } 6892 6893 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6894 int userId) { 6895 if (!sUserManager.exists(userId)) return null; 6896 mFlags = flags; 6897 return super.queryIntent(intent, resolvedType, 6898 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6899 } 6900 6901 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6902 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6903 if (!sUserManager.exists(userId)) return null; 6904 if (packageActivities == null) { 6905 return null; 6906 } 6907 mFlags = flags; 6908 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6909 final int N = packageActivities.size(); 6910 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6911 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6912 6913 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6914 for (int i = 0; i < N; ++i) { 6915 intentFilters = packageActivities.get(i).intents; 6916 if (intentFilters != null && intentFilters.size() > 0) { 6917 PackageParser.ActivityIntentInfo[] array = 6918 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6919 intentFilters.toArray(array); 6920 listCut.add(array); 6921 } 6922 } 6923 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6924 } 6925 6926 public final void addActivity(PackageParser.Activity a, String type) { 6927 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6928 mActivities.put(a.getComponentName(), a); 6929 if (DEBUG_SHOW_INFO) 6930 Log.v( 6931 TAG, " " + type + " " + 6932 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6933 if (DEBUG_SHOW_INFO) 6934 Log.v(TAG, " Class=" + a.info.name); 6935 final int NI = a.intents.size(); 6936 for (int j=0; j<NI; j++) { 6937 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6938 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6939 intent.setPriority(0); 6940 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6941 + a.className + " with priority > 0, forcing to 0"); 6942 } 6943 if (DEBUG_SHOW_INFO) { 6944 Log.v(TAG, " IntentFilter:"); 6945 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6946 } 6947 if (!intent.debugCheck()) { 6948 Log.w(TAG, "==> For Activity " + a.info.name); 6949 } 6950 addFilter(intent); 6951 } 6952 } 6953 6954 public final void removeActivity(PackageParser.Activity a, String type) { 6955 mActivities.remove(a.getComponentName()); 6956 if (DEBUG_SHOW_INFO) { 6957 Log.v(TAG, " " + type + " " 6958 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6959 : a.info.name) + ":"); 6960 Log.v(TAG, " Class=" + a.info.name); 6961 } 6962 final int NI = a.intents.size(); 6963 for (int j=0; j<NI; j++) { 6964 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6965 if (DEBUG_SHOW_INFO) { 6966 Log.v(TAG, " IntentFilter:"); 6967 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6968 } 6969 removeFilter(intent); 6970 } 6971 } 6972 6973 @Override 6974 protected boolean allowFilterResult( 6975 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 6976 ActivityInfo filterAi = filter.activity.info; 6977 for (int i=dest.size()-1; i>=0; i--) { 6978 ActivityInfo destAi = dest.get(i).activityInfo; 6979 if (destAi.name == filterAi.name 6980 && destAi.packageName == filterAi.packageName) { 6981 return false; 6982 } 6983 } 6984 return true; 6985 } 6986 6987 @Override 6988 protected ActivityIntentInfo[] newArray(int size) { 6989 return new ActivityIntentInfo[size]; 6990 } 6991 6992 @Override 6993 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 6994 if (!sUserManager.exists(userId)) return true; 6995 PackageParser.Package p = filter.activity.owner; 6996 if (p != null) { 6997 PackageSetting ps = (PackageSetting)p.mExtras; 6998 if (ps != null) { 6999 // System apps are never considered stopped for purposes of 7000 // filtering, because there may be no way for the user to 7001 // actually re-launch them. 7002 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7003 && ps.getStopped(userId); 7004 } 7005 } 7006 return false; 7007 } 7008 7009 @Override 7010 protected boolean isPackageForFilter(String packageName, 7011 PackageParser.ActivityIntentInfo info) { 7012 return packageName.equals(info.activity.owner.packageName); 7013 } 7014 7015 @Override 7016 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7017 int match, int userId) { 7018 if (!sUserManager.exists(userId)) return null; 7019 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7020 return null; 7021 } 7022 final PackageParser.Activity activity = info.activity; 7023 if (mSafeMode && (activity.info.applicationInfo.flags 7024 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7025 return null; 7026 } 7027 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7028 if (ps == null) { 7029 return null; 7030 } 7031 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7032 ps.readUserState(userId), userId); 7033 if (ai == null) { 7034 return null; 7035 } 7036 final ResolveInfo res = new ResolveInfo(); 7037 res.activityInfo = ai; 7038 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7039 res.filter = info; 7040 } 7041 res.priority = info.getPriority(); 7042 res.preferredOrder = activity.owner.mPreferredOrder; 7043 //System.out.println("Result: " + res.activityInfo.className + 7044 // " = " + res.priority); 7045 res.match = match; 7046 res.isDefault = info.hasDefault; 7047 res.labelRes = info.labelRes; 7048 res.nonLocalizedLabel = info.nonLocalizedLabel; 7049 if (userNeedsBadging(userId)) { 7050 res.noResourceId = true; 7051 } else { 7052 res.icon = info.icon; 7053 } 7054 res.system = isSystemApp(res.activityInfo.applicationInfo); 7055 return res; 7056 } 7057 7058 @Override 7059 protected void sortResults(List<ResolveInfo> results) { 7060 Collections.sort(results, mResolvePrioritySorter); 7061 } 7062 7063 @Override 7064 protected void dumpFilter(PrintWriter out, String prefix, 7065 PackageParser.ActivityIntentInfo filter) { 7066 out.print(prefix); out.print( 7067 Integer.toHexString(System.identityHashCode(filter.activity))); 7068 out.print(' '); 7069 filter.activity.printComponentShortName(out); 7070 out.print(" filter "); 7071 out.println(Integer.toHexString(System.identityHashCode(filter))); 7072 } 7073 7074// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7075// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7076// final List<ResolveInfo> retList = Lists.newArrayList(); 7077// while (i.hasNext()) { 7078// final ResolveInfo resolveInfo = i.next(); 7079// if (isEnabledLP(resolveInfo.activityInfo)) { 7080// retList.add(resolveInfo); 7081// } 7082// } 7083// return retList; 7084// } 7085 7086 // Keys are String (activity class name), values are Activity. 7087 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7088 = new HashMap<ComponentName, PackageParser.Activity>(); 7089 private int mFlags; 7090 } 7091 7092 private final class ServiceIntentResolver 7093 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7094 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7095 boolean defaultOnly, int userId) { 7096 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7097 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7098 } 7099 7100 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7101 int userId) { 7102 if (!sUserManager.exists(userId)) return null; 7103 mFlags = flags; 7104 return super.queryIntent(intent, resolvedType, 7105 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7106 } 7107 7108 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7109 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7110 if (!sUserManager.exists(userId)) return null; 7111 if (packageServices == null) { 7112 return null; 7113 } 7114 mFlags = flags; 7115 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7116 final int N = packageServices.size(); 7117 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7118 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7119 7120 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7121 for (int i = 0; i < N; ++i) { 7122 intentFilters = packageServices.get(i).intents; 7123 if (intentFilters != null && intentFilters.size() > 0) { 7124 PackageParser.ServiceIntentInfo[] array = 7125 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7126 intentFilters.toArray(array); 7127 listCut.add(array); 7128 } 7129 } 7130 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7131 } 7132 7133 public final void addService(PackageParser.Service s) { 7134 mServices.put(s.getComponentName(), s); 7135 if (DEBUG_SHOW_INFO) { 7136 Log.v(TAG, " " 7137 + (s.info.nonLocalizedLabel != null 7138 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7139 Log.v(TAG, " Class=" + s.info.name); 7140 } 7141 final int NI = s.intents.size(); 7142 int j; 7143 for (j=0; j<NI; j++) { 7144 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7145 if (DEBUG_SHOW_INFO) { 7146 Log.v(TAG, " IntentFilter:"); 7147 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7148 } 7149 if (!intent.debugCheck()) { 7150 Log.w(TAG, "==> For Service " + s.info.name); 7151 } 7152 addFilter(intent); 7153 } 7154 } 7155 7156 public final void removeService(PackageParser.Service s) { 7157 mServices.remove(s.getComponentName()); 7158 if (DEBUG_SHOW_INFO) { 7159 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7160 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7161 Log.v(TAG, " Class=" + s.info.name); 7162 } 7163 final int NI = s.intents.size(); 7164 int j; 7165 for (j=0; j<NI; j++) { 7166 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7167 if (DEBUG_SHOW_INFO) { 7168 Log.v(TAG, " IntentFilter:"); 7169 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7170 } 7171 removeFilter(intent); 7172 } 7173 } 7174 7175 @Override 7176 protected boolean allowFilterResult( 7177 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7178 ServiceInfo filterSi = filter.service.info; 7179 for (int i=dest.size()-1; i>=0; i--) { 7180 ServiceInfo destAi = dest.get(i).serviceInfo; 7181 if (destAi.name == filterSi.name 7182 && destAi.packageName == filterSi.packageName) { 7183 return false; 7184 } 7185 } 7186 return true; 7187 } 7188 7189 @Override 7190 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7191 return new PackageParser.ServiceIntentInfo[size]; 7192 } 7193 7194 @Override 7195 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7196 if (!sUserManager.exists(userId)) return true; 7197 PackageParser.Package p = filter.service.owner; 7198 if (p != null) { 7199 PackageSetting ps = (PackageSetting)p.mExtras; 7200 if (ps != null) { 7201 // System apps are never considered stopped for purposes of 7202 // filtering, because there may be no way for the user to 7203 // actually re-launch them. 7204 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7205 && ps.getStopped(userId); 7206 } 7207 } 7208 return false; 7209 } 7210 7211 @Override 7212 protected boolean isPackageForFilter(String packageName, 7213 PackageParser.ServiceIntentInfo info) { 7214 return packageName.equals(info.service.owner.packageName); 7215 } 7216 7217 @Override 7218 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7219 int match, int userId) { 7220 if (!sUserManager.exists(userId)) return null; 7221 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7222 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7223 return null; 7224 } 7225 final PackageParser.Service service = info.service; 7226 if (mSafeMode && (service.info.applicationInfo.flags 7227 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7228 return null; 7229 } 7230 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7231 if (ps == null) { 7232 return null; 7233 } 7234 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7235 ps.readUserState(userId), userId); 7236 if (si == null) { 7237 return null; 7238 } 7239 final ResolveInfo res = new ResolveInfo(); 7240 res.serviceInfo = si; 7241 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7242 res.filter = filter; 7243 } 7244 res.priority = info.getPriority(); 7245 res.preferredOrder = service.owner.mPreferredOrder; 7246 //System.out.println("Result: " + res.activityInfo.className + 7247 // " = " + res.priority); 7248 res.match = match; 7249 res.isDefault = info.hasDefault; 7250 res.labelRes = info.labelRes; 7251 res.nonLocalizedLabel = info.nonLocalizedLabel; 7252 res.icon = info.icon; 7253 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7254 return res; 7255 } 7256 7257 @Override 7258 protected void sortResults(List<ResolveInfo> results) { 7259 Collections.sort(results, mResolvePrioritySorter); 7260 } 7261 7262 @Override 7263 protected void dumpFilter(PrintWriter out, String prefix, 7264 PackageParser.ServiceIntentInfo filter) { 7265 out.print(prefix); out.print( 7266 Integer.toHexString(System.identityHashCode(filter.service))); 7267 out.print(' '); 7268 filter.service.printComponentShortName(out); 7269 out.print(" filter "); 7270 out.println(Integer.toHexString(System.identityHashCode(filter))); 7271 } 7272 7273// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7274// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7275// final List<ResolveInfo> retList = Lists.newArrayList(); 7276// while (i.hasNext()) { 7277// final ResolveInfo resolveInfo = (ResolveInfo) i; 7278// if (isEnabledLP(resolveInfo.serviceInfo)) { 7279// retList.add(resolveInfo); 7280// } 7281// } 7282// return retList; 7283// } 7284 7285 // Keys are String (activity class name), values are Activity. 7286 private final HashMap<ComponentName, PackageParser.Service> mServices 7287 = new HashMap<ComponentName, PackageParser.Service>(); 7288 private int mFlags; 7289 }; 7290 7291 private final class ProviderIntentResolver 7292 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7293 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7294 boolean defaultOnly, int userId) { 7295 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7296 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7297 } 7298 7299 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7300 int userId) { 7301 if (!sUserManager.exists(userId)) 7302 return null; 7303 mFlags = flags; 7304 return super.queryIntent(intent, resolvedType, 7305 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7306 } 7307 7308 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7309 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7310 if (!sUserManager.exists(userId)) 7311 return null; 7312 if (packageProviders == null) { 7313 return null; 7314 } 7315 mFlags = flags; 7316 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7317 final int N = packageProviders.size(); 7318 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7319 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7320 7321 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7322 for (int i = 0; i < N; ++i) { 7323 intentFilters = packageProviders.get(i).intents; 7324 if (intentFilters != null && intentFilters.size() > 0) { 7325 PackageParser.ProviderIntentInfo[] array = 7326 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7327 intentFilters.toArray(array); 7328 listCut.add(array); 7329 } 7330 } 7331 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7332 } 7333 7334 public final void addProvider(PackageParser.Provider p) { 7335 if (mProviders.containsKey(p.getComponentName())) { 7336 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7337 return; 7338 } 7339 7340 mProviders.put(p.getComponentName(), p); 7341 if (DEBUG_SHOW_INFO) { 7342 Log.v(TAG, " " 7343 + (p.info.nonLocalizedLabel != null 7344 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7345 Log.v(TAG, " Class=" + p.info.name); 7346 } 7347 final int NI = p.intents.size(); 7348 int j; 7349 for (j = 0; j < NI; j++) { 7350 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7351 if (DEBUG_SHOW_INFO) { 7352 Log.v(TAG, " IntentFilter:"); 7353 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7354 } 7355 if (!intent.debugCheck()) { 7356 Log.w(TAG, "==> For Provider " + p.info.name); 7357 } 7358 addFilter(intent); 7359 } 7360 } 7361 7362 public final void removeProvider(PackageParser.Provider p) { 7363 mProviders.remove(p.getComponentName()); 7364 if (DEBUG_SHOW_INFO) { 7365 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7366 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7367 Log.v(TAG, " Class=" + p.info.name); 7368 } 7369 final int NI = p.intents.size(); 7370 int j; 7371 for (j = 0; j < NI; j++) { 7372 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7373 if (DEBUG_SHOW_INFO) { 7374 Log.v(TAG, " IntentFilter:"); 7375 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7376 } 7377 removeFilter(intent); 7378 } 7379 } 7380 7381 @Override 7382 protected boolean allowFilterResult( 7383 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7384 ProviderInfo filterPi = filter.provider.info; 7385 for (int i = dest.size() - 1; i >= 0; i--) { 7386 ProviderInfo destPi = dest.get(i).providerInfo; 7387 if (destPi.name == filterPi.name 7388 && destPi.packageName == filterPi.packageName) { 7389 return false; 7390 } 7391 } 7392 return true; 7393 } 7394 7395 @Override 7396 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7397 return new PackageParser.ProviderIntentInfo[size]; 7398 } 7399 7400 @Override 7401 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7402 if (!sUserManager.exists(userId)) 7403 return true; 7404 PackageParser.Package p = filter.provider.owner; 7405 if (p != null) { 7406 PackageSetting ps = (PackageSetting) p.mExtras; 7407 if (ps != null) { 7408 // System apps are never considered stopped for purposes of 7409 // filtering, because there may be no way for the user to 7410 // actually re-launch them. 7411 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7412 && ps.getStopped(userId); 7413 } 7414 } 7415 return false; 7416 } 7417 7418 @Override 7419 protected boolean isPackageForFilter(String packageName, 7420 PackageParser.ProviderIntentInfo info) { 7421 return packageName.equals(info.provider.owner.packageName); 7422 } 7423 7424 @Override 7425 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7426 int match, int userId) { 7427 if (!sUserManager.exists(userId)) 7428 return null; 7429 final PackageParser.ProviderIntentInfo info = filter; 7430 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7431 return null; 7432 } 7433 final PackageParser.Provider provider = info.provider; 7434 if (mSafeMode && (provider.info.applicationInfo.flags 7435 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7436 return null; 7437 } 7438 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7439 if (ps == null) { 7440 return null; 7441 } 7442 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7443 ps.readUserState(userId), userId); 7444 if (pi == null) { 7445 return null; 7446 } 7447 final ResolveInfo res = new ResolveInfo(); 7448 res.providerInfo = pi; 7449 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7450 res.filter = filter; 7451 } 7452 res.priority = info.getPriority(); 7453 res.preferredOrder = provider.owner.mPreferredOrder; 7454 res.match = match; 7455 res.isDefault = info.hasDefault; 7456 res.labelRes = info.labelRes; 7457 res.nonLocalizedLabel = info.nonLocalizedLabel; 7458 res.icon = info.icon; 7459 res.system = isSystemApp(res.providerInfo.applicationInfo); 7460 return res; 7461 } 7462 7463 @Override 7464 protected void sortResults(List<ResolveInfo> results) { 7465 Collections.sort(results, mResolvePrioritySorter); 7466 } 7467 7468 @Override 7469 protected void dumpFilter(PrintWriter out, String prefix, 7470 PackageParser.ProviderIntentInfo filter) { 7471 out.print(prefix); 7472 out.print( 7473 Integer.toHexString(System.identityHashCode(filter.provider))); 7474 out.print(' '); 7475 filter.provider.printComponentShortName(out); 7476 out.print(" filter "); 7477 out.println(Integer.toHexString(System.identityHashCode(filter))); 7478 } 7479 7480 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7481 = new HashMap<ComponentName, PackageParser.Provider>(); 7482 private int mFlags; 7483 }; 7484 7485 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7486 new Comparator<ResolveInfo>() { 7487 public int compare(ResolveInfo r1, ResolveInfo r2) { 7488 int v1 = r1.priority; 7489 int v2 = r2.priority; 7490 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7491 if (v1 != v2) { 7492 return (v1 > v2) ? -1 : 1; 7493 } 7494 v1 = r1.preferredOrder; 7495 v2 = r2.preferredOrder; 7496 if (v1 != v2) { 7497 return (v1 > v2) ? -1 : 1; 7498 } 7499 if (r1.isDefault != r2.isDefault) { 7500 return r1.isDefault ? -1 : 1; 7501 } 7502 v1 = r1.match; 7503 v2 = r2.match; 7504 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7505 if (v1 != v2) { 7506 return (v1 > v2) ? -1 : 1; 7507 } 7508 if (r1.system != r2.system) { 7509 return r1.system ? -1 : 1; 7510 } 7511 return 0; 7512 } 7513 }; 7514 7515 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7516 new Comparator<ProviderInfo>() { 7517 public int compare(ProviderInfo p1, ProviderInfo p2) { 7518 final int v1 = p1.initOrder; 7519 final int v2 = p2.initOrder; 7520 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7521 } 7522 }; 7523 7524 static final void sendPackageBroadcast(String action, String pkg, 7525 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7526 int[] userIds) { 7527 IActivityManager am = ActivityManagerNative.getDefault(); 7528 if (am != null) { 7529 try { 7530 if (userIds == null) { 7531 userIds = am.getRunningUserIds(); 7532 } 7533 for (int id : userIds) { 7534 final Intent intent = new Intent(action, 7535 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7536 if (extras != null) { 7537 intent.putExtras(extras); 7538 } 7539 if (targetPkg != null) { 7540 intent.setPackage(targetPkg); 7541 } 7542 // Modify the UID when posting to other users 7543 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7544 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7545 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7546 intent.putExtra(Intent.EXTRA_UID, uid); 7547 } 7548 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7549 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7550 if (DEBUG_BROADCASTS) { 7551 RuntimeException here = new RuntimeException("here"); 7552 here.fillInStackTrace(); 7553 Slog.d(TAG, "Sending to user " + id + ": " 7554 + intent.toShortString(false, true, false, false) 7555 + " " + intent.getExtras(), here); 7556 } 7557 am.broadcastIntent(null, intent, null, finishedReceiver, 7558 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7559 finishedReceiver != null, false, id); 7560 } 7561 } catch (RemoteException ex) { 7562 } 7563 } 7564 } 7565 7566 /** 7567 * Check if the external storage media is available. This is true if there 7568 * is a mounted external storage medium or if the external storage is 7569 * emulated. 7570 */ 7571 private boolean isExternalMediaAvailable() { 7572 return mMediaMounted || Environment.isExternalStorageEmulated(); 7573 } 7574 7575 @Override 7576 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7577 // writer 7578 synchronized (mPackages) { 7579 if (!isExternalMediaAvailable()) { 7580 // If the external storage is no longer mounted at this point, 7581 // the caller may not have been able to delete all of this 7582 // packages files and can not delete any more. Bail. 7583 return null; 7584 } 7585 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7586 if (lastPackage != null) { 7587 pkgs.remove(lastPackage); 7588 } 7589 if (pkgs.size() > 0) { 7590 return pkgs.get(0); 7591 } 7592 } 7593 return null; 7594 } 7595 7596 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7597 if (false) { 7598 RuntimeException here = new RuntimeException("here"); 7599 here.fillInStackTrace(); 7600 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7601 + " andCode=" + andCode, here); 7602 } 7603 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7604 userId, andCode ? 1 : 0, packageName)); 7605 } 7606 7607 void startCleaningPackages() { 7608 // reader 7609 synchronized (mPackages) { 7610 if (!isExternalMediaAvailable()) { 7611 return; 7612 } 7613 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7614 return; 7615 } 7616 } 7617 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7618 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7619 IActivityManager am = ActivityManagerNative.getDefault(); 7620 if (am != null) { 7621 try { 7622 am.startService(null, intent, null, UserHandle.USER_OWNER); 7623 } catch (RemoteException e) { 7624 } 7625 } 7626 } 7627 7628 private final class AppDirObserver extends FileObserver { 7629 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 7630 super(path, mask); 7631 mRootDir = path; 7632 mIsRom = isrom; 7633 mIsPrivileged = isPrivileged; 7634 } 7635 7636 public void onEvent(int event, String path) { 7637 String removedPackage = null; 7638 int removedAppId = -1; 7639 int[] removedUsers = null; 7640 String addedPackage = null; 7641 int addedAppId = -1; 7642 int[] addedUsers = null; 7643 7644 // TODO post a message to the handler to obtain serial ordering 7645 synchronized (mInstallLock) { 7646 String fullPathStr = null; 7647 File fullPath = null; 7648 if (path != null) { 7649 fullPath = new File(mRootDir, path); 7650 fullPathStr = fullPath.getPath(); 7651 } 7652 7653 if (DEBUG_APP_DIR_OBSERVER) 7654 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 7655 7656 if (!isApkFile(fullPath)) { 7657 if (DEBUG_APP_DIR_OBSERVER) 7658 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 7659 return; 7660 } 7661 7662 // Ignore packages that are being installed or 7663 // have just been installed. 7664 if (ignoreCodePath(fullPathStr)) { 7665 return; 7666 } 7667 PackageParser.Package p = null; 7668 PackageSetting ps = null; 7669 // reader 7670 synchronized (mPackages) { 7671 p = mAppDirs.get(fullPathStr); 7672 if (p != null) { 7673 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 7674 if (ps != null) { 7675 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7676 } else { 7677 removedUsers = sUserManager.getUserIds(); 7678 } 7679 } 7680 addedUsers = sUserManager.getUserIds(); 7681 } 7682 if ((event&REMOVE_EVENTS) != 0) { 7683 if (ps != null) { 7684 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 7685 removePackageLI(ps, true); 7686 removedPackage = ps.name; 7687 removedAppId = ps.appId; 7688 } 7689 } 7690 7691 if ((event&ADD_EVENTS) != 0) { 7692 if (p == null) { 7693 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 7694 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 7695 if (mIsRom) { 7696 flags |= PackageParser.PARSE_IS_SYSTEM 7697 | PackageParser.PARSE_IS_SYSTEM_DIR; 7698 if (mIsPrivileged) { 7699 flags |= PackageParser.PARSE_IS_PRIVILEGED; 7700 } 7701 } 7702 try { 7703 p = scanPackageLI(fullPath, flags, 7704 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 7705 System.currentTimeMillis(), UserHandle.ALL, null); 7706 } catch (PackageManagerException e) { 7707 Slog.w(TAG, "Failed to scan " + fullPath + ": " + e.getMessage()); 7708 p = null; 7709 } 7710 if (p != null) { 7711 /* 7712 * TODO this seems dangerous as the package may have 7713 * changed since we last acquired the mPackages 7714 * lock. 7715 */ 7716 // writer 7717 synchronized (mPackages) { 7718 updatePermissionsLPw(p.packageName, p, 7719 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 7720 } 7721 addedPackage = p.applicationInfo.packageName; 7722 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 7723 } 7724 } 7725 } 7726 7727 // reader 7728 synchronized (mPackages) { 7729 mSettings.writeLPr(); 7730 } 7731 } 7732 7733 if (removedPackage != null) { 7734 Bundle extras = new Bundle(1); 7735 extras.putInt(Intent.EXTRA_UID, removedAppId); 7736 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 7737 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7738 extras, null, null, removedUsers); 7739 } 7740 if (addedPackage != null) { 7741 Bundle extras = new Bundle(1); 7742 extras.putInt(Intent.EXTRA_UID, addedAppId); 7743 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 7744 extras, null, null, addedUsers); 7745 } 7746 } 7747 7748 private final String mRootDir; 7749 private final boolean mIsRom; 7750 private final boolean mIsPrivileged; 7751 } 7752 7753 @Override 7754 public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags, 7755 String installerPackageName, VerificationParams verificationParams, 7756 String packageAbiOverride) { 7757 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7758 null); 7759 7760 final File originFile = new File(originPath); 7761 final int uid = Binder.getCallingUid(); 7762 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7763 try { 7764 if (observer != null) { 7765 observer.packageInstalled("", null, INSTALL_FAILED_USER_RESTRICTED, null); 7766 } 7767 } catch (RemoteException re) { 7768 } 7769 return; 7770 } 7771 7772 UserHandle user; 7773 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7774 user = UserHandle.ALL; 7775 } else { 7776 user = new UserHandle(UserHandle.getUserId(uid)); 7777 } 7778 7779 final int filteredFlags; 7780 if (uid == Process.SHELL_UID || uid == 0) { 7781 if (DEBUG_INSTALL) { 7782 Slog.v(TAG, "Install from ADB"); 7783 } 7784 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7785 } else { 7786 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7787 } 7788 7789 verificationParams.setInstallerUid(uid); 7790 7791 final Message msg = mHandler.obtainMessage(INIT_COPY); 7792 msg.obj = new InstallParams(originFile, false, observer, filteredFlags, 7793 installerPackageName, verificationParams, user, packageAbiOverride); 7794 mHandler.sendMessage(msg); 7795 } 7796 7797 void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer, 7798 InstallSessionParams params, String installerPackageName, int installerUid, 7799 UserHandle user) { 7800 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7801 params.referrerUri, installerUid, null); 7802 7803 final Message msg = mHandler.obtainMessage(INIT_COPY); 7804 msg.obj = new InstallParams(stageDir, true, observer, params.installFlags, 7805 installerPackageName, verifParams, user, params.abiOverride); 7806 mHandler.sendMessage(msg); 7807 } 7808 7809 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7810 Bundle extras = new Bundle(1); 7811 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7812 7813 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7814 packageName, extras, null, null, new int[] {userId}); 7815 try { 7816 IActivityManager am = ActivityManagerNative.getDefault(); 7817 final boolean isSystem = 7818 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7819 if (isSystem && am.isUserRunning(userId, false)) { 7820 // The just-installed/enabled app is bundled on the system, so presumed 7821 // to be able to run automatically without needing an explicit launch. 7822 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7823 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7824 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7825 .setPackage(packageName); 7826 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7827 android.app.AppOpsManager.OP_NONE, false, false, userId); 7828 } 7829 } catch (RemoteException e) { 7830 // shouldn't happen 7831 Slog.w(TAG, "Unable to bootstrap installed package", e); 7832 } 7833 } 7834 7835 @Override 7836 public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked, 7837 int userId) { 7838 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7839 PackageSetting pkgSetting; 7840 final int uid = Binder.getCallingUid(); 7841 if (UserHandle.getUserId(uid) != userId) { 7842 mContext.enforceCallingOrSelfPermission( 7843 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7844 "setApplicationBlockedSetting for user " + userId); 7845 } 7846 7847 if (blocked && isPackageDeviceAdmin(packageName, userId)) { 7848 Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin"); 7849 return false; 7850 } 7851 7852 long callingId = Binder.clearCallingIdentity(); 7853 try { 7854 boolean sendAdded = false; 7855 boolean sendRemoved = false; 7856 // writer 7857 synchronized (mPackages) { 7858 pkgSetting = mSettings.mPackages.get(packageName); 7859 if (pkgSetting == null) { 7860 return false; 7861 } 7862 if (pkgSetting.getBlocked(userId) != blocked) { 7863 pkgSetting.setBlocked(blocked, userId); 7864 mSettings.writePackageRestrictionsLPr(userId); 7865 if (blocked) { 7866 sendRemoved = true; 7867 } else { 7868 sendAdded = true; 7869 } 7870 } 7871 } 7872 if (sendAdded) { 7873 sendPackageAddedForUser(packageName, pkgSetting, userId); 7874 return true; 7875 } 7876 if (sendRemoved) { 7877 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7878 "blocking pkg"); 7879 sendPackageBlockedForUser(packageName, pkgSetting, userId); 7880 } 7881 } finally { 7882 Binder.restoreCallingIdentity(callingId); 7883 } 7884 return false; 7885 } 7886 7887 private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting, 7888 int userId) { 7889 final PackageRemovedInfo info = new PackageRemovedInfo(); 7890 info.removedPackage = packageName; 7891 info.removedUsers = new int[] {userId}; 7892 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7893 info.sendBroadcast(false, false, false); 7894 } 7895 7896 /** 7897 * Returns true if application is not found or there was an error. Otherwise it returns 7898 * the blocked state of the package for the given user. 7899 */ 7900 @Override 7901 public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) { 7902 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7903 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7904 "getApplicationBlocked for user " + userId); 7905 PackageSetting pkgSetting; 7906 long callingId = Binder.clearCallingIdentity(); 7907 try { 7908 // writer 7909 synchronized (mPackages) { 7910 pkgSetting = mSettings.mPackages.get(packageName); 7911 if (pkgSetting == null) { 7912 return true; 7913 } 7914 return pkgSetting.getBlocked(userId); 7915 } 7916 } finally { 7917 Binder.restoreCallingIdentity(callingId); 7918 } 7919 } 7920 7921 /** 7922 * @hide 7923 */ 7924 @Override 7925 public int installExistingPackageAsUser(String packageName, int userId) { 7926 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7927 null); 7928 PackageSetting pkgSetting; 7929 final int uid = Binder.getCallingUid(); 7930 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7931 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7932 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7933 } 7934 7935 long callingId = Binder.clearCallingIdentity(); 7936 try { 7937 boolean sendAdded = false; 7938 Bundle extras = new Bundle(1); 7939 7940 // writer 7941 synchronized (mPackages) { 7942 pkgSetting = mSettings.mPackages.get(packageName); 7943 if (pkgSetting == null) { 7944 return PackageManager.INSTALL_FAILED_INVALID_URI; 7945 } 7946 if (!pkgSetting.getInstalled(userId)) { 7947 pkgSetting.setInstalled(true, userId); 7948 pkgSetting.setBlocked(false, userId); 7949 mSettings.writePackageRestrictionsLPr(userId); 7950 sendAdded = true; 7951 } 7952 } 7953 7954 if (sendAdded) { 7955 sendPackageAddedForUser(packageName, pkgSetting, userId); 7956 } 7957 } finally { 7958 Binder.restoreCallingIdentity(callingId); 7959 } 7960 7961 return PackageManager.INSTALL_SUCCEEDED; 7962 } 7963 7964 boolean isUserRestricted(int userId, String restrictionKey) { 7965 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7966 if (restrictions.getBoolean(restrictionKey, false)) { 7967 Log.w(TAG, "User is restricted: " + restrictionKey); 7968 return true; 7969 } 7970 return false; 7971 } 7972 7973 @Override 7974 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7975 mContext.enforceCallingOrSelfPermission( 7976 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7977 "Only package verification agents can verify applications"); 7978 7979 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7980 final PackageVerificationResponse response = new PackageVerificationResponse( 7981 verificationCode, Binder.getCallingUid()); 7982 msg.arg1 = id; 7983 msg.obj = response; 7984 mHandler.sendMessage(msg); 7985 } 7986 7987 @Override 7988 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7989 long millisecondsToDelay) { 7990 mContext.enforceCallingOrSelfPermission( 7991 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7992 "Only package verification agents can extend verification timeouts"); 7993 7994 final PackageVerificationState state = mPendingVerification.get(id); 7995 final PackageVerificationResponse response = new PackageVerificationResponse( 7996 verificationCodeAtTimeout, Binder.getCallingUid()); 7997 7998 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7999 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8000 } 8001 if (millisecondsToDelay < 0) { 8002 millisecondsToDelay = 0; 8003 } 8004 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8005 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8006 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8007 } 8008 8009 if ((state != null) && !state.timeoutExtended()) { 8010 state.extendTimeout(); 8011 8012 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8013 msg.arg1 = id; 8014 msg.obj = response; 8015 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8016 } 8017 } 8018 8019 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8020 int verificationCode, UserHandle user) { 8021 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8022 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8023 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8024 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8025 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8026 8027 mContext.sendBroadcastAsUser(intent, user, 8028 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8029 } 8030 8031 private ComponentName matchComponentForVerifier(String packageName, 8032 List<ResolveInfo> receivers) { 8033 ActivityInfo targetReceiver = null; 8034 8035 final int NR = receivers.size(); 8036 for (int i = 0; i < NR; i++) { 8037 final ResolveInfo info = receivers.get(i); 8038 if (info.activityInfo == null) { 8039 continue; 8040 } 8041 8042 if (packageName.equals(info.activityInfo.packageName)) { 8043 targetReceiver = info.activityInfo; 8044 break; 8045 } 8046 } 8047 8048 if (targetReceiver == null) { 8049 return null; 8050 } 8051 8052 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8053 } 8054 8055 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8056 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8057 if (pkgInfo.verifiers.length == 0) { 8058 return null; 8059 } 8060 8061 final int N = pkgInfo.verifiers.length; 8062 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8063 for (int i = 0; i < N; i++) { 8064 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8065 8066 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8067 receivers); 8068 if (comp == null) { 8069 continue; 8070 } 8071 8072 final int verifierUid = getUidForVerifier(verifierInfo); 8073 if (verifierUid == -1) { 8074 continue; 8075 } 8076 8077 if (DEBUG_VERIFY) { 8078 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8079 + " with the correct signature"); 8080 } 8081 sufficientVerifiers.add(comp); 8082 verificationState.addSufficientVerifier(verifierUid); 8083 } 8084 8085 return sufficientVerifiers; 8086 } 8087 8088 private int getUidForVerifier(VerifierInfo verifierInfo) { 8089 synchronized (mPackages) { 8090 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8091 if (pkg == null) { 8092 return -1; 8093 } else if (pkg.mSignatures.length != 1) { 8094 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8095 + " has more than one signature; ignoring"); 8096 return -1; 8097 } 8098 8099 /* 8100 * If the public key of the package's signature does not match 8101 * our expected public key, then this is a different package and 8102 * we should skip. 8103 */ 8104 8105 final byte[] expectedPublicKey; 8106 try { 8107 final Signature verifierSig = pkg.mSignatures[0]; 8108 final PublicKey publicKey = verifierSig.getPublicKey(); 8109 expectedPublicKey = publicKey.getEncoded(); 8110 } catch (CertificateException e) { 8111 return -1; 8112 } 8113 8114 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8115 8116 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8117 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8118 + " does not have the expected public key; ignoring"); 8119 return -1; 8120 } 8121 8122 return pkg.applicationInfo.uid; 8123 } 8124 } 8125 8126 @Override 8127 public void finishPackageInstall(int token) { 8128 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8129 8130 if (DEBUG_INSTALL) { 8131 Slog.v(TAG, "BM finishing package install for " + token); 8132 } 8133 8134 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8135 mHandler.sendMessage(msg); 8136 } 8137 8138 /** 8139 * Get the verification agent timeout. 8140 * 8141 * @return verification timeout in milliseconds 8142 */ 8143 private long getVerificationTimeout() { 8144 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8145 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8146 DEFAULT_VERIFICATION_TIMEOUT); 8147 } 8148 8149 /** 8150 * Get the default verification agent response code. 8151 * 8152 * @return default verification response code 8153 */ 8154 private int getDefaultVerificationResponse() { 8155 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8156 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8157 DEFAULT_VERIFICATION_RESPONSE); 8158 } 8159 8160 /** 8161 * Check whether or not package verification has been enabled. 8162 * 8163 * @return true if verification should be performed 8164 */ 8165 private boolean isVerificationEnabled(int userId, int flags) { 8166 if (!DEFAULT_VERIFY_ENABLE) { 8167 return false; 8168 } 8169 8170 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8171 8172 // Check if installing from ADB 8173 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8174 // Do not run verification in a test harness environment 8175 if (ActivityManager.isRunningInTestHarness()) { 8176 return false; 8177 } 8178 if (ensureVerifyAppsEnabled) { 8179 return true; 8180 } 8181 // Check if the developer does not want package verification for ADB installs 8182 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8183 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8184 return false; 8185 } 8186 } 8187 8188 if (ensureVerifyAppsEnabled) { 8189 return true; 8190 } 8191 8192 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8193 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8194 } 8195 8196 /** 8197 * Get the "allow unknown sources" setting. 8198 * 8199 * @return the current "allow unknown sources" setting 8200 */ 8201 private int getUnknownSourcesSettings() { 8202 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8203 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8204 -1); 8205 } 8206 8207 @Override 8208 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8209 final int uid = Binder.getCallingUid(); 8210 // writer 8211 synchronized (mPackages) { 8212 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8213 if (targetPackageSetting == null) { 8214 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8215 } 8216 8217 PackageSetting installerPackageSetting; 8218 if (installerPackageName != null) { 8219 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8220 if (installerPackageSetting == null) { 8221 throw new IllegalArgumentException("Unknown installer package: " 8222 + installerPackageName); 8223 } 8224 } else { 8225 installerPackageSetting = null; 8226 } 8227 8228 Signature[] callerSignature; 8229 Object obj = mSettings.getUserIdLPr(uid); 8230 if (obj != null) { 8231 if (obj instanceof SharedUserSetting) { 8232 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8233 } else if (obj instanceof PackageSetting) { 8234 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8235 } else { 8236 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8237 } 8238 } else { 8239 throw new SecurityException("Unknown calling uid " + uid); 8240 } 8241 8242 // Verify: can't set installerPackageName to a package that is 8243 // not signed with the same cert as the caller. 8244 if (installerPackageSetting != null) { 8245 if (compareSignatures(callerSignature, 8246 installerPackageSetting.signatures.mSignatures) 8247 != PackageManager.SIGNATURE_MATCH) { 8248 throw new SecurityException( 8249 "Caller does not have same cert as new installer package " 8250 + installerPackageName); 8251 } 8252 } 8253 8254 // Verify: if target already has an installer package, it must 8255 // be signed with the same cert as the caller. 8256 if (targetPackageSetting.installerPackageName != null) { 8257 PackageSetting setting = mSettings.mPackages.get( 8258 targetPackageSetting.installerPackageName); 8259 // If the currently set package isn't valid, then it's always 8260 // okay to change it. 8261 if (setting != null) { 8262 if (compareSignatures(callerSignature, 8263 setting.signatures.mSignatures) 8264 != PackageManager.SIGNATURE_MATCH) { 8265 throw new SecurityException( 8266 "Caller does not have same cert as old installer package " 8267 + targetPackageSetting.installerPackageName); 8268 } 8269 } 8270 } 8271 8272 // Okay! 8273 targetPackageSetting.installerPackageName = installerPackageName; 8274 scheduleWriteSettingsLocked(); 8275 } 8276 } 8277 8278 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8279 // Queue up an async operation since the package installation may take a little while. 8280 mHandler.post(new Runnable() { 8281 public void run() { 8282 mHandler.removeCallbacks(this); 8283 // Result object to be returned 8284 PackageInstalledInfo res = new PackageInstalledInfo(); 8285 res.returnCode = currentStatus; 8286 res.uid = -1; 8287 res.pkg = null; 8288 res.removedInfo = new PackageRemovedInfo(); 8289 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8290 args.doPreInstall(res.returnCode); 8291 synchronized (mInstallLock) { 8292 installPackageLI(args, true, res); 8293 } 8294 args.doPostInstall(res.returnCode, res.uid); 8295 } 8296 8297 // A restore should be performed at this point if (a) the install 8298 // succeeded, (b) the operation is not an update, and (c) the new 8299 // package has a backupAgent defined. 8300 final boolean update = res.removedInfo.removedPackage != null; 8301 boolean doRestore = (!update 8302 && res.pkg != null 8303 && res.pkg.applicationInfo.backupAgentName != null); 8304 8305 // Set up the post-install work request bookkeeping. This will be used 8306 // and cleaned up by the post-install event handling regardless of whether 8307 // there's a restore pass performed. Token values are >= 1. 8308 int token; 8309 if (mNextInstallToken < 0) mNextInstallToken = 1; 8310 token = mNextInstallToken++; 8311 8312 PostInstallData data = new PostInstallData(args, res); 8313 mRunningInstalls.put(token, data); 8314 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8315 8316 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8317 // Pass responsibility to the Backup Manager. It will perform a 8318 // restore if appropriate, then pass responsibility back to the 8319 // Package Manager to run the post-install observer callbacks 8320 // and broadcasts. 8321 IBackupManager bm = IBackupManager.Stub.asInterface( 8322 ServiceManager.getService(Context.BACKUP_SERVICE)); 8323 if (bm != null) { 8324 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8325 + " to BM for possible restore"); 8326 try { 8327 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8328 } catch (RemoteException e) { 8329 // can't happen; the backup manager is local 8330 } catch (Exception e) { 8331 Slog.e(TAG, "Exception trying to enqueue restore", e); 8332 doRestore = false; 8333 } 8334 } else { 8335 Slog.e(TAG, "Backup Manager not found!"); 8336 doRestore = false; 8337 } 8338 } 8339 8340 if (!doRestore) { 8341 // No restore possible, or the Backup Manager was mysteriously not 8342 // available -- just fire the post-install work request directly. 8343 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8344 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8345 mHandler.sendMessage(msg); 8346 } 8347 } 8348 }); 8349 } 8350 8351 private abstract class HandlerParams { 8352 private static final int MAX_RETRIES = 4; 8353 8354 /** 8355 * Number of times startCopy() has been attempted and had a non-fatal 8356 * error. 8357 */ 8358 private int mRetries = 0; 8359 8360 /** User handle for the user requesting the information or installation. */ 8361 private final UserHandle mUser; 8362 8363 HandlerParams(UserHandle user) { 8364 mUser = user; 8365 } 8366 8367 UserHandle getUser() { 8368 return mUser; 8369 } 8370 8371 final boolean startCopy() { 8372 boolean res; 8373 try { 8374 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8375 8376 if (++mRetries > MAX_RETRIES) { 8377 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8378 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8379 handleServiceError(); 8380 return false; 8381 } else { 8382 handleStartCopy(); 8383 res = true; 8384 } 8385 } catch (RemoteException e) { 8386 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8387 mHandler.sendEmptyMessage(MCS_RECONNECT); 8388 res = false; 8389 } 8390 handleReturnCode(); 8391 return res; 8392 } 8393 8394 final void serviceError() { 8395 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8396 handleServiceError(); 8397 handleReturnCode(); 8398 } 8399 8400 abstract void handleStartCopy() throws RemoteException; 8401 abstract void handleServiceError(); 8402 abstract void handleReturnCode(); 8403 } 8404 8405 class MeasureParams extends HandlerParams { 8406 private final PackageStats mStats; 8407 private boolean mSuccess; 8408 8409 private final IPackageStatsObserver mObserver; 8410 8411 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8412 super(new UserHandle(stats.userHandle)); 8413 mObserver = observer; 8414 mStats = stats; 8415 } 8416 8417 @Override 8418 public String toString() { 8419 return "MeasureParams{" 8420 + Integer.toHexString(System.identityHashCode(this)) 8421 + " " + mStats.packageName + "}"; 8422 } 8423 8424 @Override 8425 void handleStartCopy() throws RemoteException { 8426 synchronized (mInstallLock) { 8427 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8428 } 8429 8430 if (mSuccess) { 8431 final boolean mounted; 8432 if (Environment.isExternalStorageEmulated()) { 8433 mounted = true; 8434 } else { 8435 final String status = Environment.getExternalStorageState(); 8436 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8437 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8438 } 8439 8440 if (mounted) { 8441 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8442 8443 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8444 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8445 8446 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8447 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8448 8449 // Always subtract cache size, since it's a subdirectory 8450 mStats.externalDataSize -= mStats.externalCacheSize; 8451 8452 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8453 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8454 8455 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8456 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8457 } 8458 } 8459 } 8460 8461 @Override 8462 void handleReturnCode() { 8463 if (mObserver != null) { 8464 try { 8465 mObserver.onGetStatsCompleted(mStats, mSuccess); 8466 } catch (RemoteException e) { 8467 Slog.i(TAG, "Observer no longer exists."); 8468 } 8469 } 8470 } 8471 8472 @Override 8473 void handleServiceError() { 8474 Slog.e(TAG, "Could not measure application " + mStats.packageName 8475 + " external storage"); 8476 } 8477 } 8478 8479 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8480 throws RemoteException { 8481 long result = 0; 8482 for (File path : paths) { 8483 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8484 } 8485 return result; 8486 } 8487 8488 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8489 for (File path : paths) { 8490 try { 8491 mcs.clearDirectory(path.getAbsolutePath()); 8492 } catch (RemoteException e) { 8493 } 8494 } 8495 } 8496 8497 class InstallParams extends HandlerParams { 8498 /** 8499 * Location where install is coming from, before it has been 8500 * copied/renamed into place. This could be a single monolithic APK 8501 * file, or a cluster directory. This location may be untrusted. 8502 */ 8503 final File originFile; 8504 8505 /** 8506 * Flag indicating that {@link #originFile} has already been staged, 8507 * meaning downstream users don't need to defensively copy the contents. 8508 */ 8509 boolean originStaged; 8510 8511 final IPackageInstallObserver2 observer; 8512 int flags; 8513 final String installerPackageName; 8514 final VerificationParams verificationParams; 8515 private InstallArgs mArgs; 8516 private int mRet; 8517 final String packageAbiOverride; 8518 boolean multiArch; 8519 8520 InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 8521 int flags, String installerPackageName, VerificationParams verificationParams, 8522 UserHandle user, String packageAbiOverride) { 8523 super(user); 8524 this.originFile = Preconditions.checkNotNull(originFile); 8525 this.originStaged = originStaged; 8526 this.observer = observer; 8527 this.flags = flags; 8528 this.installerPackageName = installerPackageName; 8529 this.verificationParams = verificationParams; 8530 this.packageAbiOverride = packageAbiOverride; 8531 } 8532 8533 @Override 8534 public String toString() { 8535 return "InstallParams{" 8536 + Integer.toHexString(System.identityHashCode(this)) 8537 + " " + originFile + "}"; 8538 } 8539 8540 public ManifestDigest getManifestDigest() { 8541 if (verificationParams == null) { 8542 return null; 8543 } 8544 return verificationParams.getManifestDigest(); 8545 } 8546 8547 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8548 String packageName = pkgLite.packageName; 8549 int installLocation = pkgLite.installLocation; 8550 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8551 // reader 8552 synchronized (mPackages) { 8553 PackageParser.Package pkg = mPackages.get(packageName); 8554 if (pkg != null) { 8555 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8556 // Check for downgrading. 8557 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8558 if (pkgLite.versionCode < pkg.mVersionCode) { 8559 Slog.w(TAG, "Can't install update of " + packageName 8560 + " update version " + pkgLite.versionCode 8561 + " is older than installed version " 8562 + pkg.mVersionCode); 8563 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8564 } 8565 } 8566 // Check for updated system application. 8567 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8568 if (onSd) { 8569 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8570 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8571 } 8572 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8573 } else { 8574 if (onSd) { 8575 // Install flag overrides everything. 8576 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8577 } 8578 // If current upgrade specifies particular preference 8579 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8580 // Application explicitly specified internal. 8581 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8582 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8583 // App explictly prefers external. Let policy decide 8584 } else { 8585 // Prefer previous location 8586 if (isExternal(pkg)) { 8587 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8588 } 8589 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8590 } 8591 } 8592 } else { 8593 // Invalid install. Return error code 8594 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8595 } 8596 } 8597 } 8598 // All the special cases have been taken care of. 8599 // Return result based on recommended install location. 8600 if (onSd) { 8601 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8602 } 8603 return pkgLite.recommendedInstallLocation; 8604 } 8605 8606 private long getMemoryLowThreshold() { 8607 final DeviceStorageMonitorInternal 8608 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8609 if (dsm == null) { 8610 return 0L; 8611 } 8612 return dsm.getMemoryLowThreshold(); 8613 } 8614 8615 /* 8616 * Invoke remote method to get package information and install 8617 * location values. Override install location based on default 8618 * policy if needed and then create install arguments based 8619 * on the install location. 8620 */ 8621 public void handleStartCopy() throws RemoteException { 8622 int ret = PackageManager.INSTALL_SUCCEEDED; 8623 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8624 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8625 PackageInfoLite pkgLite = null; 8626 8627 if (onInt && onSd) { 8628 // Check if both bits are set. 8629 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8630 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8631 } else { 8632 final long lowThreshold = getMemoryLowThreshold(); 8633 if (lowThreshold == 0L) { 8634 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8635 } 8636 8637 // Remote call to find out default install location 8638 final String originPath = originFile.getAbsolutePath(); 8639 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold, 8640 packageAbiOverride); 8641 // Keep track of whether this package is a multiArch package until 8642 // we perform a full scan of it. We need to do this because we might 8643 // end up extracting the package shared libraries before we perform 8644 // a full scan. 8645 multiArch = pkgLite.multiArch; 8646 8647 /* 8648 * If we have too little free space, try to free cache 8649 * before giving up. 8650 */ 8651 if (pkgLite.recommendedInstallLocation 8652 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8653 final long size = mContainerService.calculateInstalledSize( 8654 originPath, isForwardLocked(), packageAbiOverride); 8655 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8656 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, 8657 lowThreshold, packageAbiOverride); 8658 } 8659 /* 8660 * The cache free must have deleted the file we 8661 * downloaded to install. 8662 * 8663 * TODO: fix the "freeCache" call to not delete 8664 * the file we care about. 8665 */ 8666 if (pkgLite.recommendedInstallLocation 8667 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8668 pkgLite.recommendedInstallLocation 8669 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8670 } 8671 } 8672 } 8673 8674 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8675 int loc = pkgLite.recommendedInstallLocation; 8676 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8677 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8678 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8679 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8680 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8681 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8682 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8683 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8684 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8685 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8686 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8687 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8688 } else { 8689 // Override with defaults if needed. 8690 loc = installLocationPolicy(pkgLite, flags); 8691 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8692 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8693 } else if (!onSd && !onInt) { 8694 // Override install location with flags 8695 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8696 // Set the flag to install on external media. 8697 flags |= PackageManager.INSTALL_EXTERNAL; 8698 flags &= ~PackageManager.INSTALL_INTERNAL; 8699 } else { 8700 // Make sure the flag for installing on external 8701 // media is unset 8702 flags |= PackageManager.INSTALL_INTERNAL; 8703 flags &= ~PackageManager.INSTALL_EXTERNAL; 8704 } 8705 } 8706 } 8707 } 8708 8709 final InstallArgs args = createInstallArgs(this); 8710 mArgs = args; 8711 8712 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8713 /* 8714 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8715 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8716 */ 8717 int userIdentifier = getUser().getIdentifier(); 8718 if (userIdentifier == UserHandle.USER_ALL 8719 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8720 userIdentifier = UserHandle.USER_OWNER; 8721 } 8722 8723 /* 8724 * Determine if we have any installed package verifiers. If we 8725 * do, then we'll defer to them to verify the packages. 8726 */ 8727 final int requiredUid = mRequiredVerifierPackage == null ? -1 8728 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8729 if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) { 8730 // TODO: send verifier the install session instead of uri 8731 final Intent verification = new Intent( 8732 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8733 verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE); 8734 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8735 8736 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8737 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8738 0 /* TODO: Which userId? */); 8739 8740 if (DEBUG_VERIFY) { 8741 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8742 + verification.toString() + " with " + pkgLite.verifiers.length 8743 + " optional verifiers"); 8744 } 8745 8746 final int verificationId = mPendingVerificationToken++; 8747 8748 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8749 8750 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8751 installerPackageName); 8752 8753 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8754 8755 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8756 pkgLite.packageName); 8757 8758 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8759 pkgLite.versionCode); 8760 8761 if (verificationParams != null) { 8762 if (verificationParams.getVerificationURI() != null) { 8763 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8764 verificationParams.getVerificationURI()); 8765 } 8766 if (verificationParams.getOriginatingURI() != null) { 8767 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8768 verificationParams.getOriginatingURI()); 8769 } 8770 if (verificationParams.getReferrer() != null) { 8771 verification.putExtra(Intent.EXTRA_REFERRER, 8772 verificationParams.getReferrer()); 8773 } 8774 if (verificationParams.getOriginatingUid() >= 0) { 8775 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8776 verificationParams.getOriginatingUid()); 8777 } 8778 if (verificationParams.getInstallerUid() >= 0) { 8779 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8780 verificationParams.getInstallerUid()); 8781 } 8782 } 8783 8784 final PackageVerificationState verificationState = new PackageVerificationState( 8785 requiredUid, args); 8786 8787 mPendingVerification.append(verificationId, verificationState); 8788 8789 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8790 receivers, verificationState); 8791 8792 /* 8793 * If any sufficient verifiers were listed in the package 8794 * manifest, attempt to ask them. 8795 */ 8796 if (sufficientVerifiers != null) { 8797 final int N = sufficientVerifiers.size(); 8798 if (N == 0) { 8799 Slog.i(TAG, "Additional verifiers required, but none installed."); 8800 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8801 } else { 8802 for (int i = 0; i < N; i++) { 8803 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8804 8805 final Intent sufficientIntent = new Intent(verification); 8806 sufficientIntent.setComponent(verifierComponent); 8807 8808 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8809 } 8810 } 8811 } 8812 8813 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8814 mRequiredVerifierPackage, receivers); 8815 if (ret == PackageManager.INSTALL_SUCCEEDED 8816 && mRequiredVerifierPackage != null) { 8817 /* 8818 * Send the intent to the required verification agent, 8819 * but only start the verification timeout after the 8820 * target BroadcastReceivers have run. 8821 */ 8822 verification.setComponent(requiredVerifierComponent); 8823 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8824 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8825 new BroadcastReceiver() { 8826 @Override 8827 public void onReceive(Context context, Intent intent) { 8828 final Message msg = mHandler 8829 .obtainMessage(CHECK_PENDING_VERIFICATION); 8830 msg.arg1 = verificationId; 8831 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8832 } 8833 }, null, 0, null, null); 8834 8835 /* 8836 * We don't want the copy to proceed until verification 8837 * succeeds, so null out this field. 8838 */ 8839 mArgs = null; 8840 } 8841 } else { 8842 /* 8843 * No package verification is enabled, so immediately start 8844 * the remote call to initiate copy using temporary file. 8845 */ 8846 ret = args.copyApk(mContainerService, true); 8847 } 8848 } 8849 8850 mRet = ret; 8851 } 8852 8853 @Override 8854 void handleReturnCode() { 8855 // If mArgs is null, then MCS couldn't be reached. When it 8856 // reconnects, it will try again to install. At that point, this 8857 // will succeed. 8858 if (mArgs != null) { 8859 processPendingInstall(mArgs, mRet); 8860 } 8861 } 8862 8863 @Override 8864 void handleServiceError() { 8865 mArgs = createInstallArgs(this); 8866 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8867 } 8868 8869 public boolean isForwardLocked() { 8870 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8871 } 8872 } 8873 8874 /* 8875 * Utility class used in movePackage api. 8876 * srcArgs and targetArgs are not set for invalid flags and make 8877 * sure to do null checks when invoking methods on them. 8878 * We probably want to return ErrorPrams for both failed installs 8879 * and moves. 8880 */ 8881 class MoveParams extends HandlerParams { 8882 final IPackageMoveObserver observer; 8883 final int flags; 8884 final String packageName; 8885 final InstallArgs srcArgs; 8886 final InstallArgs targetArgs; 8887 int uid; 8888 int mRet; 8889 8890 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8891 String packageName, String[] instructionSets, int uid, UserHandle user, 8892 boolean isMultiArch) { 8893 super(user); 8894 this.srcArgs = srcArgs; 8895 this.observer = observer; 8896 this.flags = flags; 8897 this.packageName = packageName; 8898 this.uid = uid; 8899 if (srcArgs != null) { 8900 final String codePath = srcArgs.getCodePath(); 8901 targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, 8902 instructionSets, isMultiArch); 8903 } else { 8904 targetArgs = null; 8905 } 8906 } 8907 8908 @Override 8909 public String toString() { 8910 return "MoveParams{" 8911 + Integer.toHexString(System.identityHashCode(this)) 8912 + " " + packageName + "}"; 8913 } 8914 8915 public void handleStartCopy() throws RemoteException { 8916 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8917 // Check for storage space on target medium 8918 if (!targetArgs.checkFreeStorage(mContainerService)) { 8919 Log.w(TAG, "Insufficient storage to install"); 8920 return; 8921 } 8922 8923 mRet = srcArgs.doPreCopy(); 8924 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8925 return; 8926 } 8927 8928 mRet = targetArgs.copyApk(mContainerService, false); 8929 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8930 srcArgs.doPostCopy(uid); 8931 return; 8932 } 8933 8934 mRet = srcArgs.doPostCopy(uid); 8935 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8936 return; 8937 } 8938 8939 mRet = targetArgs.doPreInstall(mRet); 8940 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8941 return; 8942 } 8943 8944 if (DEBUG_SD_INSTALL) { 8945 StringBuilder builder = new StringBuilder(); 8946 if (srcArgs != null) { 8947 builder.append("src: "); 8948 builder.append(srcArgs.getCodePath()); 8949 } 8950 if (targetArgs != null) { 8951 builder.append(" target : "); 8952 builder.append(targetArgs.getCodePath()); 8953 } 8954 Log.i(TAG, builder.toString()); 8955 } 8956 } 8957 8958 @Override 8959 void handleReturnCode() { 8960 targetArgs.doPostInstall(mRet, uid); 8961 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8962 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8963 currentStatus = PackageManager.MOVE_SUCCEEDED; 8964 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8965 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8966 } 8967 processPendingMove(this, currentStatus); 8968 } 8969 8970 @Override 8971 void handleServiceError() { 8972 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8973 } 8974 } 8975 8976 /** 8977 * Used during creation of InstallArgs 8978 * 8979 * @param flags package installation flags 8980 * @return true if should be installed on external storage 8981 */ 8982 private static boolean installOnSd(int flags) { 8983 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8984 return false; 8985 } 8986 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8987 return true; 8988 } 8989 return false; 8990 } 8991 8992 /** 8993 * Used during creation of InstallArgs 8994 * 8995 * @param flags package installation flags 8996 * @return true if should be installed as forward locked 8997 */ 8998 private static boolean installForwardLocked(int flags) { 8999 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9000 } 9001 9002 private InstallArgs createInstallArgs(InstallParams params) { 9003 // TODO: extend to support incoming zero-copy locations 9004 9005 if (installOnSd(params.flags) || params.isForwardLocked()) { 9006 return new AsecInstallArgs(params); 9007 } else { 9008 return new FileInstallArgs(params); 9009 } 9010 } 9011 9012 /** 9013 * Create args that describe an existing installed package. Typically used 9014 * when cleaning up old installs, or used as a move source. 9015 */ 9016 private InstallArgs createInstallArgsForExisting(int flags, String codePath, 9017 String resourcePath, String nativeLibraryRoot, String[] instructionSets, 9018 boolean isMultiArch) { 9019 final boolean isInAsec; 9020 if (installOnSd(flags)) { 9021 /* Apps on SD card are always in ASEC containers. */ 9022 isInAsec = true; 9023 } else if (installForwardLocked(flags) 9024 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9025 /* 9026 * Forward-locked apps are only in ASEC containers if they're the 9027 * new style 9028 */ 9029 isInAsec = true; 9030 } else { 9031 isInAsec = false; 9032 } 9033 9034 if (isInAsec) { 9035 return new AsecInstallArgs(codePath, instructionSets, 9036 installOnSd(flags), installForwardLocked(flags), isMultiArch); 9037 } else { 9038 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9039 instructionSets, isMultiArch); 9040 } 9041 } 9042 9043 private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName, 9044 String[] instructionSets, boolean isMultiArch) { 9045 final File codeFile = new File(codePath); 9046 if (installOnSd(flags) || installForwardLocked(flags)) { 9047 String cid = getNextCodePath(codePath, pkgName, "/" 9048 + AsecInstallArgs.RES_FILE_NAME); 9049 return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags), 9050 installForwardLocked(flags), isMultiArch); 9051 } else { 9052 return new FileInstallArgs(codeFile, instructionSets, isMultiArch); 9053 } 9054 } 9055 9056 static abstract class InstallArgs { 9057 /** @see InstallParams#originFile */ 9058 final File originFile; 9059 /** @see InstallParams#originStaged */ 9060 final boolean originStaged; 9061 9062 // TODO: define inherit location 9063 9064 final IPackageInstallObserver2 observer; 9065 // Always refers to PackageManager flags only 9066 final int flags; 9067 final String installerPackageName; 9068 final ManifestDigest manifestDigest; 9069 final UserHandle user; 9070 final String abiOverride; 9071 final boolean multiArch; 9072 9073 // The list of instruction sets supported by this app. This is currently 9074 // only used during the rmdex() phase to clean up resources. We can get rid of this 9075 // if we move dex files under the common app path. 9076 /* nullable */ String[] instructionSets; 9077 9078 InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 9079 int flags, String installerPackageName, ManifestDigest manifestDigest, 9080 UserHandle user, String[] instructionSets, 9081 String abiOverride, boolean multiArch) { 9082 this.originFile = originFile; 9083 this.originStaged = originStaged; 9084 this.flags = flags; 9085 this.observer = observer; 9086 this.installerPackageName = installerPackageName; 9087 this.manifestDigest = manifestDigest; 9088 this.user = user; 9089 this.instructionSets = instructionSets; 9090 this.abiOverride = abiOverride; 9091 this.multiArch = multiArch; 9092 } 9093 9094 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9095 abstract int doPreInstall(int status); 9096 9097 /** 9098 * Rename package into final resting place. All paths on the given 9099 * scanned package should be updated to reflect the rename. 9100 */ 9101 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9102 abstract int doPostInstall(int status, int uid); 9103 9104 /** @see PackageSettingBase#codePathString */ 9105 abstract String getCodePath(); 9106 /** @see PackageSettingBase#resourcePathString */ 9107 abstract String getResourcePath(); 9108 abstract String getLegacyNativeLibraryPath(); 9109 9110 // Need installer lock especially for dex file removal. 9111 abstract void cleanUpResourcesLI(); 9112 abstract boolean doPostDeleteLI(boolean delete); 9113 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9114 9115 /** 9116 * Called before the source arguments are copied. This is used mostly 9117 * for MoveParams when it needs to read the source file to put it in the 9118 * destination. 9119 */ 9120 int doPreCopy() { 9121 return PackageManager.INSTALL_SUCCEEDED; 9122 } 9123 9124 /** 9125 * Called after the source arguments are copied. This is used mostly for 9126 * MoveParams when it needs to read the source file to put it in the 9127 * destination. 9128 * 9129 * @return 9130 */ 9131 int doPostCopy(int uid) { 9132 return PackageManager.INSTALL_SUCCEEDED; 9133 } 9134 9135 protected boolean isFwdLocked() { 9136 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9137 } 9138 9139 UserHandle getUser() { 9140 return user; 9141 } 9142 } 9143 9144 /** 9145 * Logic to handle installation of non-ASEC applications, including copying 9146 * and renaming logic. 9147 */ 9148 class FileInstallArgs extends InstallArgs { 9149 private File codeFile; 9150 private File resourceFile; 9151 private File legacyNativeLibraryPath; 9152 9153 // Example topology: 9154 // /data/app/com.example/base.apk 9155 // /data/app/com.example/split_foo.apk 9156 // /data/app/com.example/lib/arm/libfoo.so 9157 // /data/app/com.example/lib/arm64/libfoo.so 9158 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9159 9160 /** New install */ 9161 FileInstallArgs(InstallParams params) { 9162 super(params.originFile, params.originStaged, params.observer, params.flags, 9163 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9164 null /* instruction sets */, params.packageAbiOverride, 9165 params.multiArch); 9166 if (isFwdLocked()) { 9167 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9168 } 9169 } 9170 9171 /** Existing install */ 9172 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9173 String[] instructionSets, boolean isMultiArch) { 9174 super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch); 9175 this.codeFile = (codePath != null) ? new File(codePath) : null; 9176 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9177 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9178 new File(legacyNativeLibraryPath) : null; 9179 } 9180 9181 /** New install from existing */ 9182 FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) { 9183 super(originFile, false, null, 0, null, null, null, instructionSets, null, 9184 isMultiArch); 9185 } 9186 9187 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9188 final long lowThreshold; 9189 9190 final DeviceStorageMonitorInternal 9191 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9192 if (dsm == null) { 9193 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9194 lowThreshold = 0L; 9195 } else { 9196 if (dsm.isMemoryLow()) { 9197 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9198 return false; 9199 } 9200 9201 lowThreshold = dsm.getMemoryLowThreshold(); 9202 } 9203 9204 return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9205 lowThreshold); 9206 } 9207 9208 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9209 int ret = PackageManager.INSTALL_SUCCEEDED; 9210 9211 if (originStaged) { 9212 Slog.d(TAG, originFile + " already staged; skipping copy"); 9213 codeFile = originFile; 9214 resourceFile = originFile; 9215 } else { 9216 try { 9217 final File tempDir = mInstallerService.allocateSessionDir(); 9218 codeFile = tempDir; 9219 resourceFile = tempDir; 9220 } catch (IOException e) { 9221 Slog.w(TAG, "Failed to create copy file: " + e); 9222 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9223 } 9224 9225 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9226 @Override 9227 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9228 if (!FileUtils.isValidExtFilename(name)) { 9229 throw new IllegalArgumentException("Invalid filename: " + name); 9230 } 9231 try { 9232 final File file = new File(codeFile, name); 9233 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9234 O_RDWR | O_CREAT, 0644); 9235 Os.chmod(file.getAbsolutePath(), 0644); 9236 return new ParcelFileDescriptor(fd); 9237 } catch (ErrnoException e) { 9238 throw new RemoteException("Failed to open: " + e.getMessage()); 9239 } 9240 } 9241 }; 9242 9243 ret = imcs.copyPackage(originFile.getAbsolutePath(), target); 9244 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9245 Slog.e(TAG, "Failed to copy package"); 9246 return ret; 9247 } 9248 } 9249 9250 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9251 NativeLibraryHelper.Handle handle = null; 9252 try { 9253 handle = NativeLibraryHelper.Handle.create(codeFile); 9254 if (multiArch) { 9255 // Warn if we've set an abiOverride for multi-lib packages.. 9256 // By definition, we need to copy both 32 and 64 bit libraries for 9257 // such packages. 9258 if (abiOverride != null) { 9259 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9260 } 9261 9262 int copyRet = PackageManager.NO_NATIVE_LIBRARIES; 9263 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9264 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9265 Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */); 9266 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9267 Slog.w(TAG, "Failure copying 32 bit native libraries [errorCode=" + copyRet + "]"); 9268 return copyRet; 9269 } 9270 } 9271 9272 if (DEBUG_ABI_SELECTION && copyRet >= 0) { 9273 Log.d(TAG, "Installed 32 bit libraries under: " + codeFile + " abi=" + 9274 Build.SUPPORTED_32_BIT_ABIS[copyRet]); 9275 } 9276 9277 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9278 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9279 Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */); 9280 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9281 Slog.w(TAG, "Failure copying 64 bit native libraries [errorCode=" + copyRet + "]"); 9282 return copyRet; 9283 } 9284 } 9285 9286 if (DEBUG_ABI_SELECTION && copyRet >= 0) { 9287 Log.d(TAG, "Installed 64 bit libraries under: " + codeFile + " abi=" + 9288 Build.SUPPORTED_64_BIT_ABIS[copyRet]); 9289 } 9290 } else { 9291 String[] abiList = (abiOverride != null) ? 9292 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 9293 9294 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null && 9295 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9296 abiList = Build.SUPPORTED_32_BIT_ABIS; 9297 } 9298 9299 int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList, 9300 true /* use isa specific subdirs */); 9301 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9302 Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]"); 9303 return copyRet; 9304 } 9305 9306 if (DEBUG_ABI_SELECTION && copyRet >= 0) { 9307 Log.d(TAG, "Installed libraries under: " + codeFile + " abi=" + abiList[copyRet]); 9308 } 9309 } 9310 } catch (IOException e) { 9311 Slog.e(TAG, "Copying native libraries failed", e); 9312 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9313 } finally { 9314 IoUtils.closeQuietly(handle); 9315 } 9316 9317 return ret; 9318 } 9319 9320 int doPreInstall(int status) { 9321 if (status != PackageManager.INSTALL_SUCCEEDED) { 9322 cleanUp(); 9323 } 9324 return status; 9325 } 9326 9327 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9328 if (status != PackageManager.INSTALL_SUCCEEDED) { 9329 cleanUp(); 9330 return false; 9331 } else { 9332 final File beforeCodeFile = codeFile; 9333 final File afterCodeFile = new File(mAppInstallDir, 9334 getNextCodePath(oldCodePath, pkg.packageName, null)); 9335 9336 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9337 if (!beforeCodeFile.renameTo(afterCodeFile)) { 9338 return false; 9339 } 9340 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9341 return false; 9342 } 9343 9344 // Reflect the rename internally 9345 codeFile = afterCodeFile; 9346 resourceFile = afterCodeFile; 9347 9348 // Reflect the rename in scanned details 9349 pkg.codePath = afterCodeFile.getAbsolutePath(); 9350 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9351 pkg.baseCodePath); 9352 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9353 pkg.splitCodePaths); 9354 9355 // Reflect the rename in app info 9356 pkg.applicationInfo.setCodePath(pkg.codePath); 9357 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9358 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9359 pkg.applicationInfo.setResourcePath(pkg.codePath); 9360 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9361 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9362 9363 return true; 9364 } 9365 } 9366 9367 int doPostInstall(int status, int uid) { 9368 if (status != PackageManager.INSTALL_SUCCEEDED) { 9369 cleanUp(); 9370 } 9371 return status; 9372 } 9373 9374 @Override 9375 String getCodePath() { 9376 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9377 } 9378 9379 @Override 9380 String getResourcePath() { 9381 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9382 } 9383 9384 @Override 9385 String getLegacyNativeLibraryPath() { 9386 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9387 } 9388 9389 private boolean cleanUp() { 9390 if (codeFile == null || !codeFile.exists()) { 9391 return false; 9392 } 9393 9394 if (codeFile.isDirectory()) { 9395 FileUtils.deleteContents(codeFile); 9396 } 9397 codeFile.delete(); 9398 9399 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9400 resourceFile.delete(); 9401 } 9402 9403 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9404 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9405 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9406 } 9407 legacyNativeLibraryPath.delete(); 9408 } 9409 9410 return true; 9411 } 9412 9413 void cleanUpResourcesLI() { 9414 // Try enumerating all code paths before deleting 9415 List<String> allCodePaths = Collections.EMPTY_LIST; 9416 if (codeFile != null && codeFile.exists()) { 9417 try { 9418 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9419 allCodePaths = pkg.getAllCodePaths(); 9420 } catch (PackageParserException e) { 9421 // Ignored; we tried our best 9422 } 9423 } 9424 9425 cleanUp(); 9426 9427 if (!allCodePaths.isEmpty()) { 9428 if (instructionSets == null) { 9429 throw new IllegalStateException("instructionSet == null"); 9430 } 9431 9432 for (String codePath : allCodePaths) { 9433 for (String instructionSet : instructionSets) { 9434 int retCode = mInstaller.rmdex(codePath, instructionSet); 9435 if (retCode < 0) { 9436 Slog.w(TAG, "Couldn't remove dex file for package: " 9437 + " at location " + codePath + ", retcode=" + retCode); 9438 // we don't consider this to be a failure of the core package deletion 9439 } 9440 } 9441 } 9442 } 9443 } 9444 9445 boolean doPostDeleteLI(boolean delete) { 9446 // XXX err, shouldn't we respect the delete flag? 9447 cleanUpResourcesLI(); 9448 return true; 9449 } 9450 } 9451 9452 private boolean isAsecExternal(String cid) { 9453 final String asecPath = PackageHelper.getSdFilesystem(cid); 9454 return !asecPath.startsWith(mAsecInternalPath); 9455 } 9456 9457 /** 9458 * Extract the MountService "container ID" from the full code path of an 9459 * .apk. 9460 */ 9461 static String cidFromCodePath(String fullCodePath) { 9462 int eidx = fullCodePath.lastIndexOf("/"); 9463 String subStr1 = fullCodePath.substring(0, eidx); 9464 int sidx = subStr1.lastIndexOf("/"); 9465 return subStr1.substring(sidx+1, eidx); 9466 } 9467 9468 /** 9469 * Logic to handle installation of ASEC applications, including copying and 9470 * renaming logic. 9471 */ 9472 class AsecInstallArgs extends InstallArgs { 9473 // TODO: teach about handling cluster directories 9474 9475 static final String RES_FILE_NAME = "pkg.apk"; 9476 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9477 9478 String cid; 9479 String packagePath; 9480 String resourcePath; 9481 String legacyNativeLibraryDir; 9482 9483 /** New install */ 9484 AsecInstallArgs(InstallParams params) { 9485 super(params.originFile, params.originStaged, params.observer, params.flags, 9486 params.installerPackageName, params.getManifestDigest(), 9487 params.getUser(), null /* instruction sets */, 9488 params.packageAbiOverride, params.multiArch); 9489 } 9490 9491 /** Existing install */ 9492 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9493 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9494 super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9495 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9496 instructionSets, null, isMultiArch); 9497 // Extract cid from fullCodePath 9498 int eidx = fullCodePath.lastIndexOf("/"); 9499 String subStr1 = fullCodePath.substring(0, eidx); 9500 int sidx = subStr1.lastIndexOf("/"); 9501 cid = subStr1.substring(sidx+1, eidx); 9502 setCachePath(subStr1); 9503 } 9504 9505 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked, 9506 boolean isMultiArch) { 9507 super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9508 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9509 instructionSets, null, isMultiArch); 9510 this.cid = cid; 9511 setCachePath(PackageHelper.getSdDir(cid)); 9512 } 9513 9514 /** New install from existing */ 9515 AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets, 9516 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9517 super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9518 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9519 instructionSets, null, isMultiArch); 9520 this.cid = cid; 9521 } 9522 9523 void createCopyFile() { 9524 cid = getTempContainerId(); 9525 } 9526 9527 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9528 return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9529 abiOverride); 9530 } 9531 9532 private final boolean isExternal() { 9533 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9534 } 9535 9536 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9537 if (temp) { 9538 createCopyFile(); 9539 } else { 9540 /* 9541 * Pre-emptively destroy the container since it's destroyed if 9542 * copying fails due to it existing anyway. 9543 */ 9544 PackageHelper.destroySdDir(cid); 9545 } 9546 9547 final String newCachePath = imcs.copyPackageToContainer( 9548 originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9549 isFwdLocked(), abiOverride); 9550 9551 if (newCachePath != null) { 9552 setCachePath(newCachePath); 9553 return PackageManager.INSTALL_SUCCEEDED; 9554 } else { 9555 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9556 } 9557 } 9558 9559 @Override 9560 String getCodePath() { 9561 return packagePath; 9562 } 9563 9564 @Override 9565 String getResourcePath() { 9566 return resourcePath; 9567 } 9568 9569 @Override 9570 String getLegacyNativeLibraryPath() { 9571 return legacyNativeLibraryDir; 9572 } 9573 9574 int doPreInstall(int status) { 9575 if (status != PackageManager.INSTALL_SUCCEEDED) { 9576 // Destroy container 9577 PackageHelper.destroySdDir(cid); 9578 } else { 9579 boolean mounted = PackageHelper.isContainerMounted(cid); 9580 if (!mounted) { 9581 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9582 Process.SYSTEM_UID); 9583 if (newCachePath != null) { 9584 setCachePath(newCachePath); 9585 } else { 9586 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9587 } 9588 } 9589 } 9590 return status; 9591 } 9592 9593 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9594 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9595 String newCachePath = null; 9596 if (PackageHelper.isContainerMounted(cid)) { 9597 // Unmount the container 9598 if (!PackageHelper.unMountSdDir(cid)) { 9599 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9600 return false; 9601 } 9602 } 9603 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9604 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9605 " which might be stale. Will try to clean up."); 9606 // Clean up the stale container and proceed to recreate. 9607 if (!PackageHelper.destroySdDir(newCacheId)) { 9608 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9609 return false; 9610 } 9611 // Successfully cleaned up stale container. Try to rename again. 9612 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9613 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9614 + " inspite of cleaning it up."); 9615 return false; 9616 } 9617 } 9618 if (!PackageHelper.isContainerMounted(newCacheId)) { 9619 Slog.w(TAG, "Mounting container " + newCacheId); 9620 newCachePath = PackageHelper.mountSdDir(newCacheId, 9621 getEncryptKey(), Process.SYSTEM_UID); 9622 } else { 9623 newCachePath = PackageHelper.getSdDir(newCacheId); 9624 } 9625 if (newCachePath == null) { 9626 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9627 return false; 9628 } 9629 Log.i(TAG, "Succesfully renamed " + cid + 9630 " to " + newCacheId + 9631 " at new path: " + newCachePath); 9632 cid = newCacheId; 9633 setCachePath(newCachePath); 9634 9635 // TODO: extend to support split APKs 9636 pkg.codePath = getCodePath(); 9637 pkg.baseCodePath = getCodePath(); 9638 pkg.splitCodePaths = null; 9639 9640 pkg.applicationInfo.setCodePath(getCodePath()); 9641 pkg.applicationInfo.setBaseCodePath(getCodePath()); 9642 pkg.applicationInfo.setSplitCodePaths(null); 9643 pkg.applicationInfo.setResourcePath(getResourcePath()); 9644 pkg.applicationInfo.setBaseResourcePath(getResourcePath()); 9645 pkg.applicationInfo.setSplitResourcePaths(null); 9646 9647 return true; 9648 } 9649 9650 private void setCachePath(String newCachePath) { 9651 File cachePath = new File(newCachePath); 9652 legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath(); 9653 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9654 9655 if (isFwdLocked()) { 9656 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9657 } else { 9658 resourcePath = packagePath; 9659 } 9660 } 9661 9662 int doPostInstall(int status, int uid) { 9663 if (status != PackageManager.INSTALL_SUCCEEDED) { 9664 cleanUp(); 9665 } else { 9666 final int groupOwner; 9667 final String protectedFile; 9668 if (isFwdLocked()) { 9669 groupOwner = UserHandle.getSharedAppGid(uid); 9670 protectedFile = RES_FILE_NAME; 9671 } else { 9672 groupOwner = -1; 9673 protectedFile = null; 9674 } 9675 9676 if (uid < Process.FIRST_APPLICATION_UID 9677 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9678 Slog.e(TAG, "Failed to finalize " + cid); 9679 PackageHelper.destroySdDir(cid); 9680 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9681 } 9682 9683 boolean mounted = PackageHelper.isContainerMounted(cid); 9684 if (!mounted) { 9685 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9686 } 9687 } 9688 return status; 9689 } 9690 9691 private void cleanUp() { 9692 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9693 9694 // Destroy secure container 9695 PackageHelper.destroySdDir(cid); 9696 } 9697 9698 void cleanUpResourcesLI() { 9699 String sourceFile = getCodePath(); 9700 // Remove dex file 9701 if (instructionSets == null) { 9702 throw new IllegalStateException("instructionSet == null"); 9703 } 9704 for (String instructionSet : instructionSets) { 9705 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9706 if (retCode < 0) { 9707 Slog.w(TAG, "Couldn't remove dex file for package: " 9708 + " at location " 9709 + sourceFile.toString() + ", retcode=" + retCode); 9710 // we don't consider this to be a failure of the core package deletion 9711 } 9712 } 9713 cleanUp(); 9714 } 9715 9716 boolean matchContainer(String app) { 9717 if (cid.startsWith(app)) { 9718 return true; 9719 } 9720 return false; 9721 } 9722 9723 String getPackageName() { 9724 return getAsecPackageName(cid); 9725 } 9726 9727 boolean doPostDeleteLI(boolean delete) { 9728 boolean ret = false; 9729 boolean mounted = PackageHelper.isContainerMounted(cid); 9730 if (mounted) { 9731 // Unmount first 9732 ret = PackageHelper.unMountSdDir(cid); 9733 } 9734 if (ret && delete) { 9735 cleanUpResourcesLI(); 9736 } 9737 return ret; 9738 } 9739 9740 @Override 9741 int doPreCopy() { 9742 if (isFwdLocked()) { 9743 if (!PackageHelper.fixSdPermissions(cid, 9744 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9745 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9746 } 9747 } 9748 9749 return PackageManager.INSTALL_SUCCEEDED; 9750 } 9751 9752 @Override 9753 int doPostCopy(int uid) { 9754 if (isFwdLocked()) { 9755 if (uid < Process.FIRST_APPLICATION_UID 9756 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9757 RES_FILE_NAME)) { 9758 Slog.e(TAG, "Failed to finalize " + cid); 9759 PackageHelper.destroySdDir(cid); 9760 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9761 } 9762 } 9763 9764 return PackageManager.INSTALL_SUCCEEDED; 9765 } 9766 } 9767 9768 static String getAsecPackageName(String packageCid) { 9769 int idx = packageCid.lastIndexOf("-"); 9770 if (idx == -1) { 9771 return packageCid; 9772 } 9773 return packageCid.substring(0, idx); 9774 } 9775 9776 // Utility method used to create code paths based on package name and available index. 9777 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9778 String idxStr = ""; 9779 int idx = 1; 9780 // Fall back to default value of idx=1 if prefix is not 9781 // part of oldCodePath 9782 if (oldCodePath != null) { 9783 String subStr = oldCodePath; 9784 // Drop the suffix right away 9785 if (suffix != null && subStr.endsWith(suffix)) { 9786 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9787 } 9788 // If oldCodePath already contains prefix find out the 9789 // ending index to either increment or decrement. 9790 int sidx = subStr.lastIndexOf(prefix); 9791 if (sidx != -1) { 9792 subStr = subStr.substring(sidx + prefix.length()); 9793 if (subStr != null) { 9794 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9795 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9796 } 9797 try { 9798 idx = Integer.parseInt(subStr); 9799 if (idx <= 1) { 9800 idx++; 9801 } else { 9802 idx--; 9803 } 9804 } catch(NumberFormatException e) { 9805 } 9806 } 9807 } 9808 } 9809 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9810 return prefix + idxStr; 9811 } 9812 9813 // Utility method used to ignore ADD/REMOVE events 9814 // by directory observer. 9815 private static boolean ignoreCodePath(String fullPathStr) { 9816 String apkName = deriveCodePathName(fullPathStr); 9817 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9818 if (idx != -1 && ((idx+1) < apkName.length())) { 9819 // Make sure the package ends with a numeral 9820 String version = apkName.substring(idx+1); 9821 try { 9822 Integer.parseInt(version); 9823 return true; 9824 } catch (NumberFormatException e) {} 9825 } 9826 return false; 9827 } 9828 9829 // Utility method that returns the relative package path with respect 9830 // to the installation directory. Like say for /data/data/com.test-1.apk 9831 // string com.test-1 is returned. 9832 static String deriveCodePathName(String codePath) { 9833 if (codePath == null) { 9834 return null; 9835 } 9836 final File codeFile = new File(codePath); 9837 final String name = codeFile.getName(); 9838 if (codeFile.isDirectory()) { 9839 return name; 9840 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9841 final int lastDot = name.lastIndexOf('.'); 9842 return name.substring(0, lastDot); 9843 } else { 9844 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9845 return null; 9846 } 9847 } 9848 9849 class PackageInstalledInfo { 9850 String name; 9851 int uid; 9852 // The set of users that originally had this package installed. 9853 int[] origUsers; 9854 // The set of users that now have this package installed. 9855 int[] newUsers; 9856 PackageParser.Package pkg; 9857 int returnCode; 9858 String returnMsg; 9859 PackageRemovedInfo removedInfo; 9860 9861 public void setError(int code, String msg) { 9862 returnCode = code; 9863 returnMsg = msg; 9864 Slog.w(TAG, msg); 9865 } 9866 9867 // In some error cases we want to convey more info back to the observer 9868 String origPackage; 9869 String origPermission; 9870 } 9871 9872 /* 9873 * Install a non-existing package. 9874 */ 9875 private void installNewPackageLI(PackageParser.Package pkg, 9876 int parseFlags, int scanMode, UserHandle user, 9877 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9878 // Remember this for later, in case we need to rollback this install 9879 String pkgName = pkg.packageName; 9880 9881 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9882 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9883 synchronized(mPackages) { 9884 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9885 // A package with the same name is already installed, though 9886 // it has been renamed to an older name. The package we 9887 // are trying to install should be installed as an update to 9888 // the existing one, but that has not been requested, so bail. 9889 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9890 + " without first uninstalling package running as " 9891 + mSettings.mRenamedPackages.get(pkgName)); 9892 return; 9893 } 9894 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9895 // Don't allow installation over an existing package with the same name. 9896 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9897 + " without first uninstalling."); 9898 return; 9899 } 9900 } 9901 9902 try { 9903 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9904 System.currentTimeMillis(), user, abiOverride); 9905 9906 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9907 // delete the partially installed application. the data directory will have to be 9908 // restored if it was already existing 9909 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9910 // remove package from internal structures. Note that we want deletePackageX to 9911 // delete the package data and cache directories that it created in 9912 // scanPackageLocked, unless those directories existed before we even tried to 9913 // install. 9914 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9915 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9916 res.removedInfo, true); 9917 } 9918 9919 } catch (PackageManagerException e) { 9920 res.setError(e.error, 9921 "Package couldn't be installed in " + pkg.codePath + ": " + e.getMessage()); 9922 } 9923 } 9924 9925 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9926 // Upgrade keysets are being used. Determine if new package has a superset of the 9927 // required keys. 9928 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9929 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9930 for (int i = 0; i < upgradeKeySets.length; i++) { 9931 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9932 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9933 return true; 9934 } 9935 } 9936 return false; 9937 } 9938 9939 private void replacePackageLI(PackageParser.Package pkg, 9940 int parseFlags, int scanMode, UserHandle user, 9941 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9942 PackageParser.Package oldPackage; 9943 String pkgName = pkg.packageName; 9944 int[] allUsers; 9945 boolean[] perUserInstalled; 9946 9947 // First find the old package info and check signatures 9948 synchronized(mPackages) { 9949 oldPackage = mPackages.get(pkgName); 9950 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9951 PackageSetting ps = mSettings.mPackages.get(pkgName); 9952 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9953 // default to original signature matching 9954 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9955 != PackageManager.SIGNATURE_MATCH) { 9956 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9957 "New package has a different signature: " + pkgName); 9958 return; 9959 } 9960 } else { 9961 if(!checkUpgradeKeySetLP(ps, pkg)) { 9962 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9963 "New package not signed by keys specified by upgrade-keysets: " 9964 + pkgName); 9965 return; 9966 } 9967 } 9968 9969 // In case of rollback, remember per-user/profile install state 9970 allUsers = sUserManager.getUserIds(); 9971 perUserInstalled = new boolean[allUsers.length]; 9972 for (int i = 0; i < allUsers.length; i++) { 9973 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9974 } 9975 } 9976 boolean sysPkg = (isSystemApp(oldPackage)); 9977 if (sysPkg) { 9978 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9979 user, allUsers, perUserInstalled, installerPackageName, res, 9980 abiOverride); 9981 } else { 9982 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9983 user, allUsers, perUserInstalled, installerPackageName, res, 9984 abiOverride); 9985 } 9986 } 9987 9988 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9989 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9990 int[] allUsers, boolean[] perUserInstalled, 9991 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9992 String pkgName = deletedPackage.packageName; 9993 boolean deletedPkg = true; 9994 boolean updatedSettings = false; 9995 9996 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9997 + deletedPackage); 9998 long origUpdateTime; 9999 if (pkg.mExtras != null) { 10000 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10001 } else { 10002 origUpdateTime = 0; 10003 } 10004 10005 // First delete the existing package while retaining the data directory 10006 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10007 res.removedInfo, true)) { 10008 // If the existing package wasn't successfully deleted 10009 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10010 deletedPkg = false; 10011 } else { 10012 // Successfully deleted the old package. Now proceed with re-installation 10013 try { 10014 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10015 scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user, abiOverride); 10016 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10017 updatedSettings = true; 10018 } catch (PackageManagerException e) { 10019 res.setError(e.error, 10020 "Package couldn't be installed in " + pkg.codePath + ": " + e.getMessage()); 10021 } 10022 } 10023 10024 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10025 // remove package from internal structures. Note that we want deletePackageX to 10026 // delete the package data and cache directories that it created in 10027 // scanPackageLocked, unless those directories existed before we even tried to 10028 // install. 10029 if(updatedSettings) { 10030 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10031 deletePackageLI( 10032 pkgName, null, true, allUsers, perUserInstalled, 10033 PackageManager.DELETE_KEEP_DATA, 10034 res.removedInfo, true); 10035 } 10036 // Since we failed to install the new package we need to restore the old 10037 // package that we deleted. 10038 if (deletedPkg) { 10039 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10040 File restoreFile = new File(deletedPackage.codePath); 10041 // Parse old package 10042 boolean oldOnSd = isExternal(deletedPackage); 10043 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10044 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10045 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10046 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 10047 | SCAN_UPDATE_TIME; 10048 try { 10049 scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null, 10050 null); 10051 } catch (PackageManagerException e) { 10052 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10053 + e.getMessage()); 10054 return; 10055 } 10056 // Restore of old package succeeded. Update permissions. 10057 // writer 10058 synchronized (mPackages) { 10059 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10060 UPDATE_PERMISSIONS_ALL); 10061 // can downgrade to reader 10062 mSettings.writeLPr(); 10063 } 10064 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10065 } 10066 } 10067 } 10068 10069 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10070 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10071 int[] allUsers, boolean[] perUserInstalled, 10072 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10073 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10074 + ", old=" + deletedPackage); 10075 boolean updatedSettings = false; 10076 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 10077 PackageParser.PARSE_IS_SYSTEM; 10078 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10079 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10080 } 10081 String packageName = deletedPackage.packageName; 10082 if (packageName == null) { 10083 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10084 "Attempt to delete null packageName."); 10085 return; 10086 } 10087 PackageParser.Package oldPkg; 10088 PackageSetting oldPkgSetting; 10089 // reader 10090 synchronized (mPackages) { 10091 oldPkg = mPackages.get(packageName); 10092 oldPkgSetting = mSettings.mPackages.get(packageName); 10093 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10094 (oldPkgSetting == null)) { 10095 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10096 "Couldn't find package:" + packageName + " information"); 10097 return; 10098 } 10099 } 10100 10101 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10102 10103 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10104 res.removedInfo.removedPackage = packageName; 10105 // Remove existing system package 10106 removePackageLI(oldPkgSetting, true); 10107 // writer 10108 synchronized (mPackages) { 10109 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10110 // We didn't need to disable the .apk as a current system package, 10111 // which means we are replacing another update that is already 10112 // installed. We need to make sure to delete the older one's .apk. 10113 res.removedInfo.args = createInstallArgsForExisting(0, 10114 deletedPackage.applicationInfo.getCodePath(), 10115 deletedPackage.applicationInfo.getResourcePath(), 10116 deletedPackage.applicationInfo.nativeLibraryRootDir, 10117 getAppDexInstructionSets(deletedPackage.applicationInfo), 10118 isMultiArch(deletedPackage.applicationInfo)); 10119 } else { 10120 res.removedInfo.args = null; 10121 } 10122 } 10123 10124 // Successfully disabled the old package. Now proceed with re-installation 10125 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10126 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10127 10128 PackageParser.Package newPackage = null; 10129 try { 10130 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride); 10131 if (newPackage.mExtras != null) { 10132 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10133 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10134 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10135 10136 // is the update attempting to change shared user? that isn't going to work... 10137 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10138 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10139 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10140 + " to " + newPkgSetting.sharedUser); 10141 updatedSettings = true; 10142 } 10143 } 10144 10145 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10146 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10147 updatedSettings = true; 10148 } 10149 10150 } catch (PackageManagerException e) { 10151 res.setError(e.error, 10152 "Package couldn't be installed in " + pkg.codePath + ": " + e.getMessage()); 10153 } 10154 10155 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10156 // Re installation failed. Restore old information 10157 // Remove new pkg information 10158 if (newPackage != null) { 10159 removeInstalledPackageLI(newPackage, true); 10160 } 10161 // Add back the old system package 10162 try { 10163 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, 10164 null); 10165 } catch (PackageManagerException e) { 10166 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10167 } 10168 // Restore the old system information in Settings 10169 synchronized(mPackages) { 10170 if (updatedSettings) { 10171 mSettings.enableSystemPackageLPw(packageName); 10172 mSettings.setInstallerPackageName(packageName, 10173 oldPkgSetting.installerPackageName); 10174 } 10175 mSettings.writeLPr(); 10176 } 10177 } 10178 } 10179 10180 // Utility method used to move dex files during install. 10181 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10182 // TODO: extend to move split APK dex files 10183 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10184 final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo); 10185 for (String instructionSet : instructionSets) { 10186 int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath, 10187 instructionSet); 10188 if (retCode != 0) { 10189 /* 10190 * Programs may be lazily run through dexopt, so the 10191 * source may not exist. However, something seems to 10192 * have gone wrong, so note that dexopt needs to be 10193 * run again and remove the source file. In addition, 10194 * remove the target to make sure there isn't a stale 10195 * file from a previous version of the package. 10196 */ 10197 newPackage.mDexOptNeeded = true; 10198 mInstaller.rmdex(oldCodePath, instructionSet); 10199 mInstaller.rmdex(newPackage.baseCodePath, instructionSet); 10200 } 10201 } 10202 } 10203 return PackageManager.INSTALL_SUCCEEDED; 10204 } 10205 10206 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10207 int[] allUsers, boolean[] perUserInstalled, 10208 PackageInstalledInfo res) { 10209 String pkgName = newPackage.packageName; 10210 synchronized (mPackages) { 10211 //write settings. the installStatus will be incomplete at this stage. 10212 //note that the new package setting would have already been 10213 //added to mPackages. It hasn't been persisted yet. 10214 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10215 mSettings.writeLPr(); 10216 } 10217 10218 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10219 10220 synchronized (mPackages) { 10221 updatePermissionsLPw(newPackage.packageName, newPackage, 10222 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10223 ? UPDATE_PERMISSIONS_ALL : 0)); 10224 // For system-bundled packages, we assume that installing an upgraded version 10225 // of the package implies that the user actually wants to run that new code, 10226 // so we enable the package. 10227 if (isSystemApp(newPackage)) { 10228 // NB: implicit assumption that system package upgrades apply to all users 10229 if (DEBUG_INSTALL) { 10230 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10231 } 10232 PackageSetting ps = mSettings.mPackages.get(pkgName); 10233 if (ps != null) { 10234 if (res.origUsers != null) { 10235 for (int userHandle : res.origUsers) { 10236 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10237 userHandle, installerPackageName); 10238 } 10239 } 10240 // Also convey the prior install/uninstall state 10241 if (allUsers != null && perUserInstalled != null) { 10242 for (int i = 0; i < allUsers.length; i++) { 10243 if (DEBUG_INSTALL) { 10244 Slog.d(TAG, " user " + allUsers[i] 10245 + " => " + perUserInstalled[i]); 10246 } 10247 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10248 } 10249 // these install state changes will be persisted in the 10250 // upcoming call to mSettings.writeLPr(). 10251 } 10252 } 10253 } 10254 res.name = pkgName; 10255 res.uid = newPackage.applicationInfo.uid; 10256 res.pkg = newPackage; 10257 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10258 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10259 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10260 //to update install status 10261 mSettings.writeLPr(); 10262 } 10263 } 10264 10265 private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) { 10266 int pFlags = args.flags; 10267 String installerPackageName = args.installerPackageName; 10268 File tmpPackageFile = new File(args.getCodePath()); 10269 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10270 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10271 boolean replace = false; 10272 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10273 | (newInstall ? SCAN_NEW_INSTALL : 0); 10274 // Result object to be returned 10275 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10276 10277 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10278 // Retrieve PackageSettings and parse package 10279 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10280 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10281 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10282 PackageParser pp = new PackageParser(); 10283 pp.setSeparateProcesses(mSeparateProcesses); 10284 pp.setDisplayMetrics(mMetrics); 10285 10286 final PackageParser.Package pkg; 10287 try { 10288 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10289 } catch (PackageParserException e) { 10290 res.setError(e.error, "Failed parse during installPackageLI: " + e.getMessage()); 10291 return; 10292 } 10293 10294 String pkgName = res.name = pkg.packageName; 10295 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10296 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10297 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10298 return; 10299 } 10300 } 10301 10302 try { 10303 pp.collectCertificates(pkg, parseFlags); 10304 pp.collectManifestDigest(pkg); 10305 } catch (PackageParserException e) { 10306 res.setError(e.error, "Failed collect during installPackageLI: " + e.getMessage()); 10307 return; 10308 } 10309 10310 /* If the installer passed in a manifest digest, compare it now. */ 10311 if (args.manifestDigest != null) { 10312 if (DEBUG_INSTALL) { 10313 final String parsedManifest = pkg.manifestDigest == null ? "null" 10314 : pkg.manifestDigest.toString(); 10315 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10316 + parsedManifest); 10317 } 10318 10319 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10320 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10321 return; 10322 } 10323 } else if (DEBUG_INSTALL) { 10324 final String parsedManifest = pkg.manifestDigest == null 10325 ? "null" : pkg.manifestDigest.toString(); 10326 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10327 } 10328 10329 // Get rid of all references to package scan path via parser. 10330 pp = null; 10331 String oldCodePath = null; 10332 boolean systemApp = false; 10333 synchronized (mPackages) { 10334 // Check whether the newly-scanned package wants to define an already-defined perm 10335 int N = pkg.permissions.size(); 10336 for (int i = N-1; i >= 0; i--) { 10337 PackageParser.Permission perm = pkg.permissions.get(i); 10338 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10339 if (bp != null) { 10340 // If the defining package is signed with our cert, it's okay. This 10341 // also includes the "updating the same package" case, of course. 10342 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10343 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10344 // If the owning package is the system itself, we log but allow 10345 // install to proceed; we fail the install on all other permission 10346 // redefinitions. 10347 if (!bp.sourcePackage.equals("android")) { 10348 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10349 + pkg.packageName + " attempting to redeclare permission " 10350 + perm.info.name + " already owned by " + bp.sourcePackage); 10351 res.origPermission = perm.info.name; 10352 res.origPackage = bp.sourcePackage; 10353 return; 10354 } else { 10355 Slog.w(TAG, "Package " + pkg.packageName 10356 + " attempting to redeclare system permission " 10357 + perm.info.name + "; ignoring new declaration"); 10358 pkg.permissions.remove(i); 10359 } 10360 } 10361 } 10362 } 10363 10364 // Check if installing already existing package 10365 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10366 String oldName = mSettings.mRenamedPackages.get(pkgName); 10367 if (pkg.mOriginalPackages != null 10368 && pkg.mOriginalPackages.contains(oldName) 10369 && mPackages.containsKey(oldName)) { 10370 // This package is derived from an original package, 10371 // and this device has been updating from that original 10372 // name. We must continue using the original name, so 10373 // rename the new package here. 10374 pkg.setPackageName(oldName); 10375 pkgName = pkg.packageName; 10376 replace = true; 10377 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10378 + oldName + " pkgName=" + pkgName); 10379 } else if (mPackages.containsKey(pkgName)) { 10380 // This package, under its official name, already exists 10381 // on the device; we should replace it. 10382 replace = true; 10383 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10384 } 10385 } 10386 PackageSetting ps = mSettings.mPackages.get(pkgName); 10387 if (ps != null) { 10388 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10389 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10390 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10391 systemApp = (ps.pkg.applicationInfo.flags & 10392 ApplicationInfo.FLAG_SYSTEM) != 0; 10393 } 10394 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10395 } 10396 } 10397 10398 if (systemApp && onSd) { 10399 // Disable updates to system apps on sdcard 10400 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10401 "Cannot install updates to system apps on sdcard"); 10402 return; 10403 } 10404 10405 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10406 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10407 return; 10408 } 10409 10410 if (replace) { 10411 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10412 installerPackageName, res, args.abiOverride); 10413 } else { 10414 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10415 installerPackageName, res, args.abiOverride); 10416 } 10417 synchronized (mPackages) { 10418 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10419 if (ps != null) { 10420 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10421 } 10422 } 10423 } 10424 10425 private static boolean isForwardLocked(PackageParser.Package pkg) { 10426 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10427 } 10428 10429 private static boolean isForwardLocked(ApplicationInfo info) { 10430 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10431 } 10432 10433 private boolean isForwardLocked(PackageSetting ps) { 10434 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10435 } 10436 10437 private static boolean isMultiArch(PackageSetting ps) { 10438 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10439 } 10440 10441 private static boolean isMultiArch(ApplicationInfo info) { 10442 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10443 } 10444 10445 private static boolean isExternal(PackageParser.Package pkg) { 10446 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10447 } 10448 10449 private static boolean isExternal(PackageSetting ps) { 10450 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10451 } 10452 10453 private static boolean isExternal(ApplicationInfo info) { 10454 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10455 } 10456 10457 private static boolean isSystemApp(PackageParser.Package pkg) { 10458 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10459 } 10460 10461 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10462 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10463 } 10464 10465 private static boolean isSystemApp(ApplicationInfo info) { 10466 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10467 } 10468 10469 private static boolean isSystemApp(PackageSetting ps) { 10470 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10471 } 10472 10473 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10474 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10475 } 10476 10477 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10478 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10479 } 10480 10481 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10482 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10483 } 10484 10485 private int packageFlagsToInstallFlags(PackageSetting ps) { 10486 int installFlags = 0; 10487 if (isExternal(ps)) { 10488 installFlags |= PackageManager.INSTALL_EXTERNAL; 10489 } 10490 if (isForwardLocked(ps)) { 10491 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10492 } 10493 return installFlags; 10494 } 10495 10496 private void deleteTempPackageFiles() { 10497 final FilenameFilter filter = new FilenameFilter() { 10498 public boolean accept(File dir, String name) { 10499 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10500 } 10501 }; 10502 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10503 file.delete(); 10504 } 10505 } 10506 10507 @Override 10508 public void deletePackageAsUser(final String packageName, 10509 final IPackageDeleteObserver observer, 10510 final int userId, final int flags) { 10511 mContext.enforceCallingOrSelfPermission( 10512 android.Manifest.permission.DELETE_PACKAGES, null); 10513 final int uid = Binder.getCallingUid(); 10514 if (UserHandle.getUserId(uid) != userId) { 10515 mContext.enforceCallingPermission( 10516 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10517 "deletePackage for user " + userId); 10518 } 10519 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10520 try { 10521 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 10522 } catch (RemoteException re) { 10523 } 10524 return; 10525 } 10526 10527 boolean blocked = false; 10528 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10529 int[] users = sUserManager.getUserIds(); 10530 for (int i = 0; i < users.length; ++i) { 10531 if (getBlockUninstallForUser(packageName, users[i])) { 10532 blocked = true; 10533 break; 10534 } 10535 } 10536 } else { 10537 blocked = getBlockUninstallForUser(packageName, userId); 10538 } 10539 if (blocked) { 10540 try { 10541 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED); 10542 } catch (RemoteException re) { 10543 } 10544 return; 10545 } 10546 10547 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10548 // Queue up an async operation since the package deletion may take a little while. 10549 mHandler.post(new Runnable() { 10550 public void run() { 10551 mHandler.removeCallbacks(this); 10552 final int returnCode = deletePackageX(packageName, userId, flags); 10553 if (observer != null) { 10554 try { 10555 observer.packageDeleted(packageName, returnCode); 10556 } catch (RemoteException e) { 10557 Log.i(TAG, "Observer no longer exists."); 10558 } //end catch 10559 } //end if 10560 } //end run 10561 }); 10562 } 10563 10564 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10565 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10566 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10567 try { 10568 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10569 || dpm.isDeviceOwner(packageName))) { 10570 return true; 10571 } 10572 } catch (RemoteException e) { 10573 } 10574 return false; 10575 } 10576 10577 /** 10578 * This method is an internal method that could be get invoked either 10579 * to delete an installed package or to clean up a failed installation. 10580 * After deleting an installed package, a broadcast is sent to notify any 10581 * listeners that the package has been installed. For cleaning up a failed 10582 * installation, the broadcast is not necessary since the package's 10583 * installation wouldn't have sent the initial broadcast either 10584 * The key steps in deleting a package are 10585 * deleting the package information in internal structures like mPackages, 10586 * deleting the packages base directories through installd 10587 * updating mSettings to reflect current status 10588 * persisting settings for later use 10589 * sending a broadcast if necessary 10590 */ 10591 private int deletePackageX(String packageName, int userId, int flags) { 10592 final PackageRemovedInfo info = new PackageRemovedInfo(); 10593 final boolean res; 10594 10595 if (isPackageDeviceAdmin(packageName, userId)) { 10596 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10597 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10598 } 10599 10600 boolean removedForAllUsers = false; 10601 boolean systemUpdate = false; 10602 10603 // for the uninstall-updates case and restricted profiles, remember the per- 10604 // userhandle installed state 10605 int[] allUsers; 10606 boolean[] perUserInstalled; 10607 synchronized (mPackages) { 10608 PackageSetting ps = mSettings.mPackages.get(packageName); 10609 allUsers = sUserManager.getUserIds(); 10610 perUserInstalled = new boolean[allUsers.length]; 10611 for (int i = 0; i < allUsers.length; i++) { 10612 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10613 } 10614 } 10615 10616 synchronized (mInstallLock) { 10617 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10618 res = deletePackageLI(packageName, 10619 (flags & PackageManager.DELETE_ALL_USERS) != 0 10620 ? UserHandle.ALL : new UserHandle(userId), 10621 true, allUsers, perUserInstalled, 10622 flags | REMOVE_CHATTY, info, true); 10623 systemUpdate = info.isRemovedPackageSystemUpdate; 10624 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10625 removedForAllUsers = true; 10626 } 10627 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10628 + " removedForAllUsers=" + removedForAllUsers); 10629 } 10630 10631 if (res) { 10632 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10633 10634 // If the removed package was a system update, the old system package 10635 // was re-enabled; we need to broadcast this information 10636 if (systemUpdate) { 10637 Bundle extras = new Bundle(1); 10638 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10639 ? info.removedAppId : info.uid); 10640 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10641 10642 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10643 extras, null, null, null); 10644 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10645 extras, null, null, null); 10646 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10647 null, packageName, null, null); 10648 } 10649 } 10650 // Force a gc here. 10651 Runtime.getRuntime().gc(); 10652 // Delete the resources here after sending the broadcast to let 10653 // other processes clean up before deleting resources. 10654 if (info.args != null) { 10655 synchronized (mInstallLock) { 10656 info.args.doPostDeleteLI(true); 10657 } 10658 } 10659 10660 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10661 } 10662 10663 static class PackageRemovedInfo { 10664 String removedPackage; 10665 int uid = -1; 10666 int removedAppId = -1; 10667 int[] removedUsers = null; 10668 boolean isRemovedPackageSystemUpdate = false; 10669 // Clean up resources deleted packages. 10670 InstallArgs args = null; 10671 10672 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10673 Bundle extras = new Bundle(1); 10674 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10675 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10676 if (replacing) { 10677 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10678 } 10679 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10680 if (removedPackage != null) { 10681 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10682 extras, null, null, removedUsers); 10683 if (fullRemove && !replacing) { 10684 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10685 extras, null, null, removedUsers); 10686 } 10687 } 10688 if (removedAppId >= 0) { 10689 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10690 removedUsers); 10691 } 10692 } 10693 } 10694 10695 /* 10696 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10697 * flag is not set, the data directory is removed as well. 10698 * make sure this flag is set for partially installed apps. If not its meaningless to 10699 * delete a partially installed application. 10700 */ 10701 private void removePackageDataLI(PackageSetting ps, 10702 int[] allUserHandles, boolean[] perUserInstalled, 10703 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10704 String packageName = ps.name; 10705 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10706 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10707 // Retrieve object to delete permissions for shared user later on 10708 final PackageSetting deletedPs; 10709 // reader 10710 synchronized (mPackages) { 10711 deletedPs = mSettings.mPackages.get(packageName); 10712 if (outInfo != null) { 10713 outInfo.removedPackage = packageName; 10714 outInfo.removedUsers = deletedPs != null 10715 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10716 : null; 10717 } 10718 } 10719 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10720 removeDataDirsLI(packageName); 10721 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10722 } 10723 // writer 10724 synchronized (mPackages) { 10725 if (deletedPs != null) { 10726 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10727 if (outInfo != null) { 10728 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10729 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10730 } 10731 if (deletedPs != null) { 10732 updatePermissionsLPw(deletedPs.name, null, 0); 10733 if (deletedPs.sharedUser != null) { 10734 // remove permissions associated with package 10735 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10736 } 10737 } 10738 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10739 } 10740 // make sure to preserve per-user disabled state if this removal was just 10741 // a downgrade of a system app to the factory package 10742 if (allUserHandles != null && perUserInstalled != null) { 10743 if (DEBUG_REMOVE) { 10744 Slog.d(TAG, "Propagating install state across downgrade"); 10745 } 10746 for (int i = 0; i < allUserHandles.length; i++) { 10747 if (DEBUG_REMOVE) { 10748 Slog.d(TAG, " user " + allUserHandles[i] 10749 + " => " + perUserInstalled[i]); 10750 } 10751 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10752 } 10753 } 10754 } 10755 // can downgrade to reader 10756 if (writeSettings) { 10757 // Save settings now 10758 mSettings.writeLPr(); 10759 } 10760 } 10761 if (outInfo != null) { 10762 // A user ID was deleted here. Go through all users and remove it 10763 // from KeyStore. 10764 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10765 } 10766 } 10767 10768 static boolean locationIsPrivileged(File path) { 10769 try { 10770 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10771 .getCanonicalPath(); 10772 return path.getCanonicalPath().startsWith(privilegedAppDir); 10773 } catch (IOException e) { 10774 Slog.e(TAG, "Unable to access code path " + path); 10775 } 10776 return false; 10777 } 10778 10779 /* 10780 * Tries to delete system package. 10781 */ 10782 private boolean deleteSystemPackageLI(PackageSetting newPs, 10783 int[] allUserHandles, boolean[] perUserInstalled, 10784 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10785 final boolean applyUserRestrictions 10786 = (allUserHandles != null) && (perUserInstalled != null); 10787 PackageSetting disabledPs = null; 10788 // Confirm if the system package has been updated 10789 // An updated system app can be deleted. This will also have to restore 10790 // the system pkg from system partition 10791 // reader 10792 synchronized (mPackages) { 10793 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10794 } 10795 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10796 + " disabledPs=" + disabledPs); 10797 if (disabledPs == null) { 10798 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10799 return false; 10800 } else if (DEBUG_REMOVE) { 10801 Slog.d(TAG, "Deleting system pkg from data partition"); 10802 } 10803 if (DEBUG_REMOVE) { 10804 if (applyUserRestrictions) { 10805 Slog.d(TAG, "Remembering install states:"); 10806 for (int i = 0; i < allUserHandles.length; i++) { 10807 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10808 } 10809 } 10810 } 10811 // Delete the updated package 10812 outInfo.isRemovedPackageSystemUpdate = true; 10813 if (disabledPs.versionCode < newPs.versionCode) { 10814 // Delete data for downgrades 10815 flags &= ~PackageManager.DELETE_KEEP_DATA; 10816 } else { 10817 // Preserve data by setting flag 10818 flags |= PackageManager.DELETE_KEEP_DATA; 10819 } 10820 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10821 allUserHandles, perUserInstalled, outInfo, writeSettings); 10822 if (!ret) { 10823 return false; 10824 } 10825 // writer 10826 synchronized (mPackages) { 10827 // Reinstate the old system package 10828 mSettings.enableSystemPackageLPw(newPs.name); 10829 // Remove any native libraries from the upgraded package. 10830 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10831 } 10832 // Install the system package 10833 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10834 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10835 if (locationIsPrivileged(disabledPs.codePath)) { 10836 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10837 } 10838 10839 final PackageParser.Package newPkg; 10840 try { 10841 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, 10842 null, null); 10843 } catch (PackageManagerException e) { 10844 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10845 return false; 10846 } 10847 10848 // writer 10849 synchronized (mPackages) { 10850 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10851 setBundledAppAbisAndRoots(newPkg, ps); 10852 updatePermissionsLPw(newPkg.packageName, newPkg, 10853 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10854 if (applyUserRestrictions) { 10855 if (DEBUG_REMOVE) { 10856 Slog.d(TAG, "Propagating install state across reinstall"); 10857 } 10858 for (int i = 0; i < allUserHandles.length; i++) { 10859 if (DEBUG_REMOVE) { 10860 Slog.d(TAG, " user " + allUserHandles[i] 10861 + " => " + perUserInstalled[i]); 10862 } 10863 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10864 } 10865 // Regardless of writeSettings we need to ensure that this restriction 10866 // state propagation is persisted 10867 mSettings.writeAllUsersPackageRestrictionsLPr(); 10868 } 10869 // can downgrade to reader here 10870 if (writeSettings) { 10871 mSettings.writeLPr(); 10872 } 10873 } 10874 return true; 10875 } 10876 10877 private boolean deleteInstalledPackageLI(PackageSetting ps, 10878 boolean deleteCodeAndResources, int flags, 10879 int[] allUserHandles, boolean[] perUserInstalled, 10880 PackageRemovedInfo outInfo, boolean writeSettings) { 10881 if (outInfo != null) { 10882 outInfo.uid = ps.appId; 10883 } 10884 10885 // Delete package data from internal structures and also remove data if flag is set 10886 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10887 10888 // Delete application code and resources 10889 if (deleteCodeAndResources && (outInfo != null)) { 10890 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10891 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10892 getAppDexInstructionSets(ps), isMultiArch(ps)); 10893 } 10894 return true; 10895 } 10896 10897 @Override 10898 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10899 int userId) { 10900 mContext.enforceCallingOrSelfPermission( 10901 android.Manifest.permission.DELETE_PACKAGES, null); 10902 synchronized (mPackages) { 10903 PackageSetting ps = mSettings.mPackages.get(packageName); 10904 if (ps == null) { 10905 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10906 return false; 10907 } 10908 if (!ps.getInstalled(userId)) { 10909 // Can't block uninstall for an app that is not installed or enabled. 10910 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10911 return false; 10912 } 10913 ps.setBlockUninstall(blockUninstall, userId); 10914 mSettings.writePackageRestrictionsLPr(userId); 10915 } 10916 return true; 10917 } 10918 10919 @Override 10920 public boolean getBlockUninstallForUser(String packageName, int userId) { 10921 synchronized (mPackages) { 10922 PackageSetting ps = mSettings.mPackages.get(packageName); 10923 if (ps == null) { 10924 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10925 return false; 10926 } 10927 return ps.getBlockUninstall(userId); 10928 } 10929 } 10930 10931 /* 10932 * This method handles package deletion in general 10933 */ 10934 private boolean deletePackageLI(String packageName, UserHandle user, 10935 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10936 int flags, PackageRemovedInfo outInfo, 10937 boolean writeSettings) { 10938 if (packageName == null) { 10939 Slog.w(TAG, "Attempt to delete null packageName."); 10940 return false; 10941 } 10942 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10943 PackageSetting ps; 10944 boolean dataOnly = false; 10945 int removeUser = -1; 10946 int appId = -1; 10947 synchronized (mPackages) { 10948 ps = mSettings.mPackages.get(packageName); 10949 if (ps == null) { 10950 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10951 return false; 10952 } 10953 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10954 && user.getIdentifier() != UserHandle.USER_ALL) { 10955 // The caller is asking that the package only be deleted for a single 10956 // user. To do this, we just mark its uninstalled state and delete 10957 // its data. If this is a system app, we only allow this to happen if 10958 // they have set the special DELETE_SYSTEM_APP which requests different 10959 // semantics than normal for uninstalling system apps. 10960 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10961 ps.setUserState(user.getIdentifier(), 10962 COMPONENT_ENABLED_STATE_DEFAULT, 10963 false, //installed 10964 true, //stopped 10965 true, //notLaunched 10966 false, //blocked 10967 null, null, null, 10968 false // blockUninstall 10969 ); 10970 if (!isSystemApp(ps)) { 10971 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10972 // Other user still have this package installed, so all 10973 // we need to do is clear this user's data and save that 10974 // it is uninstalled. 10975 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10976 removeUser = user.getIdentifier(); 10977 appId = ps.appId; 10978 mSettings.writePackageRestrictionsLPr(removeUser); 10979 } else { 10980 // We need to set it back to 'installed' so the uninstall 10981 // broadcasts will be sent correctly. 10982 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10983 ps.setInstalled(true, user.getIdentifier()); 10984 } 10985 } else { 10986 // This is a system app, so we assume that the 10987 // other users still have this package installed, so all 10988 // we need to do is clear this user's data and save that 10989 // it is uninstalled. 10990 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10991 removeUser = user.getIdentifier(); 10992 appId = ps.appId; 10993 mSettings.writePackageRestrictionsLPr(removeUser); 10994 } 10995 } 10996 } 10997 10998 if (removeUser >= 0) { 10999 // From above, we determined that we are deleting this only 11000 // for a single user. Continue the work here. 11001 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11002 if (outInfo != null) { 11003 outInfo.removedPackage = packageName; 11004 outInfo.removedAppId = appId; 11005 outInfo.removedUsers = new int[] {removeUser}; 11006 } 11007 mInstaller.clearUserData(packageName, removeUser); 11008 removeKeystoreDataIfNeeded(removeUser, appId); 11009 schedulePackageCleaning(packageName, removeUser, false); 11010 return true; 11011 } 11012 11013 if (dataOnly) { 11014 // Delete application data first 11015 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11016 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11017 return true; 11018 } 11019 11020 boolean ret = false; 11021 if (isSystemApp(ps)) { 11022 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11023 // When an updated system application is deleted we delete the existing resources as well and 11024 // fall back to existing code in system partition 11025 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11026 flags, outInfo, writeSettings); 11027 } else { 11028 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11029 // Kill application pre-emptively especially for apps on sd. 11030 killApplication(packageName, ps.appId, "uninstall pkg"); 11031 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11032 allUserHandles, perUserInstalled, 11033 outInfo, writeSettings); 11034 } 11035 11036 return ret; 11037 } 11038 11039 private final class ClearStorageConnection implements ServiceConnection { 11040 IMediaContainerService mContainerService; 11041 11042 @Override 11043 public void onServiceConnected(ComponentName name, IBinder service) { 11044 synchronized (this) { 11045 mContainerService = IMediaContainerService.Stub.asInterface(service); 11046 notifyAll(); 11047 } 11048 } 11049 11050 @Override 11051 public void onServiceDisconnected(ComponentName name) { 11052 } 11053 } 11054 11055 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11056 final boolean mounted; 11057 if (Environment.isExternalStorageEmulated()) { 11058 mounted = true; 11059 } else { 11060 final String status = Environment.getExternalStorageState(); 11061 11062 mounted = status.equals(Environment.MEDIA_MOUNTED) 11063 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11064 } 11065 11066 if (!mounted) { 11067 return; 11068 } 11069 11070 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11071 int[] users; 11072 if (userId == UserHandle.USER_ALL) { 11073 users = sUserManager.getUserIds(); 11074 } else { 11075 users = new int[] { userId }; 11076 } 11077 final ClearStorageConnection conn = new ClearStorageConnection(); 11078 if (mContext.bindServiceAsUser( 11079 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11080 try { 11081 for (int curUser : users) { 11082 long timeout = SystemClock.uptimeMillis() + 5000; 11083 synchronized (conn) { 11084 long now = SystemClock.uptimeMillis(); 11085 while (conn.mContainerService == null && now < timeout) { 11086 try { 11087 conn.wait(timeout - now); 11088 } catch (InterruptedException e) { 11089 } 11090 } 11091 } 11092 if (conn.mContainerService == null) { 11093 return; 11094 } 11095 11096 final UserEnvironment userEnv = new UserEnvironment(curUser); 11097 clearDirectory(conn.mContainerService, 11098 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11099 if (allData) { 11100 clearDirectory(conn.mContainerService, 11101 userEnv.buildExternalStorageAppDataDirs(packageName)); 11102 clearDirectory(conn.mContainerService, 11103 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11104 } 11105 } 11106 } finally { 11107 mContext.unbindService(conn); 11108 } 11109 } 11110 } 11111 11112 @Override 11113 public void clearApplicationUserData(final String packageName, 11114 final IPackageDataObserver observer, final int userId) { 11115 mContext.enforceCallingOrSelfPermission( 11116 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11117 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11118 // Queue up an async operation since the package deletion may take a little while. 11119 mHandler.post(new Runnable() { 11120 public void run() { 11121 mHandler.removeCallbacks(this); 11122 final boolean succeeded; 11123 synchronized (mInstallLock) { 11124 succeeded = clearApplicationUserDataLI(packageName, userId); 11125 } 11126 clearExternalStorageDataSync(packageName, userId, true); 11127 if (succeeded) { 11128 // invoke DeviceStorageMonitor's update method to clear any notifications 11129 DeviceStorageMonitorInternal 11130 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11131 if (dsm != null) { 11132 dsm.checkMemory(); 11133 } 11134 } 11135 if(observer != null) { 11136 try { 11137 observer.onRemoveCompleted(packageName, succeeded); 11138 } catch (RemoteException e) { 11139 Log.i(TAG, "Observer no longer exists."); 11140 } 11141 } //end if observer 11142 } //end run 11143 }); 11144 } 11145 11146 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11147 if (packageName == null) { 11148 Slog.w(TAG, "Attempt to delete null packageName."); 11149 return false; 11150 } 11151 PackageParser.Package p; 11152 boolean dataOnly = false; 11153 final int appId; 11154 synchronized (mPackages) { 11155 p = mPackages.get(packageName); 11156 if (p == null) { 11157 dataOnly = true; 11158 PackageSetting ps = mSettings.mPackages.get(packageName); 11159 if ((ps == null) || (ps.pkg == null)) { 11160 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11161 return false; 11162 } 11163 p = ps.pkg; 11164 } 11165 if (!dataOnly) { 11166 // need to check this only for fully installed applications 11167 if (p == null) { 11168 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11169 return false; 11170 } 11171 final ApplicationInfo applicationInfo = p.applicationInfo; 11172 if (applicationInfo == null) { 11173 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11174 return false; 11175 } 11176 } 11177 if (p != null && p.applicationInfo != null) { 11178 appId = p.applicationInfo.uid; 11179 } else { 11180 appId = -1; 11181 } 11182 } 11183 int retCode = mInstaller.clearUserData(packageName, userId); 11184 if (retCode < 0) { 11185 Slog.w(TAG, "Couldn't remove cache files for package: " 11186 + packageName); 11187 return false; 11188 } 11189 removeKeystoreDataIfNeeded(userId, appId); 11190 return true; 11191 } 11192 11193 /** 11194 * Remove entries from the keystore daemon. Will only remove it if the 11195 * {@code appId} is valid. 11196 */ 11197 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11198 if (appId < 0) { 11199 return; 11200 } 11201 11202 final KeyStore keyStore = KeyStore.getInstance(); 11203 if (keyStore != null) { 11204 if (userId == UserHandle.USER_ALL) { 11205 for (final int individual : sUserManager.getUserIds()) { 11206 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11207 } 11208 } else { 11209 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11210 } 11211 } else { 11212 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11213 } 11214 } 11215 11216 @Override 11217 public void deleteApplicationCacheFiles(final String packageName, 11218 final IPackageDataObserver observer) { 11219 mContext.enforceCallingOrSelfPermission( 11220 android.Manifest.permission.DELETE_CACHE_FILES, null); 11221 // Queue up an async operation since the package deletion may take a little while. 11222 final int userId = UserHandle.getCallingUserId(); 11223 mHandler.post(new Runnable() { 11224 public void run() { 11225 mHandler.removeCallbacks(this); 11226 final boolean succeded; 11227 synchronized (mInstallLock) { 11228 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11229 } 11230 clearExternalStorageDataSync(packageName, userId, false); 11231 if(observer != null) { 11232 try { 11233 observer.onRemoveCompleted(packageName, succeded); 11234 } catch (RemoteException e) { 11235 Log.i(TAG, "Observer no longer exists."); 11236 } 11237 } //end if observer 11238 } //end run 11239 }); 11240 } 11241 11242 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11243 if (packageName == null) { 11244 Slog.w(TAG, "Attempt to delete null packageName."); 11245 return false; 11246 } 11247 PackageParser.Package p; 11248 synchronized (mPackages) { 11249 p = mPackages.get(packageName); 11250 } 11251 if (p == null) { 11252 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11253 return false; 11254 } 11255 final ApplicationInfo applicationInfo = p.applicationInfo; 11256 if (applicationInfo == null) { 11257 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11258 return false; 11259 } 11260 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11261 if (retCode < 0) { 11262 Slog.w(TAG, "Couldn't remove cache files for package: " 11263 + packageName + " u" + userId); 11264 return false; 11265 } 11266 return true; 11267 } 11268 11269 @Override 11270 public void getPackageSizeInfo(final String packageName, int userHandle, 11271 final IPackageStatsObserver observer) { 11272 mContext.enforceCallingOrSelfPermission( 11273 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11274 if (packageName == null) { 11275 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11276 } 11277 11278 PackageStats stats = new PackageStats(packageName, userHandle); 11279 11280 /* 11281 * Queue up an async operation since the package measurement may take a 11282 * little while. 11283 */ 11284 Message msg = mHandler.obtainMessage(INIT_COPY); 11285 msg.obj = new MeasureParams(stats, observer); 11286 mHandler.sendMessage(msg); 11287 } 11288 11289 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11290 PackageStats pStats) { 11291 if (packageName == null) { 11292 Slog.w(TAG, "Attempt to get size of null packageName."); 11293 return false; 11294 } 11295 PackageParser.Package p; 11296 boolean dataOnly = false; 11297 String libDirRoot = null; 11298 String asecPath = null; 11299 PackageSetting ps = null; 11300 synchronized (mPackages) { 11301 p = mPackages.get(packageName); 11302 ps = mSettings.mPackages.get(packageName); 11303 if(p == null) { 11304 dataOnly = true; 11305 if((ps == null) || (ps.pkg == null)) { 11306 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11307 return false; 11308 } 11309 p = ps.pkg; 11310 } 11311 if (ps != null) { 11312 libDirRoot = ps.legacyNativeLibraryPathString; 11313 } 11314 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11315 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11316 if (secureContainerId != null) { 11317 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11318 } 11319 } 11320 } 11321 String publicSrcDir = null; 11322 if(!dataOnly) { 11323 final ApplicationInfo applicationInfo = p.applicationInfo; 11324 if (applicationInfo == null) { 11325 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11326 return false; 11327 } 11328 if (isForwardLocked(p)) { 11329 publicSrcDir = applicationInfo.getBaseResourcePath(); 11330 } 11331 } 11332 // TODO: extend to measure size of split APKs 11333 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11334 // not just the first level. 11335 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11336 // just the primary. 11337 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11338 publicSrcDir, asecPath, getAppDexInstructionSets(ps), 11339 pStats); 11340 if (res < 0) { 11341 return false; 11342 } 11343 11344 // Fix-up for forward-locked applications in ASEC containers. 11345 if (!isExternal(p)) { 11346 pStats.codeSize += pStats.externalCodeSize; 11347 pStats.externalCodeSize = 0L; 11348 } 11349 11350 return true; 11351 } 11352 11353 11354 @Override 11355 public void addPackageToPreferred(String packageName) { 11356 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11357 } 11358 11359 @Override 11360 public void removePackageFromPreferred(String packageName) { 11361 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11362 } 11363 11364 @Override 11365 public List<PackageInfo> getPreferredPackages(int flags) { 11366 return new ArrayList<PackageInfo>(); 11367 } 11368 11369 private int getUidTargetSdkVersionLockedLPr(int uid) { 11370 Object obj = mSettings.getUserIdLPr(uid); 11371 if (obj instanceof SharedUserSetting) { 11372 final SharedUserSetting sus = (SharedUserSetting) obj; 11373 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11374 final Iterator<PackageSetting> it = sus.packages.iterator(); 11375 while (it.hasNext()) { 11376 final PackageSetting ps = it.next(); 11377 if (ps.pkg != null) { 11378 int v = ps.pkg.applicationInfo.targetSdkVersion; 11379 if (v < vers) vers = v; 11380 } 11381 } 11382 return vers; 11383 } else if (obj instanceof PackageSetting) { 11384 final PackageSetting ps = (PackageSetting) obj; 11385 if (ps.pkg != null) { 11386 return ps.pkg.applicationInfo.targetSdkVersion; 11387 } 11388 } 11389 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11390 } 11391 11392 @Override 11393 public void addPreferredActivity(IntentFilter filter, int match, 11394 ComponentName[] set, ComponentName activity, int userId) { 11395 addPreferredActivityInternal(filter, match, set, activity, true, userId); 11396 } 11397 11398 private void addPreferredActivityInternal(IntentFilter filter, int match, 11399 ComponentName[] set, ComponentName activity, boolean always, int userId) { 11400 // writer 11401 int callingUid = Binder.getCallingUid(); 11402 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11403 if (filter.countActions() == 0) { 11404 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11405 return; 11406 } 11407 synchronized (mPackages) { 11408 if (mContext.checkCallingOrSelfPermission( 11409 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11410 != PackageManager.PERMISSION_GRANTED) { 11411 if (getUidTargetSdkVersionLockedLPr(callingUid) 11412 < Build.VERSION_CODES.FROYO) { 11413 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11414 + callingUid); 11415 return; 11416 } 11417 mContext.enforceCallingOrSelfPermission( 11418 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11419 } 11420 11421 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 11422 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11423 mSettings.editPreferredActivitiesLPw(userId).addFilter( 11424 new PreferredActivity(filter, match, set, activity, always)); 11425 mSettings.writePackageRestrictionsLPr(userId); 11426 } 11427 } 11428 11429 @Override 11430 public void replacePreferredActivity(IntentFilter filter, int match, 11431 ComponentName[] set, ComponentName activity) { 11432 if (filter.countActions() != 1) { 11433 throw new IllegalArgumentException( 11434 "replacePreferredActivity expects filter to have only 1 action."); 11435 } 11436 if (filter.countDataAuthorities() != 0 11437 || filter.countDataPaths() != 0 11438 || filter.countDataSchemes() > 1 11439 || filter.countDataTypes() != 0) { 11440 throw new IllegalArgumentException( 11441 "replacePreferredActivity expects filter to have no data authorities, " + 11442 "paths, or types; and at most one scheme."); 11443 } 11444 synchronized (mPackages) { 11445 if (mContext.checkCallingOrSelfPermission( 11446 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11447 != PackageManager.PERMISSION_GRANTED) { 11448 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11449 < Build.VERSION_CODES.FROYO) { 11450 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11451 + Binder.getCallingUid()); 11452 return; 11453 } 11454 mContext.enforceCallingOrSelfPermission( 11455 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11456 } 11457 11458 final int callingUserId = UserHandle.getCallingUserId(); 11459 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 11460 if (pir != null) { 11461 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 11462 if (filter.countDataSchemes() == 1) { 11463 Uri.Builder builder = new Uri.Builder(); 11464 builder.scheme(filter.getDataScheme(0)); 11465 intent.setData(builder.build()); 11466 } 11467 List<PreferredActivity> matches = pir.queryIntent( 11468 intent, null, true, callingUserId); 11469 if (DEBUG_PREFERRED) { 11470 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 11471 } 11472 for (int i = 0; i < matches.size(); i++) { 11473 PreferredActivity pa = matches.get(i); 11474 if (DEBUG_PREFERRED) { 11475 Slog.i(TAG, "Removing preferred activity " 11476 + pa.mPref.mComponent + ":"); 11477 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11478 } 11479 pir.removeFilter(pa); 11480 } 11481 } 11482 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 11483 } 11484 } 11485 11486 @Override 11487 public void clearPackagePreferredActivities(String packageName) { 11488 final int uid = Binder.getCallingUid(); 11489 // writer 11490 synchronized (mPackages) { 11491 PackageParser.Package pkg = mPackages.get(packageName); 11492 if (pkg == null || pkg.applicationInfo.uid != uid) { 11493 if (mContext.checkCallingOrSelfPermission( 11494 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11495 != PackageManager.PERMISSION_GRANTED) { 11496 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11497 < Build.VERSION_CODES.FROYO) { 11498 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11499 + Binder.getCallingUid()); 11500 return; 11501 } 11502 mContext.enforceCallingOrSelfPermission( 11503 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11504 } 11505 } 11506 11507 int user = UserHandle.getCallingUserId(); 11508 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11509 mSettings.writePackageRestrictionsLPr(user); 11510 scheduleWriteSettingsLocked(); 11511 } 11512 } 11513 } 11514 11515 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11516 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11517 ArrayList<PreferredActivity> removed = null; 11518 boolean changed = false; 11519 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11520 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11521 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11522 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11523 continue; 11524 } 11525 Iterator<PreferredActivity> it = pir.filterIterator(); 11526 while (it.hasNext()) { 11527 PreferredActivity pa = it.next(); 11528 // Mark entry for removal only if it matches the package name 11529 // and the entry is of type "always". 11530 if (packageName == null || 11531 (pa.mPref.mComponent.getPackageName().equals(packageName) 11532 && pa.mPref.mAlways)) { 11533 if (removed == null) { 11534 removed = new ArrayList<PreferredActivity>(); 11535 } 11536 removed.add(pa); 11537 } 11538 } 11539 if (removed != null) { 11540 for (int j=0; j<removed.size(); j++) { 11541 PreferredActivity pa = removed.get(j); 11542 pir.removeFilter(pa); 11543 } 11544 changed = true; 11545 } 11546 } 11547 return changed; 11548 } 11549 11550 @Override 11551 public void resetPreferredActivities(int userId) { 11552 mContext.enforceCallingOrSelfPermission( 11553 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11554 // writer 11555 synchronized (mPackages) { 11556 int user = UserHandle.getCallingUserId(); 11557 clearPackagePreferredActivitiesLPw(null, user); 11558 mSettings.readDefaultPreferredAppsLPw(this, user); 11559 mSettings.writePackageRestrictionsLPr(user); 11560 scheduleWriteSettingsLocked(); 11561 } 11562 } 11563 11564 @Override 11565 public int getPreferredActivities(List<IntentFilter> outFilters, 11566 List<ComponentName> outActivities, String packageName) { 11567 11568 int num = 0; 11569 final int userId = UserHandle.getCallingUserId(); 11570 // reader 11571 synchronized (mPackages) { 11572 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11573 if (pir != null) { 11574 final Iterator<PreferredActivity> it = pir.filterIterator(); 11575 while (it.hasNext()) { 11576 final PreferredActivity pa = it.next(); 11577 if (packageName == null 11578 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11579 && pa.mPref.mAlways)) { 11580 if (outFilters != null) { 11581 outFilters.add(new IntentFilter(pa)); 11582 } 11583 if (outActivities != null) { 11584 outActivities.add(pa.mPref.mComponent); 11585 } 11586 } 11587 } 11588 } 11589 } 11590 11591 return num; 11592 } 11593 11594 @Override 11595 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11596 int userId) { 11597 int callingUid = Binder.getCallingUid(); 11598 if (callingUid != Process.SYSTEM_UID) { 11599 throw new SecurityException( 11600 "addPersistentPreferredActivity can only be run by the system"); 11601 } 11602 if (filter.countActions() == 0) { 11603 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11604 return; 11605 } 11606 synchronized (mPackages) { 11607 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11608 " :"); 11609 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11610 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11611 new PersistentPreferredActivity(filter, activity)); 11612 mSettings.writePackageRestrictionsLPr(userId); 11613 } 11614 } 11615 11616 @Override 11617 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11618 int callingUid = Binder.getCallingUid(); 11619 if (callingUid != Process.SYSTEM_UID) { 11620 throw new SecurityException( 11621 "clearPackagePersistentPreferredActivities can only be run by the system"); 11622 } 11623 ArrayList<PersistentPreferredActivity> removed = null; 11624 boolean changed = false; 11625 synchronized (mPackages) { 11626 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11627 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11628 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11629 .valueAt(i); 11630 if (userId != thisUserId) { 11631 continue; 11632 } 11633 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11634 while (it.hasNext()) { 11635 PersistentPreferredActivity ppa = it.next(); 11636 // Mark entry for removal only if it matches the package name. 11637 if (ppa.mComponent.getPackageName().equals(packageName)) { 11638 if (removed == null) { 11639 removed = new ArrayList<PersistentPreferredActivity>(); 11640 } 11641 removed.add(ppa); 11642 } 11643 } 11644 if (removed != null) { 11645 for (int j=0; j<removed.size(); j++) { 11646 PersistentPreferredActivity ppa = removed.get(j); 11647 ppir.removeFilter(ppa); 11648 } 11649 changed = true; 11650 } 11651 } 11652 11653 if (changed) { 11654 mSettings.writePackageRestrictionsLPr(userId); 11655 } 11656 } 11657 } 11658 11659 @Override 11660 public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId, 11661 int targetUserId, int flags) { 11662 mContext.enforceCallingOrSelfPermission( 11663 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11664 if (intentFilter.countActions() == 0) { 11665 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11666 return; 11667 } 11668 synchronized (mPackages) { 11669 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11670 targetUserId, flags); 11671 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11672 mSettings.writePackageRestrictionsLPr(sourceUserId); 11673 } 11674 } 11675 11676 public void addCrossProfileIntentsForPackage(String packageName, 11677 int sourceUserId, int targetUserId) { 11678 mContext.enforceCallingOrSelfPermission( 11679 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11680 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11681 mSettings.writePackageRestrictionsLPr(sourceUserId); 11682 } 11683 11684 public void removeCrossProfileIntentsForPackage(String packageName, 11685 int sourceUserId, int targetUserId) { 11686 mContext.enforceCallingOrSelfPermission( 11687 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11688 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11689 mSettings.writePackageRestrictionsLPr(sourceUserId); 11690 } 11691 11692 @Override 11693 public void clearCrossProfileIntentFilters(int sourceUserId) { 11694 mContext.enforceCallingOrSelfPermission( 11695 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11696 synchronized (mPackages) { 11697 CrossProfileIntentResolver resolver = 11698 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11699 HashSet<CrossProfileIntentFilter> set = 11700 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11701 for (CrossProfileIntentFilter filter : set) { 11702 if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) { 11703 resolver.removeFilter(filter); 11704 } 11705 } 11706 mSettings.writePackageRestrictionsLPr(sourceUserId); 11707 } 11708 } 11709 11710 @Override 11711 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11712 Intent intent = new Intent(Intent.ACTION_MAIN); 11713 intent.addCategory(Intent.CATEGORY_HOME); 11714 11715 final int callingUserId = UserHandle.getCallingUserId(); 11716 List<ResolveInfo> list = queryIntentActivities(intent, null, 11717 PackageManager.GET_META_DATA, callingUserId); 11718 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11719 true, false, false, callingUserId); 11720 11721 allHomeCandidates.clear(); 11722 if (list != null) { 11723 for (ResolveInfo ri : list) { 11724 allHomeCandidates.add(ri); 11725 } 11726 } 11727 return (preferred == null || preferred.activityInfo == null) 11728 ? null 11729 : new ComponentName(preferred.activityInfo.packageName, 11730 preferred.activityInfo.name); 11731 } 11732 11733 @Override 11734 public void setApplicationEnabledSetting(String appPackageName, 11735 int newState, int flags, int userId, String callingPackage) { 11736 if (!sUserManager.exists(userId)) return; 11737 if (callingPackage == null) { 11738 callingPackage = Integer.toString(Binder.getCallingUid()); 11739 } 11740 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11741 } 11742 11743 @Override 11744 public void setComponentEnabledSetting(ComponentName componentName, 11745 int newState, int flags, int userId) { 11746 if (!sUserManager.exists(userId)) return; 11747 setEnabledSetting(componentName.getPackageName(), 11748 componentName.getClassName(), newState, flags, userId, null); 11749 } 11750 11751 private void setEnabledSetting(final String packageName, String className, int newState, 11752 final int flags, int userId, String callingPackage) { 11753 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11754 || newState == COMPONENT_ENABLED_STATE_ENABLED 11755 || newState == COMPONENT_ENABLED_STATE_DISABLED 11756 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11757 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11758 throw new IllegalArgumentException("Invalid new component state: " 11759 + newState); 11760 } 11761 PackageSetting pkgSetting; 11762 final int uid = Binder.getCallingUid(); 11763 final int permission = mContext.checkCallingOrSelfPermission( 11764 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11765 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11766 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11767 boolean sendNow = false; 11768 boolean isApp = (className == null); 11769 String componentName = isApp ? packageName : className; 11770 int packageUid = -1; 11771 ArrayList<String> components; 11772 11773 // writer 11774 synchronized (mPackages) { 11775 pkgSetting = mSettings.mPackages.get(packageName); 11776 if (pkgSetting == null) { 11777 if (className == null) { 11778 throw new IllegalArgumentException( 11779 "Unknown package: " + packageName); 11780 } 11781 throw new IllegalArgumentException( 11782 "Unknown component: " + packageName 11783 + "/" + className); 11784 } 11785 // Allow root and verify that userId is not being specified by a different user 11786 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11787 throw new SecurityException( 11788 "Permission Denial: attempt to change component state from pid=" 11789 + Binder.getCallingPid() 11790 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11791 } 11792 if (className == null) { 11793 // We're dealing with an application/package level state change 11794 if (pkgSetting.getEnabled(userId) == newState) { 11795 // Nothing to do 11796 return; 11797 } 11798 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11799 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11800 // Don't care about who enables an app. 11801 callingPackage = null; 11802 } 11803 pkgSetting.setEnabled(newState, userId, callingPackage); 11804 // pkgSetting.pkg.mSetEnabled = newState; 11805 } else { 11806 // We're dealing with a component level state change 11807 // First, verify that this is a valid class name. 11808 PackageParser.Package pkg = pkgSetting.pkg; 11809 if (pkg == null || !pkg.hasComponentClassName(className)) { 11810 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11811 throw new IllegalArgumentException("Component class " + className 11812 + " does not exist in " + packageName); 11813 } else { 11814 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11815 + className + " does not exist in " + packageName); 11816 } 11817 } 11818 switch (newState) { 11819 case COMPONENT_ENABLED_STATE_ENABLED: 11820 if (!pkgSetting.enableComponentLPw(className, userId)) { 11821 return; 11822 } 11823 break; 11824 case COMPONENT_ENABLED_STATE_DISABLED: 11825 if (!pkgSetting.disableComponentLPw(className, userId)) { 11826 return; 11827 } 11828 break; 11829 case COMPONENT_ENABLED_STATE_DEFAULT: 11830 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11831 return; 11832 } 11833 break; 11834 default: 11835 Slog.e(TAG, "Invalid new component state: " + newState); 11836 return; 11837 } 11838 } 11839 mSettings.writePackageRestrictionsLPr(userId); 11840 components = mPendingBroadcasts.get(userId, packageName); 11841 final boolean newPackage = components == null; 11842 if (newPackage) { 11843 components = new ArrayList<String>(); 11844 } 11845 if (!components.contains(componentName)) { 11846 components.add(componentName); 11847 } 11848 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11849 sendNow = true; 11850 // Purge entry from pending broadcast list if another one exists already 11851 // since we are sending one right away. 11852 mPendingBroadcasts.remove(userId, packageName); 11853 } else { 11854 if (newPackage) { 11855 mPendingBroadcasts.put(userId, packageName, components); 11856 } 11857 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11858 // Schedule a message 11859 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11860 } 11861 } 11862 } 11863 11864 long callingId = Binder.clearCallingIdentity(); 11865 try { 11866 if (sendNow) { 11867 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11868 sendPackageChangedBroadcast(packageName, 11869 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11870 } 11871 } finally { 11872 Binder.restoreCallingIdentity(callingId); 11873 } 11874 } 11875 11876 private void sendPackageChangedBroadcast(String packageName, 11877 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11878 if (DEBUG_INSTALL) 11879 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11880 + componentNames); 11881 Bundle extras = new Bundle(4); 11882 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11883 String nameList[] = new String[componentNames.size()]; 11884 componentNames.toArray(nameList); 11885 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11886 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11887 extras.putInt(Intent.EXTRA_UID, packageUid); 11888 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11889 new int[] {UserHandle.getUserId(packageUid)}); 11890 } 11891 11892 @Override 11893 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11894 if (!sUserManager.exists(userId)) return; 11895 final int uid = Binder.getCallingUid(); 11896 final int permission = mContext.checkCallingOrSelfPermission( 11897 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11898 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11899 enforceCrossUserPermission(uid, userId, true, "stop package"); 11900 // writer 11901 synchronized (mPackages) { 11902 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11903 uid, userId)) { 11904 scheduleWritePackageRestrictionsLocked(userId); 11905 } 11906 } 11907 } 11908 11909 @Override 11910 public String getInstallerPackageName(String packageName) { 11911 // reader 11912 synchronized (mPackages) { 11913 return mSettings.getInstallerPackageNameLPr(packageName); 11914 } 11915 } 11916 11917 @Override 11918 public int getApplicationEnabledSetting(String packageName, int userId) { 11919 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11920 int uid = Binder.getCallingUid(); 11921 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11922 // reader 11923 synchronized (mPackages) { 11924 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11925 } 11926 } 11927 11928 @Override 11929 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11930 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11931 int uid = Binder.getCallingUid(); 11932 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11933 // reader 11934 synchronized (mPackages) { 11935 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11936 } 11937 } 11938 11939 @Override 11940 public void enterSafeMode() { 11941 enforceSystemOrRoot("Only the system can request entering safe mode"); 11942 11943 if (!mSystemReady) { 11944 mSafeMode = true; 11945 } 11946 } 11947 11948 @Override 11949 public void systemReady() { 11950 mSystemReady = true; 11951 11952 // Read the compatibilty setting when the system is ready. 11953 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11954 mContext.getContentResolver(), 11955 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11956 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11957 if (DEBUG_SETTINGS) { 11958 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11959 } 11960 11961 synchronized (mPackages) { 11962 // Verify that all of the preferred activity components actually 11963 // exist. It is possible for applications to be updated and at 11964 // that point remove a previously declared activity component that 11965 // had been set as a preferred activity. We try to clean this up 11966 // the next time we encounter that preferred activity, but it is 11967 // possible for the user flow to never be able to return to that 11968 // situation so here we do a sanity check to make sure we haven't 11969 // left any junk around. 11970 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11971 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11972 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11973 removed.clear(); 11974 for (PreferredActivity pa : pir.filterSet()) { 11975 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11976 removed.add(pa); 11977 } 11978 } 11979 if (removed.size() > 0) { 11980 for (int r=0; r<removed.size(); r++) { 11981 PreferredActivity pa = removed.get(r); 11982 Slog.w(TAG, "Removing dangling preferred activity: " 11983 + pa.mPref.mComponent); 11984 pir.removeFilter(pa); 11985 } 11986 mSettings.writePackageRestrictionsLPr( 11987 mSettings.mPreferredActivities.keyAt(i)); 11988 } 11989 } 11990 } 11991 sUserManager.systemReady(); 11992 } 11993 11994 @Override 11995 public boolean isSafeMode() { 11996 return mSafeMode; 11997 } 11998 11999 @Override 12000 public boolean hasSystemUidErrors() { 12001 return mHasSystemUidErrors; 12002 } 12003 12004 static String arrayToString(int[] array) { 12005 StringBuffer buf = new StringBuffer(128); 12006 buf.append('['); 12007 if (array != null) { 12008 for (int i=0; i<array.length; i++) { 12009 if (i > 0) buf.append(", "); 12010 buf.append(array[i]); 12011 } 12012 } 12013 buf.append(']'); 12014 return buf.toString(); 12015 } 12016 12017 static class DumpState { 12018 public static final int DUMP_LIBS = 1 << 0; 12019 12020 public static final int DUMP_FEATURES = 1 << 1; 12021 12022 public static final int DUMP_RESOLVERS = 1 << 2; 12023 12024 public static final int DUMP_PERMISSIONS = 1 << 3; 12025 12026 public static final int DUMP_PACKAGES = 1 << 4; 12027 12028 public static final int DUMP_SHARED_USERS = 1 << 5; 12029 12030 public static final int DUMP_MESSAGES = 1 << 6; 12031 12032 public static final int DUMP_PROVIDERS = 1 << 7; 12033 12034 public static final int DUMP_VERIFIERS = 1 << 8; 12035 12036 public static final int DUMP_PREFERRED = 1 << 9; 12037 12038 public static final int DUMP_PREFERRED_XML = 1 << 10; 12039 12040 public static final int DUMP_KEYSETS = 1 << 11; 12041 12042 public static final int DUMP_VERSION = 1 << 12; 12043 12044 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12045 12046 private int mTypes; 12047 12048 private int mOptions; 12049 12050 private boolean mTitlePrinted; 12051 12052 private SharedUserSetting mSharedUser; 12053 12054 public boolean isDumping(int type) { 12055 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12056 return true; 12057 } 12058 12059 return (mTypes & type) != 0; 12060 } 12061 12062 public void setDump(int type) { 12063 mTypes |= type; 12064 } 12065 12066 public boolean isOptionEnabled(int option) { 12067 return (mOptions & option) != 0; 12068 } 12069 12070 public void setOptionEnabled(int option) { 12071 mOptions |= option; 12072 } 12073 12074 public boolean onTitlePrinted() { 12075 final boolean printed = mTitlePrinted; 12076 mTitlePrinted = true; 12077 return printed; 12078 } 12079 12080 public boolean getTitlePrinted() { 12081 return mTitlePrinted; 12082 } 12083 12084 public void setTitlePrinted(boolean enabled) { 12085 mTitlePrinted = enabled; 12086 } 12087 12088 public SharedUserSetting getSharedUser() { 12089 return mSharedUser; 12090 } 12091 12092 public void setSharedUser(SharedUserSetting user) { 12093 mSharedUser = user; 12094 } 12095 } 12096 12097 @Override 12098 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12099 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12100 != PackageManager.PERMISSION_GRANTED) { 12101 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12102 + Binder.getCallingPid() 12103 + ", uid=" + Binder.getCallingUid() 12104 + " without permission " 12105 + android.Manifest.permission.DUMP); 12106 return; 12107 } 12108 12109 DumpState dumpState = new DumpState(); 12110 boolean fullPreferred = false; 12111 boolean checkin = false; 12112 12113 String packageName = null; 12114 12115 int opti = 0; 12116 while (opti < args.length) { 12117 String opt = args[opti]; 12118 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12119 break; 12120 } 12121 opti++; 12122 if ("-a".equals(opt)) { 12123 // Right now we only know how to print all. 12124 } else if ("-h".equals(opt)) { 12125 pw.println("Package manager dump options:"); 12126 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12127 pw.println(" --checkin: dump for a checkin"); 12128 pw.println(" -f: print details of intent filters"); 12129 pw.println(" -h: print this help"); 12130 pw.println(" cmd may be one of:"); 12131 pw.println(" l[ibraries]: list known shared libraries"); 12132 pw.println(" f[ibraries]: list device features"); 12133 pw.println(" k[eysets]: print known keysets"); 12134 pw.println(" r[esolvers]: dump intent resolvers"); 12135 pw.println(" perm[issions]: dump permissions"); 12136 pw.println(" pref[erred]: print preferred package settings"); 12137 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12138 pw.println(" prov[iders]: dump content providers"); 12139 pw.println(" p[ackages]: dump installed packages"); 12140 pw.println(" s[hared-users]: dump shared user IDs"); 12141 pw.println(" m[essages]: print collected runtime messages"); 12142 pw.println(" v[erifiers]: print package verifier info"); 12143 pw.println(" version: print database version info"); 12144 pw.println(" write: write current settings now"); 12145 pw.println(" <package.name>: info about given package"); 12146 return; 12147 } else if ("--checkin".equals(opt)) { 12148 checkin = true; 12149 } else if ("-f".equals(opt)) { 12150 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12151 } else { 12152 pw.println("Unknown argument: " + opt + "; use -h for help"); 12153 } 12154 } 12155 12156 // Is the caller requesting to dump a particular piece of data? 12157 if (opti < args.length) { 12158 String cmd = args[opti]; 12159 opti++; 12160 // Is this a package name? 12161 if ("android".equals(cmd) || cmd.contains(".")) { 12162 packageName = cmd; 12163 // When dumping a single package, we always dump all of its 12164 // filter information since the amount of data will be reasonable. 12165 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12166 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12167 dumpState.setDump(DumpState.DUMP_LIBS); 12168 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12169 dumpState.setDump(DumpState.DUMP_FEATURES); 12170 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12171 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12172 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12173 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12174 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12175 dumpState.setDump(DumpState.DUMP_PREFERRED); 12176 } else if ("preferred-xml".equals(cmd)) { 12177 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12178 if (opti < args.length && "--full".equals(args[opti])) { 12179 fullPreferred = true; 12180 opti++; 12181 } 12182 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12183 dumpState.setDump(DumpState.DUMP_PACKAGES); 12184 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12185 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12186 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12187 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12188 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12189 dumpState.setDump(DumpState.DUMP_MESSAGES); 12190 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12191 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12192 } else if ("version".equals(cmd)) { 12193 dumpState.setDump(DumpState.DUMP_VERSION); 12194 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12195 dumpState.setDump(DumpState.DUMP_KEYSETS); 12196 } else if ("write".equals(cmd)) { 12197 synchronized (mPackages) { 12198 mSettings.writeLPr(); 12199 pw.println("Settings written."); 12200 return; 12201 } 12202 } 12203 } 12204 12205 if (checkin) { 12206 pw.println("vers,1"); 12207 } 12208 12209 // reader 12210 synchronized (mPackages) { 12211 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12212 if (!checkin) { 12213 if (dumpState.onTitlePrinted()) 12214 pw.println(); 12215 pw.println("Database versions:"); 12216 pw.print(" SDK Version:"); 12217 pw.print(" internal="); 12218 pw.print(mSettings.mInternalSdkPlatform); 12219 pw.print(" external="); 12220 pw.println(mSettings.mExternalSdkPlatform); 12221 pw.print(" DB Version:"); 12222 pw.print(" internal="); 12223 pw.print(mSettings.mInternalDatabaseVersion); 12224 pw.print(" external="); 12225 pw.println(mSettings.mExternalDatabaseVersion); 12226 } 12227 } 12228 12229 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12230 if (!checkin) { 12231 if (dumpState.onTitlePrinted()) 12232 pw.println(); 12233 pw.println("Verifiers:"); 12234 pw.print(" Required: "); 12235 pw.print(mRequiredVerifierPackage); 12236 pw.print(" (uid="); 12237 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12238 pw.println(")"); 12239 } else if (mRequiredVerifierPackage != null) { 12240 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12241 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12242 } 12243 } 12244 12245 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12246 boolean printedHeader = false; 12247 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12248 while (it.hasNext()) { 12249 String name = it.next(); 12250 SharedLibraryEntry ent = mSharedLibraries.get(name); 12251 if (!checkin) { 12252 if (!printedHeader) { 12253 if (dumpState.onTitlePrinted()) 12254 pw.println(); 12255 pw.println("Libraries:"); 12256 printedHeader = true; 12257 } 12258 pw.print(" "); 12259 } else { 12260 pw.print("lib,"); 12261 } 12262 pw.print(name); 12263 if (!checkin) { 12264 pw.print(" -> "); 12265 } 12266 if (ent.path != null) { 12267 if (!checkin) { 12268 pw.print("(jar) "); 12269 pw.print(ent.path); 12270 } else { 12271 pw.print(",jar,"); 12272 pw.print(ent.path); 12273 } 12274 } else { 12275 if (!checkin) { 12276 pw.print("(apk) "); 12277 pw.print(ent.apk); 12278 } else { 12279 pw.print(",apk,"); 12280 pw.print(ent.apk); 12281 } 12282 } 12283 pw.println(); 12284 } 12285 } 12286 12287 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12288 if (dumpState.onTitlePrinted()) 12289 pw.println(); 12290 if (!checkin) { 12291 pw.println("Features:"); 12292 } 12293 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12294 while (it.hasNext()) { 12295 String name = it.next(); 12296 if (!checkin) { 12297 pw.print(" "); 12298 } else { 12299 pw.print("feat,"); 12300 } 12301 pw.println(name); 12302 } 12303 } 12304 12305 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12306 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12307 : "Activity Resolver Table:", " ", packageName, 12308 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12309 dumpState.setTitlePrinted(true); 12310 } 12311 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12312 : "Receiver Resolver Table:", " ", packageName, 12313 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12314 dumpState.setTitlePrinted(true); 12315 } 12316 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12317 : "Service Resolver Table:", " ", packageName, 12318 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12319 dumpState.setTitlePrinted(true); 12320 } 12321 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12322 : "Provider Resolver Table:", " ", packageName, 12323 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12324 dumpState.setTitlePrinted(true); 12325 } 12326 } 12327 12328 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12329 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12330 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12331 int user = mSettings.mPreferredActivities.keyAt(i); 12332 if (pir.dump(pw, 12333 dumpState.getTitlePrinted() 12334 ? "\nPreferred Activities User " + user + ":" 12335 : "Preferred Activities User " + user + ":", " ", 12336 packageName, true)) { 12337 dumpState.setTitlePrinted(true); 12338 } 12339 } 12340 } 12341 12342 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12343 pw.flush(); 12344 FileOutputStream fout = new FileOutputStream(fd); 12345 BufferedOutputStream str = new BufferedOutputStream(fout); 12346 XmlSerializer serializer = new FastXmlSerializer(); 12347 try { 12348 serializer.setOutput(str, "utf-8"); 12349 serializer.startDocument(null, true); 12350 serializer.setFeature( 12351 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12352 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12353 serializer.endDocument(); 12354 serializer.flush(); 12355 } catch (IllegalArgumentException e) { 12356 pw.println("Failed writing: " + e); 12357 } catch (IllegalStateException e) { 12358 pw.println("Failed writing: " + e); 12359 } catch (IOException e) { 12360 pw.println("Failed writing: " + e); 12361 } 12362 } 12363 12364 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12365 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12366 } 12367 12368 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12369 boolean printedSomething = false; 12370 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12371 if (packageName != null && !packageName.equals(p.info.packageName)) { 12372 continue; 12373 } 12374 if (!printedSomething) { 12375 if (dumpState.onTitlePrinted()) 12376 pw.println(); 12377 pw.println("Registered ContentProviders:"); 12378 printedSomething = true; 12379 } 12380 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12381 pw.print(" "); pw.println(p.toString()); 12382 } 12383 printedSomething = false; 12384 for (Map.Entry<String, PackageParser.Provider> entry : 12385 mProvidersByAuthority.entrySet()) { 12386 PackageParser.Provider p = entry.getValue(); 12387 if (packageName != null && !packageName.equals(p.info.packageName)) { 12388 continue; 12389 } 12390 if (!printedSomething) { 12391 if (dumpState.onTitlePrinted()) 12392 pw.println(); 12393 pw.println("ContentProvider Authorities:"); 12394 printedSomething = true; 12395 } 12396 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12397 pw.print(" "); pw.println(p.toString()); 12398 if (p.info != null && p.info.applicationInfo != null) { 12399 final String appInfo = p.info.applicationInfo.toString(); 12400 pw.print(" applicationInfo="); pw.println(appInfo); 12401 } 12402 } 12403 } 12404 12405 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12406 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12407 } 12408 12409 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12410 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12411 } 12412 12413 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12414 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12415 } 12416 12417 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12418 if (dumpState.onTitlePrinted()) 12419 pw.println(); 12420 mSettings.dumpReadMessagesLPr(pw, dumpState); 12421 12422 pw.println(); 12423 pw.println("Package warning messages:"); 12424 final File fname = getSettingsProblemFile(); 12425 FileInputStream in = null; 12426 try { 12427 in = new FileInputStream(fname); 12428 final int avail = in.available(); 12429 final byte[] data = new byte[avail]; 12430 in.read(data); 12431 pw.print(new String(data)); 12432 } catch (FileNotFoundException e) { 12433 } catch (IOException e) { 12434 } finally { 12435 if (in != null) { 12436 try { 12437 in.close(); 12438 } catch (IOException e) { 12439 } 12440 } 12441 } 12442 } 12443 } 12444 } 12445 12446 // ------- apps on sdcard specific code ------- 12447 static final boolean DEBUG_SD_INSTALL = false; 12448 12449 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12450 12451 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12452 12453 private boolean mMediaMounted = false; 12454 12455 private String getEncryptKey() { 12456 try { 12457 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12458 SD_ENCRYPTION_KEYSTORE_NAME); 12459 if (sdEncKey == null) { 12460 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12461 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12462 if (sdEncKey == null) { 12463 Slog.e(TAG, "Failed to create encryption keys"); 12464 return null; 12465 } 12466 } 12467 return sdEncKey; 12468 } catch (NoSuchAlgorithmException nsae) { 12469 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12470 return null; 12471 } catch (IOException ioe) { 12472 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12473 return null; 12474 } 12475 12476 } 12477 12478 /* package */static String getTempContainerId() { 12479 int tmpIdx = 1; 12480 String list[] = PackageHelper.getSecureContainerList(); 12481 if (list != null) { 12482 for (final String name : list) { 12483 // Ignore null and non-temporary container entries 12484 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12485 continue; 12486 } 12487 12488 String subStr = name.substring(mTempContainerPrefix.length()); 12489 try { 12490 int cid = Integer.parseInt(subStr); 12491 if (cid >= tmpIdx) { 12492 tmpIdx = cid + 1; 12493 } 12494 } catch (NumberFormatException e) { 12495 } 12496 } 12497 } 12498 return mTempContainerPrefix + tmpIdx; 12499 } 12500 12501 /* 12502 * Update media status on PackageManager. 12503 */ 12504 @Override 12505 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12506 int callingUid = Binder.getCallingUid(); 12507 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12508 throw new SecurityException("Media status can only be updated by the system"); 12509 } 12510 // reader; this apparently protects mMediaMounted, but should probably 12511 // be a different lock in that case. 12512 synchronized (mPackages) { 12513 Log.i(TAG, "Updating external media status from " 12514 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12515 + (mediaStatus ? "mounted" : "unmounted")); 12516 if (DEBUG_SD_INSTALL) 12517 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12518 + ", mMediaMounted=" + mMediaMounted); 12519 if (mediaStatus == mMediaMounted) { 12520 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12521 : 0, -1); 12522 mHandler.sendMessage(msg); 12523 return; 12524 } 12525 mMediaMounted = mediaStatus; 12526 } 12527 // Queue up an async operation since the package installation may take a 12528 // little while. 12529 mHandler.post(new Runnable() { 12530 public void run() { 12531 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12532 } 12533 }); 12534 } 12535 12536 /** 12537 * Called by MountService when the initial ASECs to scan are available. 12538 * Should block until all the ASEC containers are finished being scanned. 12539 */ 12540 public void scanAvailableAsecs() { 12541 updateExternalMediaStatusInner(true, false, false); 12542 if (mShouldRestoreconData) { 12543 SELinuxMMAC.setRestoreconDone(); 12544 mShouldRestoreconData = false; 12545 } 12546 } 12547 12548 /* 12549 * Collect information of applications on external media, map them against 12550 * existing containers and update information based on current mount status. 12551 * Please note that we always have to report status if reportStatus has been 12552 * set to true especially when unloading packages. 12553 */ 12554 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12555 boolean externalStorage) { 12556 // Collection of uids 12557 int uidArr[] = null; 12558 // Collection of stale containers 12559 HashSet<String> removeCids = new HashSet<String>(); 12560 // Collection of packages on external media with valid containers. 12561 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12562 // Get list of secure containers. 12563 final String list[] = PackageHelper.getSecureContainerList(); 12564 if (list == null || list.length == 0) { 12565 Log.i(TAG, "No secure containers on sdcard"); 12566 } else { 12567 // Process list of secure containers and categorize them 12568 // as active or stale based on their package internal state. 12569 int uidList[] = new int[list.length]; 12570 int num = 0; 12571 // reader 12572 synchronized (mPackages) { 12573 for (String cid : list) { 12574 if (DEBUG_SD_INSTALL) 12575 Log.i(TAG, "Processing container " + cid); 12576 String pkgName = getAsecPackageName(cid); 12577 if (pkgName == null) { 12578 if (DEBUG_SD_INSTALL) 12579 Log.i(TAG, "Container : " + cid + " stale"); 12580 removeCids.add(cid); 12581 continue; 12582 } 12583 if (DEBUG_SD_INSTALL) 12584 Log.i(TAG, "Looking for pkg : " + pkgName); 12585 12586 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12587 if (ps == null) { 12588 Log.i(TAG, "Deleting container with no matching settings " + cid); 12589 removeCids.add(cid); 12590 continue; 12591 } 12592 12593 /* 12594 * Skip packages that are not external if we're unmounting 12595 * external storage. 12596 */ 12597 if (externalStorage && !isMounted && !isExternal(ps)) { 12598 continue; 12599 } 12600 12601 final AsecInstallArgs args = new AsecInstallArgs(cid, 12602 getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps)); 12603 // The package status is changed only if the code path 12604 // matches between settings and the container id. 12605 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12606 if (DEBUG_SD_INSTALL) { 12607 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12608 + " at code path: " + ps.codePathString); 12609 } 12610 12611 // We do have a valid package installed on sdcard 12612 processCids.put(args, ps.codePathString); 12613 final int uid = ps.appId; 12614 if (uid != -1) { 12615 uidList[num++] = uid; 12616 } 12617 } else { 12618 Log.i(TAG, "Deleting stale container for " + cid); 12619 removeCids.add(cid); 12620 } 12621 } 12622 } 12623 12624 if (num > 0) { 12625 // Sort uid list 12626 Arrays.sort(uidList, 0, num); 12627 // Throw away duplicates 12628 uidArr = new int[num]; 12629 uidArr[0] = uidList[0]; 12630 int di = 0; 12631 for (int i = 1; i < num; i++) { 12632 if (uidList[i - 1] != uidList[i]) { 12633 uidArr[di++] = uidList[i]; 12634 } 12635 } 12636 } 12637 } 12638 // Process packages with valid entries. 12639 if (isMounted) { 12640 if (DEBUG_SD_INSTALL) 12641 Log.i(TAG, "Loading packages"); 12642 loadMediaPackages(processCids, uidArr, removeCids); 12643 startCleaningPackages(); 12644 } else { 12645 if (DEBUG_SD_INSTALL) 12646 Log.i(TAG, "Unloading packages"); 12647 unloadMediaPackages(processCids, uidArr, reportStatus); 12648 } 12649 } 12650 12651 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12652 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12653 int size = pkgList.size(); 12654 if (size > 0) { 12655 // Send broadcasts here 12656 Bundle extras = new Bundle(); 12657 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12658 .toArray(new String[size])); 12659 if (uidArr != null) { 12660 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12661 } 12662 if (replacing) { 12663 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12664 } 12665 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12666 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12667 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12668 } 12669 } 12670 12671 /* 12672 * Look at potentially valid container ids from processCids If package 12673 * information doesn't match the one on record or package scanning fails, 12674 * the cid is added to list of removeCids. We currently don't delete stale 12675 * containers. 12676 */ 12677 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12678 HashSet<String> removeCids) { 12679 ArrayList<String> pkgList = new ArrayList<String>(); 12680 Set<AsecInstallArgs> keys = processCids.keySet(); 12681 boolean doGc = false; 12682 for (AsecInstallArgs args : keys) { 12683 String codePath = processCids.get(args); 12684 if (DEBUG_SD_INSTALL) 12685 Log.i(TAG, "Loading container : " + args.cid); 12686 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12687 try { 12688 // Make sure there are no container errors first. 12689 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12690 Slog.e(TAG, "Failed to mount cid : " + args.cid 12691 + " when installing from sdcard"); 12692 continue; 12693 } 12694 // Check code path here. 12695 if (codePath == null || !codePath.equals(args.getCodePath())) { 12696 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12697 + " does not match one in settings " + codePath); 12698 continue; 12699 } 12700 // Parse package 12701 int parseFlags = mDefParseFlags; 12702 if (args.isExternal()) { 12703 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12704 } 12705 if (args.isFwdLocked()) { 12706 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12707 } 12708 12709 doGc = true; 12710 synchronized (mInstallLock) { 12711 PackageParser.Package pkg = null; 12712 try { 12713 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null, null); 12714 } catch (PackageManagerException e) { 12715 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12716 } 12717 // Scan the package 12718 if (pkg != null) { 12719 /* 12720 * TODO why is the lock being held? doPostInstall is 12721 * called in other places without the lock. This needs 12722 * to be straightened out. 12723 */ 12724 // writer 12725 synchronized (mPackages) { 12726 retCode = PackageManager.INSTALL_SUCCEEDED; 12727 pkgList.add(pkg.packageName); 12728 // Post process args 12729 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12730 pkg.applicationInfo.uid); 12731 } 12732 } else { 12733 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12734 } 12735 } 12736 12737 } finally { 12738 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12739 // Don't destroy container here. Wait till gc clears things 12740 // up. 12741 removeCids.add(args.cid); 12742 } 12743 } 12744 } 12745 // writer 12746 synchronized (mPackages) { 12747 // If the platform SDK has changed since the last time we booted, 12748 // we need to re-grant app permission to catch any new ones that 12749 // appear. This is really a hack, and means that apps can in some 12750 // cases get permissions that the user didn't initially explicitly 12751 // allow... it would be nice to have some better way to handle 12752 // this situation. 12753 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12754 if (regrantPermissions) 12755 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12756 + mSdkVersion + "; regranting permissions for external storage"); 12757 mSettings.mExternalSdkPlatform = mSdkVersion; 12758 12759 // Make sure group IDs have been assigned, and any permission 12760 // changes in other apps are accounted for 12761 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12762 | (regrantPermissions 12763 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12764 : 0)); 12765 12766 mSettings.updateExternalDatabaseVersion(); 12767 12768 // can downgrade to reader 12769 // Persist settings 12770 mSettings.writeLPr(); 12771 } 12772 // Send a broadcast to let everyone know we are done processing 12773 if (pkgList.size() > 0) { 12774 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12775 } 12776 // Force gc to avoid any stale parser references that we might have. 12777 if (doGc) { 12778 Runtime.getRuntime().gc(); 12779 } 12780 // List stale containers and destroy stale temporary containers. 12781 if (removeCids != null) { 12782 for (String cid : removeCids) { 12783 if (cid.startsWith(mTempContainerPrefix)) { 12784 Log.i(TAG, "Destroying stale temporary container " + cid); 12785 PackageHelper.destroySdDir(cid); 12786 } else { 12787 Log.w(TAG, "Container " + cid + " is stale"); 12788 } 12789 } 12790 } 12791 } 12792 12793 /* 12794 * Utility method to unload a list of specified containers 12795 */ 12796 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12797 // Just unmount all valid containers. 12798 for (AsecInstallArgs arg : cidArgs) { 12799 synchronized (mInstallLock) { 12800 arg.doPostDeleteLI(false); 12801 } 12802 } 12803 } 12804 12805 /* 12806 * Unload packages mounted on external media. This involves deleting package 12807 * data from internal structures, sending broadcasts about diabled packages, 12808 * gc'ing to free up references, unmounting all secure containers 12809 * corresponding to packages on external media, and posting a 12810 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12811 * that we always have to post this message if status has been requested no 12812 * matter what. 12813 */ 12814 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12815 final boolean reportStatus) { 12816 if (DEBUG_SD_INSTALL) 12817 Log.i(TAG, "unloading media packages"); 12818 ArrayList<String> pkgList = new ArrayList<String>(); 12819 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12820 final Set<AsecInstallArgs> keys = processCids.keySet(); 12821 for (AsecInstallArgs args : keys) { 12822 String pkgName = args.getPackageName(); 12823 if (DEBUG_SD_INSTALL) 12824 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12825 // Delete package internally 12826 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12827 synchronized (mInstallLock) { 12828 boolean res = deletePackageLI(pkgName, null, false, null, null, 12829 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12830 if (res) { 12831 pkgList.add(pkgName); 12832 } else { 12833 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12834 failedList.add(args); 12835 } 12836 } 12837 } 12838 12839 // reader 12840 synchronized (mPackages) { 12841 // We didn't update the settings after removing each package; 12842 // write them now for all packages. 12843 mSettings.writeLPr(); 12844 } 12845 12846 // We have to absolutely send UPDATED_MEDIA_STATUS only 12847 // after confirming that all the receivers processed the ordered 12848 // broadcast when packages get disabled, force a gc to clean things up. 12849 // and unload all the containers. 12850 if (pkgList.size() > 0) { 12851 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12852 new IIntentReceiver.Stub() { 12853 public void performReceive(Intent intent, int resultCode, String data, 12854 Bundle extras, boolean ordered, boolean sticky, 12855 int sendingUser) throws RemoteException { 12856 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12857 reportStatus ? 1 : 0, 1, keys); 12858 mHandler.sendMessage(msg); 12859 } 12860 }); 12861 } else { 12862 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12863 keys); 12864 mHandler.sendMessage(msg); 12865 } 12866 } 12867 12868 /** Binder call */ 12869 @Override 12870 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12871 final int flags) { 12872 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12873 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12874 int returnCode = PackageManager.MOVE_SUCCEEDED; 12875 int currFlags = 0; 12876 int newFlags = 0; 12877 // reader 12878 synchronized (mPackages) { 12879 PackageParser.Package pkg = mPackages.get(packageName); 12880 if (pkg == null) { 12881 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12882 } else { 12883 // Disable moving fwd locked apps and system packages 12884 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12885 Slog.w(TAG, "Cannot move system application"); 12886 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12887 } else if (pkg.mOperationPending) { 12888 Slog.w(TAG, "Attempt to move package which has pending operations"); 12889 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12890 } else { 12891 // Find install location first 12892 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12893 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12894 Slog.w(TAG, "Ambigous flags specified for move location."); 12895 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12896 } else { 12897 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12898 : PackageManager.INSTALL_INTERNAL; 12899 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12900 : PackageManager.INSTALL_INTERNAL; 12901 12902 if (newFlags == currFlags) { 12903 Slog.w(TAG, "No move required. Trying to move to same location"); 12904 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12905 } else { 12906 if (isForwardLocked(pkg)) { 12907 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12908 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12909 } 12910 } 12911 } 12912 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12913 pkg.mOperationPending = true; 12914 } 12915 } 12916 } 12917 12918 /* 12919 * TODO this next block probably shouldn't be inside the lock. We 12920 * can't guarantee these won't change after this is fired off 12921 * anyway. 12922 */ 12923 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12924 processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false), 12925 returnCode); 12926 } else { 12927 Message msg = mHandler.obtainMessage(INIT_COPY); 12928 final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 12929 final boolean multiArch = isMultiArch(pkg.applicationInfo); 12930 InstallArgs srcArgs = createInstallArgsForExisting(currFlags, 12931 pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(), 12932 pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch); 12933 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 12934 instructionSets, pkg.applicationInfo.uid, user, multiArch); 12935 msg.obj = mp; 12936 mHandler.sendMessage(msg); 12937 } 12938 } 12939 } 12940 12941 private void processPendingMove(final MoveParams mp, final int currentStatus) { 12942 // Queue up an async operation since the package deletion may take a 12943 // little while. 12944 mHandler.post(new Runnable() { 12945 public void run() { 12946 // TODO fix this; this does nothing. 12947 mHandler.removeCallbacks(this); 12948 int returnCode = currentStatus; 12949 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 12950 int uidArr[] = null; 12951 ArrayList<String> pkgList = null; 12952 synchronized (mPackages) { 12953 PackageParser.Package pkg = mPackages.get(mp.packageName); 12954 if (pkg == null) { 12955 Slog.w(TAG, " Package " + mp.packageName 12956 + " doesn't exist. Aborting move"); 12957 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12958 } else if (!mp.srcArgs.getCodePath().equals( 12959 pkg.applicationInfo.getCodePath())) { 12960 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 12961 + mp.srcArgs.getCodePath() + " to " 12962 + pkg.applicationInfo.getCodePath() 12963 + " Aborting move and returning error"); 12964 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12965 } else { 12966 uidArr = new int[] { 12967 pkg.applicationInfo.uid 12968 }; 12969 pkgList = new ArrayList<String>(); 12970 pkgList.add(mp.packageName); 12971 } 12972 } 12973 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12974 // Send resources unavailable broadcast 12975 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 12976 // Update package code and resource paths 12977 synchronized (mInstallLock) { 12978 synchronized (mPackages) { 12979 PackageParser.Package pkg = mPackages.get(mp.packageName); 12980 // Recheck for package again. 12981 if (pkg == null) { 12982 Slog.w(TAG, " Package " + mp.packageName 12983 + " doesn't exist. Aborting move"); 12984 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12985 } else if (!mp.srcArgs.getCodePath().equals( 12986 pkg.applicationInfo.getCodePath())) { 12987 Slog.w(TAG, "Package " + mp.packageName 12988 + " code path changed from " + mp.srcArgs.getCodePath() 12989 + " to " + pkg.applicationInfo.getCodePath() 12990 + " Aborting move and returning error"); 12991 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12992 } else { 12993 final String oldCodePath = pkg.codePath; 12994 final String newCodePath = mp.targetArgs.getCodePath(); 12995 final String newResPath = mp.targetArgs.getResourcePath(); 12996 // TODO: This assumes the new style of installation. 12997 // should we look at legacyNativeLibraryPath ? 12998 final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath(); 12999 final File newNativeDir = new File(newNativeRoot); 13000 13001 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 13002 // TODO(multiArch): Fix this so that it looks at the existing 13003 // recorded CPU abis from the package. There's no need for a separate 13004 // round of ABI scanning here. 13005 NativeLibraryHelper.Handle handle = null; 13006 try { 13007 handle = NativeLibraryHelper.Handle.create( 13008 new File(newCodePath)); 13009 final int abi = NativeLibraryHelper.findSupportedAbi( 13010 handle, Build.SUPPORTED_ABIS); 13011 if (abi >= 0) { 13012 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 13013 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 13014 } 13015 } catch (IOException ioe) { 13016 Slog.w(TAG, "Unable to extract native libs for package :" 13017 + mp.packageName, ioe); 13018 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13019 } finally { 13020 IoUtils.closeQuietly(handle); 13021 } 13022 } 13023 13024 final int[] users = sUserManager.getUserIds(); 13025 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13026 for (int user : users) { 13027 // TODO(multiArch): Fix this so that it links to the 13028 // correct directory. We're currently pointing to root. but we 13029 // must point to the arch specific subdirectory (if applicable). 13030 // 13031 // TODO(multiArch): Bogus reference to nativeLibraryDir. 13032 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 13033 newNativeRoot, user) < 0) { 13034 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13035 } 13036 } 13037 } 13038 13039 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13040 pkg.codePath = newCodePath; 13041 pkg.baseCodePath = newCodePath; 13042 // Move dex files around 13043 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 13044 // Moving of dex files failed. Set 13045 // error code and abort move. 13046 pkg.codePath = oldCodePath; 13047 pkg.baseCodePath = oldCodePath; 13048 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13049 } 13050 } 13051 13052 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13053 pkg.applicationInfo.setCodePath(newCodePath); 13054 pkg.applicationInfo.setBaseCodePath(newCodePath); 13055 pkg.applicationInfo.setSplitCodePaths(null); 13056 pkg.applicationInfo.setResourcePath(newResPath); 13057 pkg.applicationInfo.setBaseResourcePath(newResPath); 13058 pkg.applicationInfo.setSplitResourcePaths(null); 13059 13060 PackageSetting ps = (PackageSetting) pkg.mExtras; 13061 ps.codePath = new File(pkg.applicationInfo.getCodePath()); 13062 ps.codePathString = ps.codePath.getPath(); 13063 ps.resourcePath = new File(pkg.applicationInfo.getResourcePath()); 13064 ps.resourcePathString = ps.resourcePath.getPath(); 13065 13066 // Note that we don't have to recalculate the primary and secondary 13067 // CPU ABIs because they must already have been calculated during the 13068 // initial install of the app. 13069 ps.legacyNativeLibraryPathString = null; 13070 13071 // Set the application info flag 13072 // correctly. 13073 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 13074 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13075 } else { 13076 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13077 } 13078 ps.setFlags(pkg.applicationInfo.flags); 13079 mAppDirs.remove(oldCodePath); 13080 mAppDirs.put(newCodePath, pkg); 13081 // Persist settings 13082 mSettings.writeLPr(); 13083 } 13084 } 13085 } 13086 } 13087 // Send resources available broadcast 13088 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13089 } 13090 } 13091 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13092 // Clean up failed installation 13093 if (mp.targetArgs != null) { 13094 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 13095 -1); 13096 } 13097 } else { 13098 // Force a gc to clear things up. 13099 Runtime.getRuntime().gc(); 13100 // Delete older code 13101 synchronized (mInstallLock) { 13102 mp.srcArgs.doPostDeleteLI(true); 13103 } 13104 } 13105 13106 // Allow more operations on this file if we didn't fail because 13107 // an operation was already pending for this package. 13108 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 13109 synchronized (mPackages) { 13110 PackageParser.Package pkg = mPackages.get(mp.packageName); 13111 if (pkg != null) { 13112 pkg.mOperationPending = false; 13113 } 13114 } 13115 } 13116 13117 IPackageMoveObserver observer = mp.observer; 13118 if (observer != null) { 13119 try { 13120 observer.packageMoved(mp.packageName, returnCode); 13121 } catch (RemoteException e) { 13122 Log.i(TAG, "Observer no longer exists."); 13123 } 13124 } 13125 } 13126 }); 13127 } 13128 13129 @Override 13130 public boolean setInstallLocation(int loc) { 13131 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13132 null); 13133 if (getInstallLocation() == loc) { 13134 return true; 13135 } 13136 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13137 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13138 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13139 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13140 return true; 13141 } 13142 return false; 13143 } 13144 13145 @Override 13146 public int getInstallLocation() { 13147 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13148 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13149 PackageHelper.APP_INSTALL_AUTO); 13150 } 13151 13152 /** Called by UserManagerService */ 13153 void cleanUpUserLILPw(int userHandle) { 13154 mDirtyUsers.remove(userHandle); 13155 mSettings.removeUserLPw(userHandle); 13156 mPendingBroadcasts.remove(userHandle); 13157 if (mInstaller != null) { 13158 // Technically, we shouldn't be doing this with the package lock 13159 // held. However, this is very rare, and there is already so much 13160 // other disk I/O going on, that we'll let it slide for now. 13161 mInstaller.removeUserDataDirs(userHandle); 13162 } 13163 mUserNeedsBadging.delete(userHandle); 13164 } 13165 13166 /** Called by UserManagerService */ 13167 void createNewUserLILPw(int userHandle, File path) { 13168 if (mInstaller != null) { 13169 mInstaller.createUserConfig(userHandle); 13170 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13171 } 13172 } 13173 13174 @Override 13175 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13176 mContext.enforceCallingOrSelfPermission( 13177 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13178 "Only package verification agents can read the verifier device identity"); 13179 13180 synchronized (mPackages) { 13181 return mSettings.getVerifierDeviceIdentityLPw(); 13182 } 13183 } 13184 13185 @Override 13186 public void setPermissionEnforced(String permission, boolean enforced) { 13187 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13188 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13189 synchronized (mPackages) { 13190 if (mSettings.mReadExternalStorageEnforced == null 13191 || mSettings.mReadExternalStorageEnforced != enforced) { 13192 mSettings.mReadExternalStorageEnforced = enforced; 13193 mSettings.writeLPr(); 13194 } 13195 } 13196 // kill any non-foreground processes so we restart them and 13197 // grant/revoke the GID. 13198 final IActivityManager am = ActivityManagerNative.getDefault(); 13199 if (am != null) { 13200 final long token = Binder.clearCallingIdentity(); 13201 try { 13202 am.killProcessesBelowForeground("setPermissionEnforcement"); 13203 } catch (RemoteException e) { 13204 } finally { 13205 Binder.restoreCallingIdentity(token); 13206 } 13207 } 13208 } else { 13209 throw new IllegalArgumentException("No selective enforcement for " + permission); 13210 } 13211 } 13212 13213 @Override 13214 @Deprecated 13215 public boolean isPermissionEnforced(String permission) { 13216 return true; 13217 } 13218 13219 @Override 13220 public boolean isStorageLow() { 13221 final long token = Binder.clearCallingIdentity(); 13222 try { 13223 final DeviceStorageMonitorInternal 13224 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13225 if (dsm != null) { 13226 return dsm.isMemoryLow(); 13227 } else { 13228 return false; 13229 } 13230 } finally { 13231 Binder.restoreCallingIdentity(token); 13232 } 13233 } 13234 13235 @Override 13236 public IPackageInstaller getPackageInstaller() { 13237 return mInstallerService; 13238 } 13239 13240 private boolean userNeedsBadging(int userId) { 13241 int index = mUserNeedsBadging.indexOfKey(userId); 13242 if (index < 0) { 13243 final UserInfo userInfo; 13244 final long token = Binder.clearCallingIdentity(); 13245 try { 13246 userInfo = sUserManager.getUserInfo(userId); 13247 } finally { 13248 Binder.restoreCallingIdentity(token); 13249 } 13250 final boolean b; 13251 if (userInfo != null && userInfo.isManagedProfile()) { 13252 b = true; 13253 } else { 13254 b = false; 13255 } 13256 mUserNeedsBadging.put(userId, b); 13257 return b; 13258 } 13259 return mUserNeedsBadging.valueAt(index); 13260 } 13261} 13262