PackageManagerService.java revision 8d479b0c2ddb150182bcf510876a240cb869661b
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.Manifest.permission.INSTALL_PACKAGES; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 28import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 29import static android.content.pm.PackageParser.isApkFile; 30import static android.os.Process.PACKAGE_INFO_GID; 31import static android.os.Process.SYSTEM_UID; 32import static android.system.OsConstants.O_CREAT; 33import static android.system.OsConstants.EEXIST; 34import static android.system.OsConstants.O_EXCL; 35import static android.system.OsConstants.O_RDWR; 36import static android.system.OsConstants.O_WRONLY; 37import static android.system.OsConstants.S_IRGRP; 38import static android.system.OsConstants.S_IROTH; 39import static android.system.OsConstants.S_IRWXU; 40import static android.system.OsConstants.S_IXGRP; 41import static android.system.OsConstants.S_IXOTH; 42import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 43import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 44import static com.android.internal.util.ArrayUtils.appendInt; 45import static com.android.internal.util.ArrayUtils.removeInt; 46 47import android.util.ArrayMap; 48 49import com.android.internal.R; 50import com.android.internal.app.IMediaContainerService; 51import com.android.internal.app.ResolverActivity; 52import com.android.internal.content.NativeLibraryHelper; 53import com.android.internal.content.PackageHelper; 54import com.android.internal.os.IParcelFileDescriptorFactory; 55import com.android.internal.util.ArrayUtils; 56import com.android.internal.util.FastPrintWriter; 57import com.android.internal.util.FastXmlSerializer; 58import com.android.internal.util.Preconditions; 59import com.android.internal.util.XmlUtils; 60import com.android.server.EventLogTags; 61import com.android.server.IntentResolver; 62import com.android.server.LocalServices; 63import com.android.server.ServiceThread; 64import com.android.server.SystemConfig; 65import com.android.server.Watchdog; 66import com.android.server.pm.Settings.DatabaseVersion; 67import com.android.server.storage.DeviceStorageMonitorInternal; 68 69import org.xmlpull.v1.XmlPullParser; 70import org.xmlpull.v1.XmlPullParserException; 71import org.xmlpull.v1.XmlSerializer; 72 73import android.app.ActivityManager; 74import android.app.ActivityManagerNative; 75import android.app.IActivityManager; 76import android.app.PackageInstallObserver; 77import android.app.admin.IDevicePolicyManager; 78import android.app.backup.IBackupManager; 79import android.content.BroadcastReceiver; 80import android.content.ComponentName; 81import android.content.Context; 82import android.content.IIntentReceiver; 83import android.content.Intent; 84import android.content.IntentFilter; 85import android.content.IntentSender; 86import android.content.IntentSender.SendIntentException; 87import android.content.ServiceConnection; 88import android.content.pm.ActivityInfo; 89import android.content.pm.ApplicationInfo; 90import android.content.pm.ContainerEncryptionParams; 91import android.content.pm.FeatureInfo; 92import android.content.pm.IPackageDataObserver; 93import android.content.pm.IPackageDeleteObserver; 94import android.content.pm.IPackageInstallObserver; 95import android.content.pm.IPackageInstallObserver2; 96import android.content.pm.IPackageInstaller; 97import android.content.pm.IPackageManager; 98import android.content.pm.IPackageMoveObserver; 99import android.content.pm.IPackageStatsObserver; 100import android.content.pm.InstrumentationInfo; 101import android.content.pm.ManifestDigest; 102import android.content.pm.PackageCleanItem; 103import android.content.pm.PackageInfo; 104import android.content.pm.PackageInfoLite; 105import android.content.pm.PackageInstallerParams; 106import android.content.pm.PackageManager; 107import android.content.pm.PackageParser.ActivityIntentInfo; 108import android.content.pm.PackageParser.PackageLite; 109import android.content.pm.PackageParser.PackageParserException; 110import android.content.pm.PackageParser; 111import android.content.pm.PackageStats; 112import android.content.pm.PackageUserState; 113import android.content.pm.ParceledListSlice; 114import android.content.pm.PermissionGroupInfo; 115import android.content.pm.PermissionInfo; 116import android.content.pm.ProviderInfo; 117import android.content.pm.ResolveInfo; 118import android.content.pm.ServiceInfo; 119import android.content.pm.Signature; 120import android.content.pm.UserInfo; 121import android.content.pm.VerificationParams; 122import android.content.pm.VerifierDeviceIdentity; 123import android.content.pm.VerifierInfo; 124import android.content.res.Resources; 125import android.hardware.display.DisplayManager; 126import android.net.Uri; 127import android.os.Binder; 128import android.os.Build; 129import android.os.Bundle; 130import android.os.Environment; 131import android.os.Environment.UserEnvironment; 132import android.os.FileObserver; 133import android.os.FileUtils; 134import android.os.Handler; 135import android.os.IBinder; 136import android.os.Looper; 137import android.os.Message; 138import android.os.Parcel; 139import android.os.ParcelFileDescriptor; 140import android.os.Process; 141import android.os.RemoteException; 142import android.os.SELinux; 143import android.os.ServiceManager; 144import android.os.SystemClock; 145import android.os.SystemProperties; 146import android.os.UserHandle; 147import android.os.UserManager; 148import android.security.KeyStore; 149import android.security.SystemKeyStore; 150import android.system.ErrnoException; 151import android.system.Os; 152import android.system.OsConstants; 153import android.system.StructStat; 154import android.text.TextUtils; 155import android.util.ArraySet; 156import android.util.AtomicFile; 157import android.util.DisplayMetrics; 158import android.util.EventLog; 159import android.util.Log; 160import android.util.LogPrinter; 161import android.util.PrintStreamPrinter; 162import android.util.Slog; 163import android.util.SparseArray; 164import android.util.SparseBooleanArray; 165import android.util.Xml; 166import android.view.Display; 167 168import java.io.BufferedInputStream; 169import java.io.BufferedOutputStream; 170import java.io.File; 171import java.io.FileDescriptor; 172import java.io.FileInputStream; 173import java.io.FileNotFoundException; 174import java.io.FileOutputStream; 175import java.io.FileReader; 176import java.io.FilenameFilter; 177import java.io.IOException; 178import java.io.InputStream; 179import java.io.PrintWriter; 180import java.nio.charset.StandardCharsets; 181import java.security.NoSuchAlgorithmException; 182import java.security.PublicKey; 183import java.security.cert.CertificateEncodingException; 184import java.security.cert.CertificateException; 185import java.text.SimpleDateFormat; 186import java.util.ArrayList; 187import java.util.Arrays; 188import java.util.Collection; 189import java.util.Collections; 190import java.util.Comparator; 191import java.util.Date; 192import java.util.HashMap; 193import java.util.HashSet; 194import java.util.Iterator; 195import java.util.List; 196import java.util.Map; 197import java.util.Random; 198import java.util.Set; 199import java.util.concurrent.atomic.AtomicBoolean; 200import java.util.concurrent.atomic.AtomicLong; 201 202import dalvik.system.DexFile; 203import dalvik.system.StaleDexCacheError; 204import dalvik.system.VMRuntime; 205 206import libcore.io.IoUtils; 207import libcore.io.Libcore; 208 209/** 210 * Keep track of all those .apks everywhere. 211 * 212 * This is very central to the platform's security; please run the unit 213 * tests whenever making modifications here: 214 * 215mmm frameworks/base/tests/AndroidTests 216adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 217adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 218 * 219 * {@hide} 220 */ 221public class PackageManagerService extends IPackageManager.Stub { 222 static final String TAG = "PackageManager"; 223 static final boolean DEBUG_SETTINGS = false; 224 static final boolean DEBUG_PREFERRED = false; 225 static final boolean DEBUG_UPGRADE = false; 226 private static final boolean DEBUG_INSTALL = false; 227 private static final boolean DEBUG_REMOVE = false; 228 private static final boolean DEBUG_BROADCASTS = false; 229 private static final boolean DEBUG_SHOW_INFO = false; 230 private static final boolean DEBUG_PACKAGE_INFO = false; 231 private static final boolean DEBUG_INTENT_MATCHING = false; 232 private static final boolean DEBUG_PACKAGE_SCANNING = false; 233 private static final boolean DEBUG_APP_DIR_OBSERVER = false; 234 private static final boolean DEBUG_VERIFY = false; 235 private static final boolean DEBUG_DEXOPT = false; 236 237 private static final int RADIO_UID = Process.PHONE_UID; 238 private static final int LOG_UID = Process.LOG_UID; 239 private static final int NFC_UID = Process.NFC_UID; 240 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 241 private static final int SHELL_UID = Process.SHELL_UID; 242 243 // Cap the size of permission trees that 3rd party apps can define 244 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 245 246 private static final int REMOVE_EVENTS = 247 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM; 248 private static final int ADD_EVENTS = 249 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO; 250 251 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS; 252 // Suffix used during package installation when copying/moving 253 // package apks to install directory. 254 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 255 256 static final int SCAN_MONITOR = 1<<0; 257 static final int SCAN_NO_DEX = 1<<1; 258 static final int SCAN_FORCE_DEX = 1<<2; 259 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 260 static final int SCAN_NEW_INSTALL = 1<<4; 261 static final int SCAN_NO_PATHS = 1<<5; 262 static final int SCAN_UPDATE_TIME = 1<<6; 263 static final int SCAN_DEFER_DEX = 1<<7; 264 static final int SCAN_BOOTING = 1<<8; 265 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 266 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 267 268 static final int REMOVE_CHATTY = 1<<16; 269 270 /** 271 * Timeout (in milliseconds) after which the watchdog should declare that 272 * our handler thread is wedged. The usual default for such things is one 273 * minute but we sometimes do very lengthy I/O operations on this thread, 274 * such as installing multi-gigabyte applications, so ours needs to be longer. 275 */ 276 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 277 278 /** 279 * Whether verification is enabled by default. 280 */ 281 private static final boolean DEFAULT_VERIFY_ENABLE = true; 282 283 /** 284 * The default maximum time to wait for the verification agent to return in 285 * milliseconds. 286 */ 287 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 288 289 /** 290 * The default response for package verification timeout. 291 * 292 * This can be either PackageManager.VERIFICATION_ALLOW or 293 * PackageManager.VERIFICATION_REJECT. 294 */ 295 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 296 297 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 298 299 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 300 DEFAULT_CONTAINER_PACKAGE, 301 "com.android.defcontainer.DefaultContainerService"); 302 303 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 304 305 private static final String LIB_DIR_NAME = "lib"; 306 private static final String LIB64_DIR_NAME = "lib64"; 307 308 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 309 310 static final String mTempContainerPrefix = "smdl2tmp"; 311 312 private static String sPreferredInstructionSet; 313 314 final ServiceThread mHandlerThread; 315 316 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 317 private static final String IDMAP_SUFFIX = "@idmap"; 318 319 final PackageHandler mHandler; 320 321 final int mSdkVersion = Build.VERSION.SDK_INT; 322 323 final Context mContext; 324 final boolean mFactoryTest; 325 final boolean mOnlyCore; 326 final DisplayMetrics mMetrics; 327 final int mDefParseFlags; 328 final String[] mSeparateProcesses; 329 330 // This is where all application persistent data goes. 331 final File mAppDataDir; 332 333 // This is where all application persistent data goes for secondary users. 334 final File mUserAppDataDir; 335 336 /** The location for ASEC container files on internal storage. */ 337 final String mAsecInternalPath; 338 339 // This is the object monitoring the framework dir. 340 final FileObserver mFrameworkInstallObserver; 341 342 // This is the object monitoring the system app dir. 343 final FileObserver mSystemInstallObserver; 344 345 // This is the object monitoring the privileged system app dir. 346 final FileObserver mPrivilegedInstallObserver; 347 348 // This is the object monitoring the vendor app dir. 349 final FileObserver mVendorInstallObserver; 350 351 // This is the object monitoring the vendor overlay package dir. 352 final FileObserver mVendorOverlayInstallObserver; 353 354 // This is the object monitoring the OEM app dir. 355 final FileObserver mOemInstallObserver; 356 357 // This is the object monitoring mAppInstallDir. 358 final FileObserver mAppInstallObserver; 359 360 // This is the object monitoring mDrmAppPrivateInstallDir. 361 final FileObserver mDrmAppInstallObserver; 362 363 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 364 // LOCK HELD. Can be called with mInstallLock held. 365 final Installer mInstaller; 366 367 /** Directory where installed third-party apps stored */ 368 final File mAppInstallDir; 369 370 /** 371 * Directory to which applications installed internally have native 372 * libraries copied. 373 */ 374 private File mAppLibInstallDir; 375 376 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 377 // apps. 378 final File mDrmAppPrivateInstallDir; 379 380 /** Directory where third-party apps are staged before install */ 381 final File mAppStagingDir; 382 383 private final Random mTempFileRandom = new Random(); 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 // Information for the parser to write more useful error messages. 399 int mLastScanError; 400 401 // ---------------------------------------------------------------- 402 403 // Keys are String (package name), values are Package. This also serves 404 // as the lock for the global state. Methods that must be called with 405 // this lock held have the prefix "LP". 406 final HashMap<String, PackageParser.Package> mPackages = 407 new HashMap<String, PackageParser.Package>(); 408 409 // Tracks available target package names -> overlay package paths. 410 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 411 new HashMap<String, HashMap<String, PackageParser.Package>>(); 412 413 final Settings mSettings; 414 boolean mRestoredSettings; 415 416 // System configuration read by SystemConfig. 417 final int[] mGlobalGids; 418 final SparseArray<HashSet<String>> mSystemPermissions; 419 final HashMap<String, FeatureInfo> mAvailableFeatures; 420 421 // If mac_permissions.xml was found for seinfo labeling. 422 boolean mFoundPolicyFile; 423 424 // If a recursive restorecon of /data/data/<pkg> is needed. 425 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 426 427 public static final class SharedLibraryEntry { 428 public final String path; 429 public final String apk; 430 431 SharedLibraryEntry(String _path, String _apk) { 432 path = _path; 433 apk = _apk; 434 } 435 } 436 437 // Currently known shared libraries. 438 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 439 new HashMap<String, SharedLibraryEntry>(); 440 441 // All available activities, for your resolving pleasure. 442 final ActivityIntentResolver mActivities = 443 new ActivityIntentResolver(); 444 445 // All available receivers, for your resolving pleasure. 446 final ActivityIntentResolver mReceivers = 447 new ActivityIntentResolver(); 448 449 // All available services, for your resolving pleasure. 450 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 451 452 // All available providers, for your resolving pleasure. 453 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 454 455 // Mapping from provider base names (first directory in content URI codePath) 456 // to the provider information. 457 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 458 new HashMap<String, PackageParser.Provider>(); 459 460 // Mapping from instrumentation class names to info about them. 461 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 462 new HashMap<ComponentName, PackageParser.Instrumentation>(); 463 464 // Mapping from permission names to info about them. 465 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 466 new HashMap<String, PackageParser.PermissionGroup>(); 467 468 // Packages whose data we have transfered into another package, thus 469 // should no longer exist. 470 final HashSet<String> mTransferedPackages = new HashSet<String>(); 471 472 // Broadcast actions that are only available to the system. 473 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 474 475 /** List of packages waiting for verification. */ 476 final SparseArray<PackageVerificationState> mPendingVerification 477 = new SparseArray<PackageVerificationState>(); 478 479 final PackageInstallerService mInstallerService; 480 481 HashSet<PackageParser.Package> mDeferredDexOpt = null; 482 483 // Cache of users who need badging. 484 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 485 486 /** Token for keys in mPendingVerification. */ 487 private int mPendingVerificationToken = 0; 488 489 boolean mSystemReady; 490 boolean mSafeMode; 491 boolean mHasSystemUidErrors; 492 493 ApplicationInfo mAndroidApplication; 494 final ActivityInfo mResolveActivity = new ActivityInfo(); 495 final ResolveInfo mResolveInfo = new ResolveInfo(); 496 ComponentName mResolveComponentName; 497 PackageParser.Package mPlatformPackage; 498 ComponentName mCustomResolverComponentName; 499 500 boolean mResolverReplaced = false; 501 502 // Set of pending broadcasts for aggregating enable/disable of components. 503 static class PendingPackageBroadcasts { 504 // for each user id, a map of <package name -> components within that package> 505 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 506 507 public PendingPackageBroadcasts() { 508 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 509 } 510 511 public ArrayList<String> get(int userId, String packageName) { 512 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 513 return packages.get(packageName); 514 } 515 516 public void put(int userId, String packageName, ArrayList<String> components) { 517 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 518 packages.put(packageName, components); 519 } 520 521 public void remove(int userId, String packageName) { 522 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 523 if (packages != null) { 524 packages.remove(packageName); 525 } 526 } 527 528 public void remove(int userId) { 529 mUidMap.remove(userId); 530 } 531 532 public int userIdCount() { 533 return mUidMap.size(); 534 } 535 536 public int userIdAt(int n) { 537 return mUidMap.keyAt(n); 538 } 539 540 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 541 return mUidMap.get(userId); 542 } 543 544 public int size() { 545 // total number of pending broadcast entries across all userIds 546 int num = 0; 547 for (int i = 0; i< mUidMap.size(); i++) { 548 num += mUidMap.valueAt(i).size(); 549 } 550 return num; 551 } 552 553 public void clear() { 554 mUidMap.clear(); 555 } 556 557 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 558 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 559 if (map == null) { 560 map = new HashMap<String, ArrayList<String>>(); 561 mUidMap.put(userId, map); 562 } 563 return map; 564 } 565 } 566 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 567 568 // Service Connection to remote media container service to copy 569 // package uri's from external media onto secure containers 570 // or internal storage. 571 private IMediaContainerService mContainerService = null; 572 573 static final int SEND_PENDING_BROADCAST = 1; 574 static final int MCS_BOUND = 3; 575 static final int END_COPY = 4; 576 static final int INIT_COPY = 5; 577 static final int MCS_UNBIND = 6; 578 static final int START_CLEANING_PACKAGE = 7; 579 static final int FIND_INSTALL_LOC = 8; 580 static final int POST_INSTALL = 9; 581 static final int MCS_RECONNECT = 10; 582 static final int MCS_GIVE_UP = 11; 583 static final int UPDATED_MEDIA_STATUS = 12; 584 static final int WRITE_SETTINGS = 13; 585 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 586 static final int PACKAGE_VERIFIED = 15; 587 static final int CHECK_PENDING_VERIFICATION = 16; 588 589 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 590 591 // Delay time in millisecs 592 static final int BROADCAST_DELAY = 10 * 1000; 593 594 static UserManagerService sUserManager; 595 596 // Stores a list of users whose package restrictions file needs to be updated 597 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 598 599 final private DefaultContainerConnection mDefContainerConn = 600 new DefaultContainerConnection(); 601 class DefaultContainerConnection implements ServiceConnection { 602 public void onServiceConnected(ComponentName name, IBinder service) { 603 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 604 IMediaContainerService imcs = 605 IMediaContainerService.Stub.asInterface(service); 606 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 607 } 608 609 public void onServiceDisconnected(ComponentName name) { 610 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 611 } 612 }; 613 614 // Recordkeeping of restore-after-install operations that are currently in flight 615 // between the Package Manager and the Backup Manager 616 class PostInstallData { 617 public InstallArgs args; 618 public PackageInstalledInfo res; 619 620 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 621 args = _a; 622 res = _r; 623 } 624 }; 625 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 626 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 627 628 private final String mRequiredVerifierPackage; 629 630 private final PackageUsage mPackageUsage = new PackageUsage(); 631 632 private class PackageUsage { 633 private static final int WRITE_INTERVAL 634 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 635 636 private final Object mFileLock = new Object(); 637 private final AtomicLong mLastWritten = new AtomicLong(0); 638 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 639 640 private boolean mIsHistoricalPackageUsageAvailable = true; 641 642 boolean isHistoricalPackageUsageAvailable() { 643 return mIsHistoricalPackageUsageAvailable; 644 } 645 646 void write(boolean force) { 647 if (force) { 648 writeInternal(); 649 return; 650 } 651 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 652 && !DEBUG_DEXOPT) { 653 return; 654 } 655 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 656 new Thread("PackageUsage_DiskWriter") { 657 @Override 658 public void run() { 659 try { 660 writeInternal(); 661 } finally { 662 mBackgroundWriteRunning.set(false); 663 } 664 } 665 }.start(); 666 } 667 } 668 669 private void writeInternal() { 670 synchronized (mPackages) { 671 synchronized (mFileLock) { 672 AtomicFile file = getFile(); 673 FileOutputStream f = null; 674 try { 675 f = file.startWrite(); 676 BufferedOutputStream out = new BufferedOutputStream(f); 677 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 678 StringBuilder sb = new StringBuilder(); 679 for (PackageParser.Package pkg : mPackages.values()) { 680 if (pkg.mLastPackageUsageTimeInMills == 0) { 681 continue; 682 } 683 sb.setLength(0); 684 sb.append(pkg.packageName); 685 sb.append(' '); 686 sb.append((long)pkg.mLastPackageUsageTimeInMills); 687 sb.append('\n'); 688 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 689 } 690 out.flush(); 691 file.finishWrite(f); 692 } catch (IOException e) { 693 if (f != null) { 694 file.failWrite(f); 695 } 696 Log.e(TAG, "Failed to write package usage times", e); 697 } 698 } 699 } 700 mLastWritten.set(SystemClock.elapsedRealtime()); 701 } 702 703 void readLP() { 704 synchronized (mFileLock) { 705 AtomicFile file = getFile(); 706 BufferedInputStream in = null; 707 try { 708 in = new BufferedInputStream(file.openRead()); 709 StringBuffer sb = new StringBuffer(); 710 while (true) { 711 String packageName = readToken(in, sb, ' '); 712 if (packageName == null) { 713 break; 714 } 715 String timeInMillisString = readToken(in, sb, '\n'); 716 if (timeInMillisString == null) { 717 throw new IOException("Failed to find last usage time for package " 718 + packageName); 719 } 720 PackageParser.Package pkg = mPackages.get(packageName); 721 if (pkg == null) { 722 continue; 723 } 724 long timeInMillis; 725 try { 726 timeInMillis = Long.parseLong(timeInMillisString.toString()); 727 } catch (NumberFormatException e) { 728 throw new IOException("Failed to parse " + timeInMillisString 729 + " as a long.", e); 730 } 731 pkg.mLastPackageUsageTimeInMills = timeInMillis; 732 } 733 } catch (FileNotFoundException expected) { 734 mIsHistoricalPackageUsageAvailable = false; 735 } catch (IOException e) { 736 Log.w(TAG, "Failed to read package usage times", e); 737 } finally { 738 IoUtils.closeQuietly(in); 739 } 740 } 741 mLastWritten.set(SystemClock.elapsedRealtime()); 742 } 743 744 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 745 throws IOException { 746 sb.setLength(0); 747 while (true) { 748 int ch = in.read(); 749 if (ch == -1) { 750 if (sb.length() == 0) { 751 return null; 752 } 753 throw new IOException("Unexpected EOF"); 754 } 755 if (ch == endOfToken) { 756 return sb.toString(); 757 } 758 sb.append((char)ch); 759 } 760 } 761 762 private AtomicFile getFile() { 763 File dataDir = Environment.getDataDirectory(); 764 File systemDir = new File(dataDir, "system"); 765 File fname = new File(systemDir, "package-usage.list"); 766 return new AtomicFile(fname); 767 } 768 } 769 770 class PackageHandler extends Handler { 771 private boolean mBound = false; 772 final ArrayList<HandlerParams> mPendingInstalls = 773 new ArrayList<HandlerParams>(); 774 775 private boolean connectToService() { 776 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 777 " DefaultContainerService"); 778 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 779 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 780 if (mContext.bindServiceAsUser(service, mDefContainerConn, 781 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 782 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 783 mBound = true; 784 return true; 785 } 786 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 787 return false; 788 } 789 790 private void disconnectService() { 791 mContainerService = null; 792 mBound = false; 793 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 794 mContext.unbindService(mDefContainerConn); 795 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 796 } 797 798 PackageHandler(Looper looper) { 799 super(looper); 800 } 801 802 public void handleMessage(Message msg) { 803 try { 804 doHandleMessage(msg); 805 } finally { 806 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 807 } 808 } 809 810 void doHandleMessage(Message msg) { 811 switch (msg.what) { 812 case INIT_COPY: { 813 HandlerParams params = (HandlerParams) msg.obj; 814 int idx = mPendingInstalls.size(); 815 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 816 // If a bind was already initiated we dont really 817 // need to do anything. The pending install 818 // will be processed later on. 819 if (!mBound) { 820 // If this is the only one pending we might 821 // have to bind to the service again. 822 if (!connectToService()) { 823 Slog.e(TAG, "Failed to bind to media container service"); 824 params.serviceError(); 825 return; 826 } else { 827 // Once we bind to the service, the first 828 // pending request will be processed. 829 mPendingInstalls.add(idx, params); 830 } 831 } else { 832 mPendingInstalls.add(idx, params); 833 // Already bound to the service. Just make 834 // sure we trigger off processing the first request. 835 if (idx == 0) { 836 mHandler.sendEmptyMessage(MCS_BOUND); 837 } 838 } 839 break; 840 } 841 case MCS_BOUND: { 842 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 843 if (msg.obj != null) { 844 mContainerService = (IMediaContainerService) msg.obj; 845 } 846 if (mContainerService == null) { 847 // Something seriously wrong. Bail out 848 Slog.e(TAG, "Cannot bind to media container service"); 849 for (HandlerParams params : mPendingInstalls) { 850 // Indicate service bind error 851 params.serviceError(); 852 } 853 mPendingInstalls.clear(); 854 } else if (mPendingInstalls.size() > 0) { 855 HandlerParams params = mPendingInstalls.get(0); 856 if (params != null) { 857 if (params.startCopy()) { 858 // We are done... look for more work or to 859 // go idle. 860 if (DEBUG_SD_INSTALL) Log.i(TAG, 861 "Checking for more work or unbind..."); 862 // Delete pending install 863 if (mPendingInstalls.size() > 0) { 864 mPendingInstalls.remove(0); 865 } 866 if (mPendingInstalls.size() == 0) { 867 if (mBound) { 868 if (DEBUG_SD_INSTALL) Log.i(TAG, 869 "Posting delayed MCS_UNBIND"); 870 removeMessages(MCS_UNBIND); 871 Message ubmsg = obtainMessage(MCS_UNBIND); 872 // Unbind after a little delay, to avoid 873 // continual thrashing. 874 sendMessageDelayed(ubmsg, 10000); 875 } 876 } else { 877 // There are more pending requests in queue. 878 // Just post MCS_BOUND message to trigger processing 879 // of next pending install. 880 if (DEBUG_SD_INSTALL) Log.i(TAG, 881 "Posting MCS_BOUND for next work"); 882 mHandler.sendEmptyMessage(MCS_BOUND); 883 } 884 } 885 } 886 } else { 887 // Should never happen ideally. 888 Slog.w(TAG, "Empty queue"); 889 } 890 break; 891 } 892 case MCS_RECONNECT: { 893 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 894 if (mPendingInstalls.size() > 0) { 895 if (mBound) { 896 disconnectService(); 897 } 898 if (!connectToService()) { 899 Slog.e(TAG, "Failed to bind to media container service"); 900 for (HandlerParams params : mPendingInstalls) { 901 // Indicate service bind error 902 params.serviceError(); 903 } 904 mPendingInstalls.clear(); 905 } 906 } 907 break; 908 } 909 case MCS_UNBIND: { 910 // If there is no actual work left, then time to unbind. 911 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 912 913 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 914 if (mBound) { 915 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 916 917 disconnectService(); 918 } 919 } else if (mPendingInstalls.size() > 0) { 920 // There are more pending requests in queue. 921 // Just post MCS_BOUND message to trigger processing 922 // of next pending install. 923 mHandler.sendEmptyMessage(MCS_BOUND); 924 } 925 926 break; 927 } 928 case MCS_GIVE_UP: { 929 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 930 mPendingInstalls.remove(0); 931 break; 932 } 933 case SEND_PENDING_BROADCAST: { 934 String packages[]; 935 ArrayList<String> components[]; 936 int size = 0; 937 int uids[]; 938 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 939 synchronized (mPackages) { 940 if (mPendingBroadcasts == null) { 941 return; 942 } 943 size = mPendingBroadcasts.size(); 944 if (size <= 0) { 945 // Nothing to be done. Just return 946 return; 947 } 948 packages = new String[size]; 949 components = new ArrayList[size]; 950 uids = new int[size]; 951 int i = 0; // filling out the above arrays 952 953 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 954 int packageUserId = mPendingBroadcasts.userIdAt(n); 955 Iterator<Map.Entry<String, ArrayList<String>>> it 956 = mPendingBroadcasts.packagesForUserId(packageUserId) 957 .entrySet().iterator(); 958 while (it.hasNext() && i < size) { 959 Map.Entry<String, ArrayList<String>> ent = it.next(); 960 packages[i] = ent.getKey(); 961 components[i] = ent.getValue(); 962 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 963 uids[i] = (ps != null) 964 ? UserHandle.getUid(packageUserId, ps.appId) 965 : -1; 966 i++; 967 } 968 } 969 size = i; 970 mPendingBroadcasts.clear(); 971 } 972 // Send broadcasts 973 for (int i = 0; i < size; i++) { 974 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 975 } 976 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 977 break; 978 } 979 case START_CLEANING_PACKAGE: { 980 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 981 final String packageName = (String)msg.obj; 982 final int userId = msg.arg1; 983 final boolean andCode = msg.arg2 != 0; 984 synchronized (mPackages) { 985 if (userId == UserHandle.USER_ALL) { 986 int[] users = sUserManager.getUserIds(); 987 for (int user : users) { 988 mSettings.addPackageToCleanLPw( 989 new PackageCleanItem(user, packageName, andCode)); 990 } 991 } else { 992 mSettings.addPackageToCleanLPw( 993 new PackageCleanItem(userId, packageName, andCode)); 994 } 995 } 996 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 997 startCleaningPackages(); 998 } break; 999 case POST_INSTALL: { 1000 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1001 PostInstallData data = mRunningInstalls.get(msg.arg1); 1002 mRunningInstalls.delete(msg.arg1); 1003 boolean deleteOld = false; 1004 1005 if (data != null) { 1006 InstallArgs args = data.args; 1007 PackageInstalledInfo res = data.res; 1008 1009 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1010 res.removedInfo.sendBroadcast(false, true, false); 1011 Bundle extras = new Bundle(1); 1012 extras.putInt(Intent.EXTRA_UID, res.uid); 1013 // Determine the set of users who are adding this 1014 // package for the first time vs. those who are seeing 1015 // an update. 1016 int[] firstUsers; 1017 int[] updateUsers = new int[0]; 1018 if (res.origUsers == null || res.origUsers.length == 0) { 1019 firstUsers = res.newUsers; 1020 } else { 1021 firstUsers = new int[0]; 1022 for (int i=0; i<res.newUsers.length; i++) { 1023 int user = res.newUsers[i]; 1024 boolean isNew = true; 1025 for (int j=0; j<res.origUsers.length; j++) { 1026 if (res.origUsers[j] == user) { 1027 isNew = false; 1028 break; 1029 } 1030 } 1031 if (isNew) { 1032 int[] newFirst = new int[firstUsers.length+1]; 1033 System.arraycopy(firstUsers, 0, newFirst, 0, 1034 firstUsers.length); 1035 newFirst[firstUsers.length] = user; 1036 firstUsers = newFirst; 1037 } else { 1038 int[] newUpdate = new int[updateUsers.length+1]; 1039 System.arraycopy(updateUsers, 0, newUpdate, 0, 1040 updateUsers.length); 1041 newUpdate[updateUsers.length] = user; 1042 updateUsers = newUpdate; 1043 } 1044 } 1045 } 1046 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1047 res.pkg.applicationInfo.packageName, 1048 extras, null, null, firstUsers); 1049 final boolean update = res.removedInfo.removedPackage != null; 1050 if (update) { 1051 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1052 } 1053 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1054 res.pkg.applicationInfo.packageName, 1055 extras, null, null, updateUsers); 1056 if (update) { 1057 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1058 res.pkg.applicationInfo.packageName, 1059 extras, null, null, updateUsers); 1060 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1061 null, null, 1062 res.pkg.applicationInfo.packageName, null, updateUsers); 1063 1064 // treat asec-hosted packages like removable media on upgrade 1065 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1066 if (DEBUG_INSTALL) { 1067 Slog.i(TAG, "upgrading pkg " + res.pkg 1068 + " is ASEC-hosted -> AVAILABLE"); 1069 } 1070 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1071 ArrayList<String> pkgList = new ArrayList<String>(1); 1072 pkgList.add(res.pkg.applicationInfo.packageName); 1073 sendResourcesChangedBroadcast(true, true, 1074 pkgList,uidArray, null); 1075 } 1076 } 1077 if (res.removedInfo.args != null) { 1078 // Remove the replaced package's older resources safely now 1079 deleteOld = true; 1080 } 1081 1082 // Log current value of "unknown sources" setting 1083 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1084 getUnknownSourcesSettings()); 1085 } 1086 // Force a gc to clear up things 1087 Runtime.getRuntime().gc(); 1088 // We delete after a gc for applications on sdcard. 1089 if (deleteOld) { 1090 synchronized (mInstallLock) { 1091 res.removedInfo.args.doPostDeleteLI(true); 1092 } 1093 } 1094 if (args.observer != null) { 1095 try { 1096 args.observer.packageInstalled(res.name, res.returnCode); 1097 } catch (RemoteException e) { 1098 Slog.i(TAG, "Observer no longer exists."); 1099 } 1100 } 1101 if (args.observer2 != null) { 1102 try { 1103 Bundle extras = extrasForInstallResult(res); 1104 args.observer2.packageInstalled(res.name, extras, res.returnCode); 1105 } catch (RemoteException e) { 1106 Slog.i(TAG, "Observer no longer exists."); 1107 } 1108 } 1109 } else { 1110 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1111 } 1112 } break; 1113 case UPDATED_MEDIA_STATUS: { 1114 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1115 boolean reportStatus = msg.arg1 == 1; 1116 boolean doGc = msg.arg2 == 1; 1117 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1118 if (doGc) { 1119 // Force a gc to clear up stale containers. 1120 Runtime.getRuntime().gc(); 1121 } 1122 if (msg.obj != null) { 1123 @SuppressWarnings("unchecked") 1124 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1125 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1126 // Unload containers 1127 unloadAllContainers(args); 1128 } 1129 if (reportStatus) { 1130 try { 1131 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1132 PackageHelper.getMountService().finishMediaUpdate(); 1133 } catch (RemoteException e) { 1134 Log.e(TAG, "MountService not running?"); 1135 } 1136 } 1137 } break; 1138 case WRITE_SETTINGS: { 1139 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1140 synchronized (mPackages) { 1141 removeMessages(WRITE_SETTINGS); 1142 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1143 mSettings.writeLPr(); 1144 mDirtyUsers.clear(); 1145 } 1146 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1147 } break; 1148 case WRITE_PACKAGE_RESTRICTIONS: { 1149 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1150 synchronized (mPackages) { 1151 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1152 for (int userId : mDirtyUsers) { 1153 mSettings.writePackageRestrictionsLPr(userId); 1154 } 1155 mDirtyUsers.clear(); 1156 } 1157 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1158 } break; 1159 case CHECK_PENDING_VERIFICATION: { 1160 final int verificationId = msg.arg1; 1161 final PackageVerificationState state = mPendingVerification.get(verificationId); 1162 1163 if ((state != null) && !state.timeoutExtended()) { 1164 final InstallArgs args = state.getInstallArgs(); 1165 final Uri originUri = Uri.fromFile(args.originFile); 1166 1167 Slog.i(TAG, "Verification timed out for " + originUri); 1168 mPendingVerification.remove(verificationId); 1169 1170 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1171 1172 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1173 Slog.i(TAG, "Continuing with installation of " + originUri); 1174 state.setVerifierResponse(Binder.getCallingUid(), 1175 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1176 broadcastPackageVerified(verificationId, originUri, 1177 PackageManager.VERIFICATION_ALLOW, 1178 state.getInstallArgs().getUser()); 1179 try { 1180 ret = args.copyApk(mContainerService, true); 1181 } catch (RemoteException e) { 1182 Slog.e(TAG, "Could not contact the ContainerService"); 1183 } 1184 } else { 1185 broadcastPackageVerified(verificationId, originUri, 1186 PackageManager.VERIFICATION_REJECT, 1187 state.getInstallArgs().getUser()); 1188 } 1189 1190 processPendingInstall(args, ret); 1191 mHandler.sendEmptyMessage(MCS_UNBIND); 1192 } 1193 break; 1194 } 1195 case PACKAGE_VERIFIED: { 1196 final int verificationId = msg.arg1; 1197 1198 final PackageVerificationState state = mPendingVerification.get(verificationId); 1199 if (state == null) { 1200 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1201 break; 1202 } 1203 1204 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1205 1206 state.setVerifierResponse(response.callerUid, response.code); 1207 1208 if (state.isVerificationComplete()) { 1209 mPendingVerification.remove(verificationId); 1210 1211 final InstallArgs args = state.getInstallArgs(); 1212 final Uri originUri = Uri.fromFile(args.originFile); 1213 1214 int ret; 1215 if (state.isInstallAllowed()) { 1216 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1217 broadcastPackageVerified(verificationId, originUri, 1218 response.code, state.getInstallArgs().getUser()); 1219 try { 1220 ret = args.copyApk(mContainerService, true); 1221 } catch (RemoteException e) { 1222 Slog.e(TAG, "Could not contact the ContainerService"); 1223 } 1224 } else { 1225 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1226 } 1227 1228 processPendingInstall(args, ret); 1229 1230 mHandler.sendEmptyMessage(MCS_UNBIND); 1231 } 1232 1233 break; 1234 } 1235 } 1236 } 1237 } 1238 1239 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1240 Bundle extras = null; 1241 switch (res.returnCode) { 1242 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1243 extras = new Bundle(); 1244 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1245 res.origPermission); 1246 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1247 res.origPackage); 1248 break; 1249 } 1250 } 1251 return extras; 1252 } 1253 1254 void scheduleWriteSettingsLocked() { 1255 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1256 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1257 } 1258 } 1259 1260 void scheduleWritePackageRestrictionsLocked(int userId) { 1261 if (!sUserManager.exists(userId)) return; 1262 mDirtyUsers.add(userId); 1263 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1264 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1265 } 1266 } 1267 1268 public static final PackageManagerService main(Context context, Installer installer, 1269 boolean factoryTest, boolean onlyCore) { 1270 PackageManagerService m = new PackageManagerService(context, installer, 1271 factoryTest, onlyCore); 1272 ServiceManager.addService("package", m); 1273 return m; 1274 } 1275 1276 static String[] splitString(String str, char sep) { 1277 int count = 1; 1278 int i = 0; 1279 while ((i=str.indexOf(sep, i)) >= 0) { 1280 count++; 1281 i++; 1282 } 1283 1284 String[] res = new String[count]; 1285 i=0; 1286 count = 0; 1287 int lastI=0; 1288 while ((i=str.indexOf(sep, i)) >= 0) { 1289 res[count] = str.substring(lastI, i); 1290 count++; 1291 i++; 1292 lastI = i; 1293 } 1294 res[count] = str.substring(lastI, str.length()); 1295 return res; 1296 } 1297 1298 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1299 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1300 Context.DISPLAY_SERVICE); 1301 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1302 } 1303 1304 public PackageManagerService(Context context, Installer installer, 1305 boolean factoryTest, boolean onlyCore) { 1306 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1307 SystemClock.uptimeMillis()); 1308 1309 if (mSdkVersion <= 0) { 1310 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1311 } 1312 1313 mContext = context; 1314 mFactoryTest = factoryTest; 1315 mOnlyCore = onlyCore; 1316 mMetrics = new DisplayMetrics(); 1317 mSettings = new Settings(context); 1318 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1319 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1320 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1321 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1322 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1323 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1324 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1325 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1326 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1327 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1328 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1329 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1330 1331 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1332 if (separateProcesses != null && separateProcesses.length() > 0) { 1333 if ("*".equals(separateProcesses)) { 1334 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1335 mSeparateProcesses = null; 1336 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1337 } else { 1338 mDefParseFlags = 0; 1339 mSeparateProcesses = separateProcesses.split(","); 1340 Slog.w(TAG, "Running with debug.separate_processes: " 1341 + separateProcesses); 1342 } 1343 } else { 1344 mDefParseFlags = 0; 1345 mSeparateProcesses = null; 1346 } 1347 1348 mInstaller = installer; 1349 1350 getDefaultDisplayMetrics(context, mMetrics); 1351 1352 SystemConfig systemConfig = SystemConfig.getInstance(); 1353 mGlobalGids = systemConfig.getGlobalGids(); 1354 mSystemPermissions = systemConfig.getSystemPermissions(); 1355 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1356 1357 synchronized (mInstallLock) { 1358 // writer 1359 synchronized (mPackages) { 1360 mHandlerThread = new ServiceThread(TAG, 1361 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1362 mHandlerThread.start(); 1363 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1364 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1365 1366 File dataDir = Environment.getDataDirectory(); 1367 mAppDataDir = new File(dataDir, "data"); 1368 mAppInstallDir = new File(dataDir, "app"); 1369 mAppLibInstallDir = new File(dataDir, "app-lib"); 1370 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1371 mUserAppDataDir = new File(dataDir, "user"); 1372 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1373 mAppStagingDir = new File(dataDir, "app-staging"); 1374 1375 sUserManager = new UserManagerService(context, this, 1376 mInstallLock, mPackages); 1377 1378 // Propagate permission configuration in to package manager. 1379 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1380 = systemConfig.getPermissions(); 1381 for (int i=0; i<permConfig.size(); i++) { 1382 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1383 BasePermission bp = mSettings.mPermissions.get(perm.name); 1384 if (bp == null) { 1385 bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN); 1386 mSettings.mPermissions.put(perm.name, bp); 1387 } 1388 if (perm.gids != null) { 1389 bp.gids = appendInts(bp.gids, perm.gids); 1390 } 1391 } 1392 1393 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1394 for (int i=0; i<libConfig.size(); i++) { 1395 mSharedLibraries.put(libConfig.keyAt(i), 1396 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1397 } 1398 1399 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1400 1401 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1402 mSdkVersion, mOnlyCore); 1403 1404 String customResolverActivity = Resources.getSystem().getString( 1405 R.string.config_customResolverActivity); 1406 if (TextUtils.isEmpty(customResolverActivity)) { 1407 customResolverActivity = null; 1408 } else { 1409 mCustomResolverComponentName = ComponentName.unflattenFromString( 1410 customResolverActivity); 1411 } 1412 1413 long startTime = SystemClock.uptimeMillis(); 1414 1415 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1416 startTime); 1417 1418 // Set flag to monitor and not change apk file paths when 1419 // scanning install directories. 1420 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1421 1422 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1423 1424 /** 1425 * Add everything in the in the boot class path to the 1426 * list of process files because dexopt will have been run 1427 * if necessary during zygote startup. 1428 */ 1429 String bootClassPath = System.getProperty("java.boot.class.path"); 1430 if (bootClassPath != null) { 1431 String[] paths = splitString(bootClassPath, ':'); 1432 for (int i=0; i<paths.length; i++) { 1433 alreadyDexOpted.add(paths[i]); 1434 } 1435 } else { 1436 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1437 } 1438 1439 boolean didDexOptLibraryOrTool = false; 1440 1441 final List<String> instructionSets = getAllInstructionSets(); 1442 1443 /** 1444 * Ensure all external libraries have had dexopt run on them. 1445 */ 1446 if (mSharedLibraries.size() > 0) { 1447 // NOTE: For now, we're compiling these system "shared libraries" 1448 // (and framework jars) into all available architectures. It's possible 1449 // to compile them only when we come across an app that uses them (there's 1450 // already logic for that in scanPackageLI) but that adds some complexity. 1451 for (String instructionSet : instructionSets) { 1452 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1453 final String lib = libEntry.path; 1454 if (lib == null) { 1455 continue; 1456 } 1457 1458 try { 1459 if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) { 1460 alreadyDexOpted.add(lib); 1461 1462 // The list of "shared libraries" we have at this point is 1463 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet); 1464 didDexOptLibraryOrTool = true; 1465 } 1466 } catch (FileNotFoundException e) { 1467 Slog.w(TAG, "Library not found: " + lib); 1468 } catch (IOException e) { 1469 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1470 + e.getMessage()); 1471 } 1472 } 1473 } 1474 } 1475 1476 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1477 1478 // Gross hack for now: we know this file doesn't contain any 1479 // code, so don't dexopt it to avoid the resulting log spew. 1480 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1481 1482 // Gross hack for now: we know this file is only part of 1483 // the boot class path for art, so don't dexopt it to 1484 // avoid the resulting log spew. 1485 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1486 1487 /** 1488 * And there are a number of commands implemented in Java, which 1489 * we currently need to do the dexopt on so that they can be 1490 * run from a non-root shell. 1491 */ 1492 String[] frameworkFiles = frameworkDir.list(); 1493 if (frameworkFiles != null) { 1494 // TODO: We could compile these only for the most preferred ABI. We should 1495 // first double check that the dex files for these commands are not referenced 1496 // by other system apps. 1497 for (String instructionSet : instructionSets) { 1498 for (int i=0; i<frameworkFiles.length; i++) { 1499 File libPath = new File(frameworkDir, frameworkFiles[i]); 1500 String path = libPath.getPath(); 1501 // Skip the file if we already did it. 1502 if (alreadyDexOpted.contains(path)) { 1503 continue; 1504 } 1505 // Skip the file if it is not a type we want to dexopt. 1506 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1507 continue; 1508 } 1509 try { 1510 if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) { 1511 mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet); 1512 didDexOptLibraryOrTool = true; 1513 } 1514 } catch (FileNotFoundException e) { 1515 Slog.w(TAG, "Jar not found: " + path); 1516 } catch (IOException e) { 1517 Slog.w(TAG, "Exception reading jar: " + path, e); 1518 } 1519 } 1520 } 1521 } 1522 1523 if (didDexOptLibraryOrTool) { 1524 // If we dexopted a library or tool, then something on the system has 1525 // changed. Consider this significant, and wipe away all other 1526 // existing dexopt files to ensure we don't leave any dangling around. 1527 // 1528 // TODO: This should be revisited because it isn't as good an indicator 1529 // as it used to be. It used to include the boot classpath but at some point 1530 // DexFile.isDexOptNeeded started returning false for the boot 1531 // class path files in all cases. It is very possible in a 1532 // small maintenance release update that the library and tool 1533 // jars may be unchanged but APK could be removed resulting in 1534 // unused dalvik-cache files. 1535 for (String instructionSet : instructionSets) { 1536 mInstaller.pruneDexCache(instructionSet); 1537 } 1538 1539 // Additionally, delete all dex files from the root directory 1540 // since there shouldn't be any there anyway, unless we're upgrading 1541 // from an older OS version or a build that contained the "old" style 1542 // flat scheme. 1543 mInstaller.pruneDexCache("."); 1544 } 1545 1546 // Collect vendor overlay packages. 1547 // (Do this before scanning any apps.) 1548 // For security and version matching reason, only consider 1549 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1550 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1551 mVendorOverlayInstallObserver = new AppDirObserver( 1552 vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false); 1553 mVendorOverlayInstallObserver.startWatching(); 1554 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1555 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1556 1557 // Find base frameworks (resource packages without code). 1558 mFrameworkInstallObserver = new AppDirObserver( 1559 frameworkDir.getPath(), OBSERVER_EVENTS, true, false); 1560 mFrameworkInstallObserver.startWatching(); 1561 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1562 | PackageParser.PARSE_IS_SYSTEM_DIR 1563 | PackageParser.PARSE_IS_PRIVILEGED, 1564 scanMode | SCAN_NO_DEX, 0); 1565 1566 // Collected privileged system packages. 1567 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1568 mPrivilegedInstallObserver = new AppDirObserver( 1569 privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true); 1570 mPrivilegedInstallObserver.startWatching(); 1571 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1572 | PackageParser.PARSE_IS_SYSTEM_DIR 1573 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1574 1575 // Collect ordinary system packages. 1576 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1577 mSystemInstallObserver = new AppDirObserver( 1578 systemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1579 mSystemInstallObserver.startWatching(); 1580 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1581 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1582 1583 // Collect all vendor packages. 1584 File vendorAppDir = new File("/vendor/app"); 1585 try { 1586 vendorAppDir = vendorAppDir.getCanonicalFile(); 1587 } catch (IOException e) { 1588 // failed to look up canonical path, continue with original one 1589 } 1590 mVendorInstallObserver = new AppDirObserver( 1591 vendorAppDir.getPath(), OBSERVER_EVENTS, true, false); 1592 mVendorInstallObserver.startWatching(); 1593 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1594 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1595 1596 // Collect all OEM packages. 1597 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1598 mOemInstallObserver = new AppDirObserver( 1599 oemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1600 mOemInstallObserver.startWatching(); 1601 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1602 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1603 1604 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1605 mInstaller.moveFiles(); 1606 1607 // Prune any system packages that no longer exist. 1608 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1609 if (!mOnlyCore) { 1610 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1611 while (psit.hasNext()) { 1612 PackageSetting ps = psit.next(); 1613 1614 /* 1615 * If this is not a system app, it can't be a 1616 * disable system app. 1617 */ 1618 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1619 continue; 1620 } 1621 1622 /* 1623 * If the package is scanned, it's not erased. 1624 */ 1625 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1626 if (scannedPkg != null) { 1627 /* 1628 * If the system app is both scanned and in the 1629 * disabled packages list, then it must have been 1630 * added via OTA. Remove it from the currently 1631 * scanned package so the previously user-installed 1632 * application can be scanned. 1633 */ 1634 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1635 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1636 + "; removing system app"); 1637 removePackageLI(ps, true); 1638 } 1639 1640 continue; 1641 } 1642 1643 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1644 psit.remove(); 1645 String msg = "System package " + ps.name 1646 + " no longer exists; wiping its data"; 1647 reportSettingsProblem(Log.WARN, msg); 1648 removeDataDirsLI(ps.name); 1649 } else { 1650 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1651 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1652 possiblyDeletedUpdatedSystemApps.add(ps.name); 1653 } 1654 } 1655 } 1656 } 1657 1658 //look for any incomplete package installations 1659 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1660 //clean up list 1661 for(int i = 0; i < deletePkgsList.size(); i++) { 1662 //clean up here 1663 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1664 } 1665 //delete tmp files 1666 deleteTempPackageFiles(); 1667 1668 // Remove any shared userIDs that have no associated packages 1669 mSettings.pruneSharedUsersLPw(); 1670 1671 if (!mOnlyCore) { 1672 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1673 SystemClock.uptimeMillis()); 1674 mAppInstallObserver = new AppDirObserver( 1675 mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1676 mAppInstallObserver.startWatching(); 1677 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1678 1679 mDrmAppInstallObserver = new AppDirObserver( 1680 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1681 mDrmAppInstallObserver.startWatching(); 1682 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1683 scanMode, 0); 1684 1685 /** 1686 * Remove disable package settings for any updated system 1687 * apps that were removed via an OTA. If they're not a 1688 * previously-updated app, remove them completely. 1689 * Otherwise, just revoke their system-level permissions. 1690 */ 1691 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1692 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1693 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1694 1695 String msg; 1696 if (deletedPkg == null) { 1697 msg = "Updated system package " + deletedAppName 1698 + " no longer exists; wiping its data"; 1699 removeDataDirsLI(deletedAppName); 1700 } else { 1701 msg = "Updated system app + " + deletedAppName 1702 + " no longer present; removing system privileges for " 1703 + deletedAppName; 1704 1705 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1706 1707 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1708 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1709 } 1710 reportSettingsProblem(Log.WARN, msg); 1711 } 1712 } else { 1713 mAppInstallObserver = null; 1714 mDrmAppInstallObserver = null; 1715 } 1716 1717 // Now that we know all of the shared libraries, update all clients to have 1718 // the correct library paths. 1719 updateAllSharedLibrariesLPw(); 1720 1721 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1722 // NOTE: We ignore potential failures here during a system scan (like 1723 // the rest of the commands above) because there's precious little we 1724 // can do about it. A settings error is reported, though. 1725 adjustCpuAbisForSharedUserLPw(setting.packages, null, 1726 false /* force dexopt */, false /* defer dexopt */); 1727 } 1728 1729 // Now that we know all the packages we are keeping, 1730 // read and update their last usage times. 1731 mPackageUsage.readLP(); 1732 1733 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1734 SystemClock.uptimeMillis()); 1735 Slog.i(TAG, "Time to scan packages: " 1736 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1737 + " seconds"); 1738 1739 // If the platform SDK has changed since the last time we booted, 1740 // we need to re-grant app permission to catch any new ones that 1741 // appear. This is really a hack, and means that apps can in some 1742 // cases get permissions that the user didn't initially explicitly 1743 // allow... it would be nice to have some better way to handle 1744 // this situation. 1745 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1746 != mSdkVersion; 1747 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1748 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1749 + "; regranting permissions for internal storage"); 1750 mSettings.mInternalSdkPlatform = mSdkVersion; 1751 1752 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1753 | (regrantPermissions 1754 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1755 : 0)); 1756 1757 // If this is the first boot, and it is a normal boot, then 1758 // we need to initialize the default preferred apps. 1759 if (!mRestoredSettings && !onlyCore) { 1760 mSettings.readDefaultPreferredAppsLPw(this, 0); 1761 } 1762 1763 // All the changes are done during package scanning. 1764 mSettings.updateInternalDatabaseVersion(); 1765 1766 // can downgrade to reader 1767 mSettings.writeLPr(); 1768 1769 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1770 SystemClock.uptimeMillis()); 1771 1772 1773 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1774 } // synchronized (mPackages) 1775 } // synchronized (mInstallLock) 1776 1777 mInstallerService = new PackageInstallerService(context, this, mAppStagingDir); 1778 1779 // Now after opening every single application zip, make sure they 1780 // are all flushed. Not really needed, but keeps things nice and 1781 // tidy. 1782 Runtime.getRuntime().gc(); 1783 } 1784 1785 @Override 1786 public boolean isFirstBoot() { 1787 return !mRestoredSettings; 1788 } 1789 1790 @Override 1791 public boolean isOnlyCoreApps() { 1792 return mOnlyCore; 1793 } 1794 1795 private String getRequiredVerifierLPr() { 1796 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1797 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1798 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1799 1800 String requiredVerifier = null; 1801 1802 final int N = receivers.size(); 1803 for (int i = 0; i < N; i++) { 1804 final ResolveInfo info = receivers.get(i); 1805 1806 if (info.activityInfo == null) { 1807 continue; 1808 } 1809 1810 final String packageName = info.activityInfo.packageName; 1811 1812 final PackageSetting ps = mSettings.mPackages.get(packageName); 1813 if (ps == null) { 1814 continue; 1815 } 1816 1817 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1818 if (!gp.grantedPermissions 1819 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1820 continue; 1821 } 1822 1823 if (requiredVerifier != null) { 1824 throw new RuntimeException("There can be only one required verifier"); 1825 } 1826 1827 requiredVerifier = packageName; 1828 } 1829 1830 return requiredVerifier; 1831 } 1832 1833 @Override 1834 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1835 throws RemoteException { 1836 try { 1837 return super.onTransact(code, data, reply, flags); 1838 } catch (RuntimeException e) { 1839 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1840 Slog.wtf(TAG, "Package Manager Crash", e); 1841 } 1842 throw e; 1843 } 1844 } 1845 1846 void cleanupInstallFailedPackage(PackageSetting ps) { 1847 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1848 removeDataDirsLI(ps.name); 1849 1850 // TODO: try cleaning up codePath directory contents first, since it 1851 // might be a cluster 1852 1853 if (ps.codePath != null) { 1854 if (!ps.codePath.delete()) { 1855 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1856 } 1857 } 1858 if (ps.resourcePath != null) { 1859 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1860 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1861 } 1862 } 1863 mSettings.removePackageLPw(ps.name); 1864 } 1865 1866 static int[] appendInts(int[] cur, int[] add) { 1867 if (add == null) return cur; 1868 if (cur == null) return add; 1869 final int N = add.length; 1870 for (int i=0; i<N; i++) { 1871 cur = appendInt(cur, add[i]); 1872 } 1873 return cur; 1874 } 1875 1876 static int[] removeInts(int[] cur, int[] rem) { 1877 if (rem == null) return cur; 1878 if (cur == null) return cur; 1879 final int N = rem.length; 1880 for (int i=0; i<N; i++) { 1881 cur = removeInt(cur, rem[i]); 1882 } 1883 return cur; 1884 } 1885 1886 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1887 if (!sUserManager.exists(userId)) return null; 1888 final PackageSetting ps = (PackageSetting) p.mExtras; 1889 if (ps == null) { 1890 return null; 1891 } 1892 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1893 final PackageUserState state = ps.readUserState(userId); 1894 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1895 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1896 state, userId); 1897 } 1898 1899 @Override 1900 public boolean isPackageAvailable(String packageName, int userId) { 1901 if (!sUserManager.exists(userId)) return false; 1902 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1903 synchronized (mPackages) { 1904 PackageParser.Package p = mPackages.get(packageName); 1905 if (p != null) { 1906 final PackageSetting ps = (PackageSetting) p.mExtras; 1907 if (ps != null) { 1908 final PackageUserState state = ps.readUserState(userId); 1909 if (state != null) { 1910 return PackageParser.isAvailable(state); 1911 } 1912 } 1913 } 1914 } 1915 return false; 1916 } 1917 1918 @Override 1919 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1920 if (!sUserManager.exists(userId)) return null; 1921 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1922 // reader 1923 synchronized (mPackages) { 1924 PackageParser.Package p = mPackages.get(packageName); 1925 if (DEBUG_PACKAGE_INFO) 1926 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1927 if (p != null) { 1928 return generatePackageInfo(p, flags, userId); 1929 } 1930 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1931 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1932 } 1933 } 1934 return null; 1935 } 1936 1937 @Override 1938 public String[] currentToCanonicalPackageNames(String[] names) { 1939 String[] out = new String[names.length]; 1940 // reader 1941 synchronized (mPackages) { 1942 for (int i=names.length-1; i>=0; i--) { 1943 PackageSetting ps = mSettings.mPackages.get(names[i]); 1944 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1945 } 1946 } 1947 return out; 1948 } 1949 1950 @Override 1951 public String[] canonicalToCurrentPackageNames(String[] names) { 1952 String[] out = new String[names.length]; 1953 // reader 1954 synchronized (mPackages) { 1955 for (int i=names.length-1; i>=0; i--) { 1956 String cur = mSettings.mRenamedPackages.get(names[i]); 1957 out[i] = cur != null ? cur : names[i]; 1958 } 1959 } 1960 return out; 1961 } 1962 1963 @Override 1964 public int getPackageUid(String packageName, int userId) { 1965 if (!sUserManager.exists(userId)) return -1; 1966 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1967 // reader 1968 synchronized (mPackages) { 1969 PackageParser.Package p = mPackages.get(packageName); 1970 if(p != null) { 1971 return UserHandle.getUid(userId, p.applicationInfo.uid); 1972 } 1973 PackageSetting ps = mSettings.mPackages.get(packageName); 1974 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1975 return -1; 1976 } 1977 p = ps.pkg; 1978 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1979 } 1980 } 1981 1982 @Override 1983 public int[] getPackageGids(String packageName) { 1984 // reader 1985 synchronized (mPackages) { 1986 PackageParser.Package p = mPackages.get(packageName); 1987 if (DEBUG_PACKAGE_INFO) 1988 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1989 if (p != null) { 1990 final PackageSetting ps = (PackageSetting)p.mExtras; 1991 return ps.getGids(); 1992 } 1993 } 1994 // stupid thing to indicate an error. 1995 return new int[0]; 1996 } 1997 1998 static final PermissionInfo generatePermissionInfo( 1999 BasePermission bp, int flags) { 2000 if (bp.perm != null) { 2001 return PackageParser.generatePermissionInfo(bp.perm, flags); 2002 } 2003 PermissionInfo pi = new PermissionInfo(); 2004 pi.name = bp.name; 2005 pi.packageName = bp.sourcePackage; 2006 pi.nonLocalizedLabel = bp.name; 2007 pi.protectionLevel = bp.protectionLevel; 2008 return pi; 2009 } 2010 2011 @Override 2012 public PermissionInfo getPermissionInfo(String name, int flags) { 2013 // reader 2014 synchronized (mPackages) { 2015 final BasePermission p = mSettings.mPermissions.get(name); 2016 if (p != null) { 2017 return generatePermissionInfo(p, flags); 2018 } 2019 return null; 2020 } 2021 } 2022 2023 @Override 2024 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2025 // reader 2026 synchronized (mPackages) { 2027 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2028 for (BasePermission p : mSettings.mPermissions.values()) { 2029 if (group == null) { 2030 if (p.perm == null || p.perm.info.group == null) { 2031 out.add(generatePermissionInfo(p, flags)); 2032 } 2033 } else { 2034 if (p.perm != null && group.equals(p.perm.info.group)) { 2035 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2036 } 2037 } 2038 } 2039 2040 if (out.size() > 0) { 2041 return out; 2042 } 2043 return mPermissionGroups.containsKey(group) ? out : null; 2044 } 2045 } 2046 2047 @Override 2048 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2049 // reader 2050 synchronized (mPackages) { 2051 return PackageParser.generatePermissionGroupInfo( 2052 mPermissionGroups.get(name), flags); 2053 } 2054 } 2055 2056 @Override 2057 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2058 // reader 2059 synchronized (mPackages) { 2060 final int N = mPermissionGroups.size(); 2061 ArrayList<PermissionGroupInfo> out 2062 = new ArrayList<PermissionGroupInfo>(N); 2063 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2064 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2065 } 2066 return out; 2067 } 2068 } 2069 2070 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2071 int userId) { 2072 if (!sUserManager.exists(userId)) return null; 2073 PackageSetting ps = mSettings.mPackages.get(packageName); 2074 if (ps != null) { 2075 if (ps.pkg == null) { 2076 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2077 flags, userId); 2078 if (pInfo != null) { 2079 return pInfo.applicationInfo; 2080 } 2081 return null; 2082 } 2083 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2084 ps.readUserState(userId), userId); 2085 } 2086 return null; 2087 } 2088 2089 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2090 int userId) { 2091 if (!sUserManager.exists(userId)) return null; 2092 PackageSetting ps = mSettings.mPackages.get(packageName); 2093 if (ps != null) { 2094 PackageParser.Package pkg = ps.pkg; 2095 if (pkg == null) { 2096 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2097 return null; 2098 } 2099 // Only data remains, so we aren't worried about code paths 2100 pkg = new PackageParser.Package(packageName); 2101 pkg.applicationInfo.packageName = packageName; 2102 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2103 pkg.applicationInfo.dataDir = 2104 getDataPathForPackage(packageName, 0).getPath(); 2105 pkg.applicationInfo.cpuAbi = ps.cpuAbiString; 2106 } 2107 return generatePackageInfo(pkg, flags, userId); 2108 } 2109 return null; 2110 } 2111 2112 @Override 2113 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2114 if (!sUserManager.exists(userId)) return null; 2115 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2116 // writer 2117 synchronized (mPackages) { 2118 PackageParser.Package p = mPackages.get(packageName); 2119 if (DEBUG_PACKAGE_INFO) Log.v( 2120 TAG, "getApplicationInfo " + packageName 2121 + ": " + p); 2122 if (p != null) { 2123 PackageSetting ps = mSettings.mPackages.get(packageName); 2124 if (ps == null) return null; 2125 // Note: isEnabledLP() does not apply here - always return info 2126 return PackageParser.generateApplicationInfo( 2127 p, flags, ps.readUserState(userId), userId); 2128 } 2129 if ("android".equals(packageName)||"system".equals(packageName)) { 2130 return mAndroidApplication; 2131 } 2132 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2133 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2134 } 2135 } 2136 return null; 2137 } 2138 2139 2140 @Override 2141 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2142 mContext.enforceCallingOrSelfPermission( 2143 android.Manifest.permission.CLEAR_APP_CACHE, null); 2144 // Queue up an async operation since clearing cache may take a little while. 2145 mHandler.post(new Runnable() { 2146 public void run() { 2147 mHandler.removeCallbacks(this); 2148 int retCode = -1; 2149 synchronized (mInstallLock) { 2150 retCode = mInstaller.freeCache(freeStorageSize); 2151 if (retCode < 0) { 2152 Slog.w(TAG, "Couldn't clear application caches"); 2153 } 2154 } 2155 if (observer != null) { 2156 try { 2157 observer.onRemoveCompleted(null, (retCode >= 0)); 2158 } catch (RemoteException e) { 2159 Slog.w(TAG, "RemoveException when invoking call back"); 2160 } 2161 } 2162 } 2163 }); 2164 } 2165 2166 @Override 2167 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2168 mContext.enforceCallingOrSelfPermission( 2169 android.Manifest.permission.CLEAR_APP_CACHE, null); 2170 // Queue up an async operation since clearing cache may take a little while. 2171 mHandler.post(new Runnable() { 2172 public void run() { 2173 mHandler.removeCallbacks(this); 2174 int retCode = -1; 2175 synchronized (mInstallLock) { 2176 retCode = mInstaller.freeCache(freeStorageSize); 2177 if (retCode < 0) { 2178 Slog.w(TAG, "Couldn't clear application caches"); 2179 } 2180 } 2181 if(pi != null) { 2182 try { 2183 // Callback via pending intent 2184 int code = (retCode >= 0) ? 1 : 0; 2185 pi.sendIntent(null, code, null, 2186 null, null); 2187 } catch (SendIntentException e1) { 2188 Slog.i(TAG, "Failed to send pending intent"); 2189 } 2190 } 2191 } 2192 }); 2193 } 2194 2195 void freeStorage(long freeStorageSize) throws IOException { 2196 synchronized (mInstallLock) { 2197 if (mInstaller.freeCache(freeStorageSize) < 0) { 2198 throw new IOException("Failed to free enough space"); 2199 } 2200 } 2201 } 2202 2203 @Override 2204 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2205 if (!sUserManager.exists(userId)) return null; 2206 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2207 synchronized (mPackages) { 2208 PackageParser.Activity a = mActivities.mActivities.get(component); 2209 2210 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2211 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2212 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2213 if (ps == null) return null; 2214 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2215 userId); 2216 } 2217 if (mResolveComponentName.equals(component)) { 2218 return mResolveActivity; 2219 } 2220 } 2221 return null; 2222 } 2223 2224 @Override 2225 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2226 String resolvedType) { 2227 synchronized (mPackages) { 2228 PackageParser.Activity a = mActivities.mActivities.get(component); 2229 if (a == null) { 2230 return false; 2231 } 2232 for (int i=0; i<a.intents.size(); i++) { 2233 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2234 intent.getData(), intent.getCategories(), TAG) >= 0) { 2235 return true; 2236 } 2237 } 2238 return false; 2239 } 2240 } 2241 2242 @Override 2243 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2244 if (!sUserManager.exists(userId)) return null; 2245 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2246 synchronized (mPackages) { 2247 PackageParser.Activity a = mReceivers.mActivities.get(component); 2248 if (DEBUG_PACKAGE_INFO) Log.v( 2249 TAG, "getReceiverInfo " + component + ": " + a); 2250 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2251 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2252 if (ps == null) return null; 2253 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2254 userId); 2255 } 2256 } 2257 return null; 2258 } 2259 2260 @Override 2261 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2262 if (!sUserManager.exists(userId)) return null; 2263 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2264 synchronized (mPackages) { 2265 PackageParser.Service s = mServices.mServices.get(component); 2266 if (DEBUG_PACKAGE_INFO) Log.v( 2267 TAG, "getServiceInfo " + component + ": " + s); 2268 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2269 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2270 if (ps == null) return null; 2271 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2272 userId); 2273 } 2274 } 2275 return null; 2276 } 2277 2278 @Override 2279 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2280 if (!sUserManager.exists(userId)) return null; 2281 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2282 synchronized (mPackages) { 2283 PackageParser.Provider p = mProviders.mProviders.get(component); 2284 if (DEBUG_PACKAGE_INFO) Log.v( 2285 TAG, "getProviderInfo " + component + ": " + p); 2286 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2287 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2288 if (ps == null) return null; 2289 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2290 userId); 2291 } 2292 } 2293 return null; 2294 } 2295 2296 @Override 2297 public String[] getSystemSharedLibraryNames() { 2298 Set<String> libSet; 2299 synchronized (mPackages) { 2300 libSet = mSharedLibraries.keySet(); 2301 int size = libSet.size(); 2302 if (size > 0) { 2303 String[] libs = new String[size]; 2304 libSet.toArray(libs); 2305 return libs; 2306 } 2307 } 2308 return null; 2309 } 2310 2311 @Override 2312 public FeatureInfo[] getSystemAvailableFeatures() { 2313 Collection<FeatureInfo> featSet; 2314 synchronized (mPackages) { 2315 featSet = mAvailableFeatures.values(); 2316 int size = featSet.size(); 2317 if (size > 0) { 2318 FeatureInfo[] features = new FeatureInfo[size+1]; 2319 featSet.toArray(features); 2320 FeatureInfo fi = new FeatureInfo(); 2321 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2322 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2323 features[size] = fi; 2324 return features; 2325 } 2326 } 2327 return null; 2328 } 2329 2330 @Override 2331 public boolean hasSystemFeature(String name) { 2332 synchronized (mPackages) { 2333 return mAvailableFeatures.containsKey(name); 2334 } 2335 } 2336 2337 private void checkValidCaller(int uid, int userId) { 2338 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2339 return; 2340 2341 throw new SecurityException("Caller uid=" + uid 2342 + " is not privileged to communicate with user=" + userId); 2343 } 2344 2345 @Override 2346 public int checkPermission(String permName, String pkgName) { 2347 synchronized (mPackages) { 2348 PackageParser.Package p = mPackages.get(pkgName); 2349 if (p != null && p.mExtras != null) { 2350 PackageSetting ps = (PackageSetting)p.mExtras; 2351 if (ps.sharedUser != null) { 2352 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2353 return PackageManager.PERMISSION_GRANTED; 2354 } 2355 } else if (ps.grantedPermissions.contains(permName)) { 2356 return PackageManager.PERMISSION_GRANTED; 2357 } 2358 } 2359 } 2360 return PackageManager.PERMISSION_DENIED; 2361 } 2362 2363 @Override 2364 public int checkUidPermission(String permName, int uid) { 2365 synchronized (mPackages) { 2366 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2367 if (obj != null) { 2368 GrantedPermissions gp = (GrantedPermissions)obj; 2369 if (gp.grantedPermissions.contains(permName)) { 2370 return PackageManager.PERMISSION_GRANTED; 2371 } 2372 } else { 2373 HashSet<String> perms = mSystemPermissions.get(uid); 2374 if (perms != null && perms.contains(permName)) { 2375 return PackageManager.PERMISSION_GRANTED; 2376 } 2377 } 2378 } 2379 return PackageManager.PERMISSION_DENIED; 2380 } 2381 2382 /** 2383 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2384 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2385 * @param message the message to log on security exception 2386 */ 2387 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2388 String message) { 2389 if (userId < 0) { 2390 throw new IllegalArgumentException("Invalid userId " + userId); 2391 } 2392 if (userId == UserHandle.getUserId(callingUid)) return; 2393 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2394 if (requireFullPermission) { 2395 mContext.enforceCallingOrSelfPermission( 2396 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2397 } else { 2398 try { 2399 mContext.enforceCallingOrSelfPermission( 2400 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2401 } catch (SecurityException se) { 2402 mContext.enforceCallingOrSelfPermission( 2403 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2404 } 2405 } 2406 } 2407 } 2408 2409 private BasePermission findPermissionTreeLP(String permName) { 2410 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2411 if (permName.startsWith(bp.name) && 2412 permName.length() > bp.name.length() && 2413 permName.charAt(bp.name.length()) == '.') { 2414 return bp; 2415 } 2416 } 2417 return null; 2418 } 2419 2420 private BasePermission checkPermissionTreeLP(String permName) { 2421 if (permName != null) { 2422 BasePermission bp = findPermissionTreeLP(permName); 2423 if (bp != null) { 2424 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2425 return bp; 2426 } 2427 throw new SecurityException("Calling uid " 2428 + Binder.getCallingUid() 2429 + " is not allowed to add to permission tree " 2430 + bp.name + " owned by uid " + bp.uid); 2431 } 2432 } 2433 throw new SecurityException("No permission tree found for " + permName); 2434 } 2435 2436 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2437 if (s1 == null) { 2438 return s2 == null; 2439 } 2440 if (s2 == null) { 2441 return false; 2442 } 2443 if (s1.getClass() != s2.getClass()) { 2444 return false; 2445 } 2446 return s1.equals(s2); 2447 } 2448 2449 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2450 if (pi1.icon != pi2.icon) return false; 2451 if (pi1.logo != pi2.logo) return false; 2452 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2453 if (!compareStrings(pi1.name, pi2.name)) return false; 2454 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2455 // We'll take care of setting this one. 2456 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2457 // These are not currently stored in settings. 2458 //if (!compareStrings(pi1.group, pi2.group)) return false; 2459 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2460 //if (pi1.labelRes != pi2.labelRes) return false; 2461 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2462 return true; 2463 } 2464 2465 int permissionInfoFootprint(PermissionInfo info) { 2466 int size = info.name.length(); 2467 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2468 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2469 return size; 2470 } 2471 2472 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2473 int size = 0; 2474 for (BasePermission perm : mSettings.mPermissions.values()) { 2475 if (perm.uid == tree.uid) { 2476 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2477 } 2478 } 2479 return size; 2480 } 2481 2482 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2483 // We calculate the max size of permissions defined by this uid and throw 2484 // if that plus the size of 'info' would exceed our stated maximum. 2485 if (tree.uid != Process.SYSTEM_UID) { 2486 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2487 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2488 throw new SecurityException("Permission tree size cap exceeded"); 2489 } 2490 } 2491 } 2492 2493 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2494 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2495 throw new SecurityException("Label must be specified in permission"); 2496 } 2497 BasePermission tree = checkPermissionTreeLP(info.name); 2498 BasePermission bp = mSettings.mPermissions.get(info.name); 2499 boolean added = bp == null; 2500 boolean changed = true; 2501 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2502 if (added) { 2503 enforcePermissionCapLocked(info, tree); 2504 bp = new BasePermission(info.name, tree.sourcePackage, 2505 BasePermission.TYPE_DYNAMIC); 2506 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2507 throw new SecurityException( 2508 "Not allowed to modify non-dynamic permission " 2509 + info.name); 2510 } else { 2511 if (bp.protectionLevel == fixedLevel 2512 && bp.perm.owner.equals(tree.perm.owner) 2513 && bp.uid == tree.uid 2514 && comparePermissionInfos(bp.perm.info, info)) { 2515 changed = false; 2516 } 2517 } 2518 bp.protectionLevel = fixedLevel; 2519 info = new PermissionInfo(info); 2520 info.protectionLevel = fixedLevel; 2521 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2522 bp.perm.info.packageName = tree.perm.info.packageName; 2523 bp.uid = tree.uid; 2524 if (added) { 2525 mSettings.mPermissions.put(info.name, bp); 2526 } 2527 if (changed) { 2528 if (!async) { 2529 mSettings.writeLPr(); 2530 } else { 2531 scheduleWriteSettingsLocked(); 2532 } 2533 } 2534 return added; 2535 } 2536 2537 @Override 2538 public boolean addPermission(PermissionInfo info) { 2539 synchronized (mPackages) { 2540 return addPermissionLocked(info, false); 2541 } 2542 } 2543 2544 @Override 2545 public boolean addPermissionAsync(PermissionInfo info) { 2546 synchronized (mPackages) { 2547 return addPermissionLocked(info, true); 2548 } 2549 } 2550 2551 @Override 2552 public void removePermission(String name) { 2553 synchronized (mPackages) { 2554 checkPermissionTreeLP(name); 2555 BasePermission bp = mSettings.mPermissions.get(name); 2556 if (bp != null) { 2557 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2558 throw new SecurityException( 2559 "Not allowed to modify non-dynamic permission " 2560 + name); 2561 } 2562 mSettings.mPermissions.remove(name); 2563 mSettings.writeLPr(); 2564 } 2565 } 2566 } 2567 2568 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2569 int index = pkg.requestedPermissions.indexOf(bp.name); 2570 if (index == -1) { 2571 throw new SecurityException("Package " + pkg.packageName 2572 + " has not requested permission " + bp.name); 2573 } 2574 boolean isNormal = 2575 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2576 == PermissionInfo.PROTECTION_NORMAL); 2577 boolean isDangerous = 2578 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2579 == PermissionInfo.PROTECTION_DANGEROUS); 2580 boolean isDevelopment = 2581 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2582 2583 if (!isNormal && !isDangerous && !isDevelopment) { 2584 throw new SecurityException("Permission " + bp.name 2585 + " is not a changeable permission type"); 2586 } 2587 2588 if (isNormal || isDangerous) { 2589 if (pkg.requestedPermissionsRequired.get(index)) { 2590 throw new SecurityException("Can't change " + bp.name 2591 + ". It is required by the application"); 2592 } 2593 } 2594 } 2595 2596 @Override 2597 public void grantPermission(String packageName, String permissionName) { 2598 mContext.enforceCallingOrSelfPermission( 2599 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2600 synchronized (mPackages) { 2601 final PackageParser.Package pkg = mPackages.get(packageName); 2602 if (pkg == null) { 2603 throw new IllegalArgumentException("Unknown package: " + packageName); 2604 } 2605 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2606 if (bp == null) { 2607 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2608 } 2609 2610 checkGrantRevokePermissions(pkg, bp); 2611 2612 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2613 if (ps == null) { 2614 return; 2615 } 2616 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2617 if (gp.grantedPermissions.add(permissionName)) { 2618 if (ps.haveGids) { 2619 gp.gids = appendInts(gp.gids, bp.gids); 2620 } 2621 mSettings.writeLPr(); 2622 } 2623 } 2624 } 2625 2626 @Override 2627 public void revokePermission(String packageName, String permissionName) { 2628 int changedAppId = -1; 2629 2630 synchronized (mPackages) { 2631 final PackageParser.Package pkg = mPackages.get(packageName); 2632 if (pkg == null) { 2633 throw new IllegalArgumentException("Unknown package: " + packageName); 2634 } 2635 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2636 mContext.enforceCallingOrSelfPermission( 2637 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2638 } 2639 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2640 if (bp == null) { 2641 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2642 } 2643 2644 checkGrantRevokePermissions(pkg, bp); 2645 2646 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2647 if (ps == null) { 2648 return; 2649 } 2650 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2651 if (gp.grantedPermissions.remove(permissionName)) { 2652 gp.grantedPermissions.remove(permissionName); 2653 if (ps.haveGids) { 2654 gp.gids = removeInts(gp.gids, bp.gids); 2655 } 2656 mSettings.writeLPr(); 2657 changedAppId = ps.appId; 2658 } 2659 } 2660 2661 if (changedAppId >= 0) { 2662 // We changed the perm on someone, kill its processes. 2663 IActivityManager am = ActivityManagerNative.getDefault(); 2664 if (am != null) { 2665 final int callingUserId = UserHandle.getCallingUserId(); 2666 final long ident = Binder.clearCallingIdentity(); 2667 try { 2668 //XXX we should only revoke for the calling user's app permissions, 2669 // but for now we impact all users. 2670 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2671 // "revoke " + permissionName); 2672 int[] users = sUserManager.getUserIds(); 2673 for (int user : users) { 2674 am.killUid(UserHandle.getUid(user, changedAppId), 2675 "revoke " + permissionName); 2676 } 2677 } catch (RemoteException e) { 2678 } finally { 2679 Binder.restoreCallingIdentity(ident); 2680 } 2681 } 2682 } 2683 } 2684 2685 @Override 2686 public boolean isProtectedBroadcast(String actionName) { 2687 synchronized (mPackages) { 2688 return mProtectedBroadcasts.contains(actionName); 2689 } 2690 } 2691 2692 @Override 2693 public int checkSignatures(String pkg1, String pkg2) { 2694 synchronized (mPackages) { 2695 final PackageParser.Package p1 = mPackages.get(pkg1); 2696 final PackageParser.Package p2 = mPackages.get(pkg2); 2697 if (p1 == null || p1.mExtras == null 2698 || p2 == null || p2.mExtras == null) { 2699 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2700 } 2701 return compareSignatures(p1.mSignatures, p2.mSignatures); 2702 } 2703 } 2704 2705 @Override 2706 public int checkUidSignatures(int uid1, int uid2) { 2707 // Map to base uids. 2708 uid1 = UserHandle.getAppId(uid1); 2709 uid2 = UserHandle.getAppId(uid2); 2710 // reader 2711 synchronized (mPackages) { 2712 Signature[] s1; 2713 Signature[] s2; 2714 Object obj = mSettings.getUserIdLPr(uid1); 2715 if (obj != null) { 2716 if (obj instanceof SharedUserSetting) { 2717 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2718 } else if (obj instanceof PackageSetting) { 2719 s1 = ((PackageSetting)obj).signatures.mSignatures; 2720 } else { 2721 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2722 } 2723 } else { 2724 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2725 } 2726 obj = mSettings.getUserIdLPr(uid2); 2727 if (obj != null) { 2728 if (obj instanceof SharedUserSetting) { 2729 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2730 } else if (obj instanceof PackageSetting) { 2731 s2 = ((PackageSetting)obj).signatures.mSignatures; 2732 } else { 2733 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2734 } 2735 } else { 2736 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2737 } 2738 return compareSignatures(s1, s2); 2739 } 2740 } 2741 2742 /** 2743 * Compares two sets of signatures. Returns: 2744 * <br /> 2745 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2746 * <br /> 2747 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2748 * <br /> 2749 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2750 * <br /> 2751 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2752 * <br /> 2753 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2754 */ 2755 static int compareSignatures(Signature[] s1, Signature[] s2) { 2756 if (s1 == null) { 2757 return s2 == null 2758 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2759 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2760 } 2761 2762 if (s2 == null) { 2763 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2764 } 2765 2766 if (s1.length != s2.length) { 2767 return PackageManager.SIGNATURE_NO_MATCH; 2768 } 2769 2770 // Since both signature sets are of size 1, we can compare without HashSets. 2771 if (s1.length == 1) { 2772 return s1[0].equals(s2[0]) ? 2773 PackageManager.SIGNATURE_MATCH : 2774 PackageManager.SIGNATURE_NO_MATCH; 2775 } 2776 2777 HashSet<Signature> set1 = new HashSet<Signature>(); 2778 for (Signature sig : s1) { 2779 set1.add(sig); 2780 } 2781 HashSet<Signature> set2 = new HashSet<Signature>(); 2782 for (Signature sig : s2) { 2783 set2.add(sig); 2784 } 2785 // Make sure s2 contains all signatures in s1. 2786 if (set1.equals(set2)) { 2787 return PackageManager.SIGNATURE_MATCH; 2788 } 2789 return PackageManager.SIGNATURE_NO_MATCH; 2790 } 2791 2792 /** 2793 * If the database version for this type of package (internal storage or 2794 * external storage) is less than the version where package signatures 2795 * were updated, return true. 2796 */ 2797 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2798 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2799 DatabaseVersion.SIGNATURE_END_ENTITY)) 2800 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2801 DatabaseVersion.SIGNATURE_END_ENTITY)); 2802 } 2803 2804 /** 2805 * Used for backward compatibility to make sure any packages with 2806 * certificate chains get upgraded to the new style. {@code existingSigs} 2807 * will be in the old format (since they were stored on disk from before the 2808 * system upgrade) and {@code scannedSigs} will be in the newer format. 2809 */ 2810 private int compareSignaturesCompat(PackageSignatures existingSigs, 2811 PackageParser.Package scannedPkg) { 2812 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2813 return PackageManager.SIGNATURE_NO_MATCH; 2814 } 2815 2816 HashSet<Signature> existingSet = new HashSet<Signature>(); 2817 for (Signature sig : existingSigs.mSignatures) { 2818 existingSet.add(sig); 2819 } 2820 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2821 for (Signature sig : scannedPkg.mSignatures) { 2822 try { 2823 Signature[] chainSignatures = sig.getChainSignatures(); 2824 for (Signature chainSig : chainSignatures) { 2825 scannedCompatSet.add(chainSig); 2826 } 2827 } catch (CertificateEncodingException e) { 2828 scannedCompatSet.add(sig); 2829 } 2830 } 2831 /* 2832 * Make sure the expanded scanned set contains all signatures in the 2833 * existing one. 2834 */ 2835 if (scannedCompatSet.equals(existingSet)) { 2836 // Migrate the old signatures to the new scheme. 2837 existingSigs.assignSignatures(scannedPkg.mSignatures); 2838 // The new KeySets will be re-added later in the scanning process. 2839 mSettings.mKeySetManagerService.removeAppKeySetData(scannedPkg.packageName); 2840 return PackageManager.SIGNATURE_MATCH; 2841 } 2842 return PackageManager.SIGNATURE_NO_MATCH; 2843 } 2844 2845 @Override 2846 public String[] getPackagesForUid(int uid) { 2847 uid = UserHandle.getAppId(uid); 2848 // reader 2849 synchronized (mPackages) { 2850 Object obj = mSettings.getUserIdLPr(uid); 2851 if (obj instanceof SharedUserSetting) { 2852 final SharedUserSetting sus = (SharedUserSetting) obj; 2853 final int N = sus.packages.size(); 2854 final String[] res = new String[N]; 2855 final Iterator<PackageSetting> it = sus.packages.iterator(); 2856 int i = 0; 2857 while (it.hasNext()) { 2858 res[i++] = it.next().name; 2859 } 2860 return res; 2861 } else if (obj instanceof PackageSetting) { 2862 final PackageSetting ps = (PackageSetting) obj; 2863 return new String[] { ps.name }; 2864 } 2865 } 2866 return null; 2867 } 2868 2869 @Override 2870 public String getNameForUid(int uid) { 2871 // reader 2872 synchronized (mPackages) { 2873 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2874 if (obj instanceof SharedUserSetting) { 2875 final SharedUserSetting sus = (SharedUserSetting) obj; 2876 return sus.name + ":" + sus.userId; 2877 } else if (obj instanceof PackageSetting) { 2878 final PackageSetting ps = (PackageSetting) obj; 2879 return ps.name; 2880 } 2881 } 2882 return null; 2883 } 2884 2885 @Override 2886 public int getUidForSharedUser(String sharedUserName) { 2887 if(sharedUserName == null) { 2888 return -1; 2889 } 2890 // reader 2891 synchronized (mPackages) { 2892 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2893 if (suid == null) { 2894 return -1; 2895 } 2896 return suid.userId; 2897 } 2898 } 2899 2900 @Override 2901 public int getFlagsForUid(int uid) { 2902 synchronized (mPackages) { 2903 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2904 if (obj instanceof SharedUserSetting) { 2905 final SharedUserSetting sus = (SharedUserSetting) obj; 2906 return sus.pkgFlags; 2907 } else if (obj instanceof PackageSetting) { 2908 final PackageSetting ps = (PackageSetting) obj; 2909 return ps.pkgFlags; 2910 } 2911 } 2912 return 0; 2913 } 2914 2915 @Override 2916 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2917 int flags, int userId) { 2918 if (!sUserManager.exists(userId)) return null; 2919 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2920 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2921 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2922 } 2923 2924 @Override 2925 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2926 IntentFilter filter, int match, ComponentName activity) { 2927 final int userId = UserHandle.getCallingUserId(); 2928 if (DEBUG_PREFERRED) { 2929 Log.v(TAG, "setLastChosenActivity intent=" + intent 2930 + " resolvedType=" + resolvedType 2931 + " flags=" + flags 2932 + " filter=" + filter 2933 + " match=" + match 2934 + " activity=" + activity); 2935 filter.dump(new PrintStreamPrinter(System.out), " "); 2936 } 2937 intent.setComponent(null); 2938 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2939 // Find any earlier preferred or last chosen entries and nuke them 2940 findPreferredActivity(intent, resolvedType, 2941 flags, query, 0, false, true, false, userId); 2942 // Add the new activity as the last chosen for this filter 2943 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2944 } 2945 2946 @Override 2947 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2948 final int userId = UserHandle.getCallingUserId(); 2949 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2950 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2951 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2952 false, false, false, userId); 2953 } 2954 2955 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2956 int flags, List<ResolveInfo> query, int userId) { 2957 if (query != null) { 2958 final int N = query.size(); 2959 if (N == 1) { 2960 return query.get(0); 2961 } else if (N > 1) { 2962 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2963 // If there is more than one activity with the same priority, 2964 // then let the user decide between them. 2965 ResolveInfo r0 = query.get(0); 2966 ResolveInfo r1 = query.get(1); 2967 if (DEBUG_INTENT_MATCHING || debug) { 2968 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2969 + r1.activityInfo.name + "=" + r1.priority); 2970 } 2971 // If the first activity has a higher priority, or a different 2972 // default, then it is always desireable to pick it. 2973 if (r0.priority != r1.priority 2974 || r0.preferredOrder != r1.preferredOrder 2975 || r0.isDefault != r1.isDefault) { 2976 return query.get(0); 2977 } 2978 // If we have saved a preference for a preferred activity for 2979 // this Intent, use that. 2980 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2981 flags, query, r0.priority, true, false, debug, userId); 2982 if (ri != null) { 2983 return ri; 2984 } 2985 if (userId != 0) { 2986 ri = new ResolveInfo(mResolveInfo); 2987 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2988 ri.activityInfo.applicationInfo = new ApplicationInfo( 2989 ri.activityInfo.applicationInfo); 2990 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2991 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2992 return ri; 2993 } 2994 return mResolveInfo; 2995 } 2996 } 2997 return null; 2998 } 2999 3000 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3001 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3002 final int N = query.size(); 3003 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3004 .get(userId); 3005 // Get the list of persistent preferred activities that handle the intent 3006 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3007 List<PersistentPreferredActivity> pprefs = ppir != null 3008 ? ppir.queryIntent(intent, resolvedType, 3009 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3010 : null; 3011 if (pprefs != null && pprefs.size() > 0) { 3012 final int M = pprefs.size(); 3013 for (int i=0; i<M; i++) { 3014 final PersistentPreferredActivity ppa = pprefs.get(i); 3015 if (DEBUG_PREFERRED || debug) { 3016 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3017 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3018 + "\n component=" + ppa.mComponent); 3019 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3020 } 3021 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3022 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3023 if (DEBUG_PREFERRED || debug) { 3024 Slog.v(TAG, "Found persistent preferred activity:"); 3025 if (ai != null) { 3026 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3027 } else { 3028 Slog.v(TAG, " null"); 3029 } 3030 } 3031 if (ai == null) { 3032 // This previously registered persistent preferred activity 3033 // component is no longer known. Ignore it and do NOT remove it. 3034 continue; 3035 } 3036 for (int j=0; j<N; j++) { 3037 final ResolveInfo ri = query.get(j); 3038 if (!ri.activityInfo.applicationInfo.packageName 3039 .equals(ai.applicationInfo.packageName)) { 3040 continue; 3041 } 3042 if (!ri.activityInfo.name.equals(ai.name)) { 3043 continue; 3044 } 3045 // Found a persistent preference that can handle the intent. 3046 if (DEBUG_PREFERRED || debug) { 3047 Slog.v(TAG, "Returning persistent preferred activity: " + 3048 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3049 } 3050 return ri; 3051 } 3052 } 3053 } 3054 return null; 3055 } 3056 3057 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3058 List<ResolveInfo> query, int priority, boolean always, 3059 boolean removeMatches, boolean debug, int userId) { 3060 if (!sUserManager.exists(userId)) return null; 3061 // writer 3062 synchronized (mPackages) { 3063 if (intent.getSelector() != null) { 3064 intent = intent.getSelector(); 3065 } 3066 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3067 3068 // Try to find a matching persistent preferred activity. 3069 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3070 debug, userId); 3071 3072 // If a persistent preferred activity matched, use it. 3073 if (pri != null) { 3074 return pri; 3075 } 3076 3077 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3078 // Get the list of preferred activities that handle the intent 3079 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3080 List<PreferredActivity> prefs = pir != null 3081 ? pir.queryIntent(intent, resolvedType, 3082 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3083 : null; 3084 if (prefs != null && prefs.size() > 0) { 3085 // First figure out how good the original match set is. 3086 // We will only allow preferred activities that came 3087 // from the same match quality. 3088 int match = 0; 3089 3090 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3091 3092 final int N = query.size(); 3093 for (int j=0; j<N; j++) { 3094 final ResolveInfo ri = query.get(j); 3095 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3096 + ": 0x" + Integer.toHexString(match)); 3097 if (ri.match > match) { 3098 match = ri.match; 3099 } 3100 } 3101 3102 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3103 + Integer.toHexString(match)); 3104 3105 match &= IntentFilter.MATCH_CATEGORY_MASK; 3106 final int M = prefs.size(); 3107 for (int i=0; i<M; i++) { 3108 final PreferredActivity pa = prefs.get(i); 3109 if (DEBUG_PREFERRED || debug) { 3110 Slog.v(TAG, "Checking PreferredActivity ds=" 3111 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3112 + "\n component=" + pa.mPref.mComponent); 3113 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3114 } 3115 if (pa.mPref.mMatch != match) { 3116 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3117 + Integer.toHexString(pa.mPref.mMatch)); 3118 continue; 3119 } 3120 // If it's not an "always" type preferred activity and that's what we're 3121 // looking for, skip it. 3122 if (always && !pa.mPref.mAlways) { 3123 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3124 continue; 3125 } 3126 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3127 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3128 if (DEBUG_PREFERRED || debug) { 3129 Slog.v(TAG, "Found preferred activity:"); 3130 if (ai != null) { 3131 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3132 } else { 3133 Slog.v(TAG, " null"); 3134 } 3135 } 3136 if (ai == null) { 3137 // This previously registered preferred activity 3138 // component is no longer known. Most likely an update 3139 // to the app was installed and in the new version this 3140 // component no longer exists. Clean it up by removing 3141 // it from the preferred activities list, and skip it. 3142 Slog.w(TAG, "Removing dangling preferred activity: " 3143 + pa.mPref.mComponent); 3144 pir.removeFilter(pa); 3145 continue; 3146 } 3147 for (int j=0; j<N; j++) { 3148 final ResolveInfo ri = query.get(j); 3149 if (!ri.activityInfo.applicationInfo.packageName 3150 .equals(ai.applicationInfo.packageName)) { 3151 continue; 3152 } 3153 if (!ri.activityInfo.name.equals(ai.name)) { 3154 continue; 3155 } 3156 3157 if (removeMatches) { 3158 pir.removeFilter(pa); 3159 if (DEBUG_PREFERRED) { 3160 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3161 } 3162 break; 3163 } 3164 3165 // Okay we found a previously set preferred or last chosen app. 3166 // If the result set is different from when this 3167 // was created, we need to clear it and re-ask the 3168 // user their preference, if we're looking for an "always" type entry. 3169 if (always && !pa.mPref.sameSet(query, priority)) { 3170 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3171 + intent + " type " + resolvedType); 3172 if (DEBUG_PREFERRED) { 3173 Slog.v(TAG, "Removing preferred activity since set changed " 3174 + pa.mPref.mComponent); 3175 } 3176 pir.removeFilter(pa); 3177 // Re-add the filter as a "last chosen" entry (!always) 3178 PreferredActivity lastChosen = new PreferredActivity( 3179 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3180 pir.addFilter(lastChosen); 3181 mSettings.writePackageRestrictionsLPr(userId); 3182 return null; 3183 } 3184 3185 // Yay! Either the set matched or we're looking for the last chosen 3186 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3187 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3188 mSettings.writePackageRestrictionsLPr(userId); 3189 return ri; 3190 } 3191 } 3192 } 3193 mSettings.writePackageRestrictionsLPr(userId); 3194 } 3195 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3196 return null; 3197 } 3198 3199 /* 3200 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3201 */ 3202 @Override 3203 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3204 int targetUserId) { 3205 mContext.enforceCallingOrSelfPermission( 3206 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3207 List<CrossProfileIntentFilter> matches = 3208 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3209 if (matches != null) { 3210 int size = matches.size(); 3211 for (int i = 0; i < size; i++) { 3212 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3213 } 3214 } 3215 3216 ArrayList<String> packageNames = null; 3217 SparseArray<ArrayList<String>> fromSource = 3218 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3219 if (fromSource != null) { 3220 packageNames = fromSource.get(targetUserId); 3221 } 3222 if (packageNames.contains(intent.getPackage())) { 3223 return true; 3224 } 3225 // We need the package name, so we try to resolve with the loosest flags possible 3226 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3227 intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3228 int count = resolveInfos.size(); 3229 for (int i = 0; i < count; i++) { 3230 ResolveInfo resolveInfo = resolveInfos.get(i); 3231 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3232 return true; 3233 } 3234 } 3235 return false; 3236 } 3237 3238 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3239 String resolvedType, int userId) { 3240 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3241 if (resolver != null) { 3242 return resolver.queryIntent(intent, resolvedType, false, userId); 3243 } 3244 return null; 3245 } 3246 3247 @Override 3248 public List<ResolveInfo> queryIntentActivities(Intent intent, 3249 String resolvedType, int flags, int userId) { 3250 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3251 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3252 ComponentName comp = intent.getComponent(); 3253 if (comp == null) { 3254 if (intent.getSelector() != null) { 3255 intent = intent.getSelector(); 3256 comp = intent.getComponent(); 3257 } 3258 } 3259 3260 if (comp != null) { 3261 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3262 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3263 if (ai != null) { 3264 final ResolveInfo ri = new ResolveInfo(); 3265 ri.activityInfo = ai; 3266 list.add(ri); 3267 } 3268 return list; 3269 } 3270 3271 // reader 3272 synchronized (mPackages) { 3273 final String pkgName = intent.getPackage(); 3274 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3275 if (pkgName == null) { 3276 ResolveInfo resolveInfo = null; 3277 if (queryCrossProfile) { 3278 // Check if the intent needs to be forwarded to another user for this package 3279 ArrayList<ResolveInfo> crossProfileResult = 3280 queryIntentActivitiesCrossProfilePackage( 3281 intent, resolvedType, flags, userId); 3282 if (!crossProfileResult.isEmpty()) { 3283 // Skip the current profile 3284 return crossProfileResult; 3285 } 3286 List<CrossProfileIntentFilter> matchingFilters = 3287 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3288 // Check for results that need to skip the current profile. 3289 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3290 resolvedType, flags, userId); 3291 if (resolveInfo != null) { 3292 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3293 result.add(resolveInfo); 3294 return result; 3295 } 3296 // Check for cross profile results. 3297 resolveInfo = queryCrossProfileIntents( 3298 matchingFilters, intent, resolvedType, flags, userId); 3299 } 3300 // Check for results in the current profile. 3301 List<ResolveInfo> result = mActivities.queryIntent( 3302 intent, resolvedType, flags, userId); 3303 if (resolveInfo != null) { 3304 result.add(resolveInfo); 3305 } 3306 return result; 3307 } 3308 final PackageParser.Package pkg = mPackages.get(pkgName); 3309 if (pkg != null) { 3310 if (queryCrossProfile) { 3311 ArrayList<ResolveInfo> crossProfileResult = 3312 queryIntentActivitiesCrossProfilePackage( 3313 intent, resolvedType, flags, userId, pkg, pkgName); 3314 if (!crossProfileResult.isEmpty()) { 3315 // Skip the current profile 3316 return crossProfileResult; 3317 } 3318 } 3319 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3320 pkg.activities, userId); 3321 } 3322 return new ArrayList<ResolveInfo>(); 3323 } 3324 } 3325 3326 private ResolveInfo querySkipCurrentProfileIntents( 3327 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3328 int flags, int sourceUserId) { 3329 if (matchingFilters != null) { 3330 int size = matchingFilters.size(); 3331 for (int i = 0; i < size; i ++) { 3332 CrossProfileIntentFilter filter = matchingFilters.get(i); 3333 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3334 // Checking if there are activities in the target user that can handle the 3335 // intent. 3336 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3337 flags, sourceUserId); 3338 if (resolveInfo != null) { 3339 return resolveInfo; 3340 } 3341 } 3342 } 3343 } 3344 return null; 3345 } 3346 3347 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3348 Intent intent, String resolvedType, int flags, int userId) { 3349 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3350 SparseArray<ArrayList<String>> sourceForwardingInfo = 3351 mSettings.mCrossProfilePackageInfo.get(userId); 3352 if (sourceForwardingInfo != null) { 3353 int NI = sourceForwardingInfo.size(); 3354 for (int i = 0; i < NI; i++) { 3355 int targetUserId = sourceForwardingInfo.keyAt(i); 3356 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3357 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3358 intent, resolvedType, flags, targetUserId); 3359 int NJ = resolveInfos.size(); 3360 for (int j = 0; j < NJ; j++) { 3361 ResolveInfo resolveInfo = resolveInfos.get(j); 3362 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3363 matchingResolveInfos.add(createForwardingResolveInfo( 3364 resolveInfo.filter, userId, targetUserId)); 3365 } 3366 } 3367 } 3368 } 3369 return matchingResolveInfos; 3370 } 3371 3372 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3373 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3374 String packageName) { 3375 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3376 SparseArray<ArrayList<String>> sourceForwardingInfo = 3377 mSettings.mCrossProfilePackageInfo.get(userId); 3378 if (sourceForwardingInfo != null) { 3379 int NI = sourceForwardingInfo.size(); 3380 for (int i = 0; i < NI; i++) { 3381 int targetUserId = sourceForwardingInfo.keyAt(i); 3382 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3383 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3384 intent, resolvedType, flags, pkg.activities, targetUserId); 3385 int NJ = resolveInfos.size(); 3386 for (int j = 0; j < NJ; j++) { 3387 ResolveInfo resolveInfo = resolveInfos.get(j); 3388 matchingResolveInfos.add(createForwardingResolveInfo( 3389 resolveInfo.filter, userId, targetUserId)); 3390 } 3391 } 3392 } 3393 } 3394 return matchingResolveInfos; 3395 } 3396 3397 // Return matching ResolveInfo if any for skip current profile intent filters. 3398 private ResolveInfo queryCrossProfileIntents( 3399 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3400 int flags, int sourceUserId) { 3401 if (matchingFilters != null) { 3402 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3403 // match the same intent. For performance reasons, it is better not to 3404 // run queryIntent twice for the same userId 3405 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3406 int size = matchingFilters.size(); 3407 for (int i = 0; i < size; i++) { 3408 CrossProfileIntentFilter filter = matchingFilters.get(i); 3409 int targetUserId = filter.getTargetUserId(); 3410 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3411 && !alreadyTriedUserIds.get(targetUserId)) { 3412 // Checking if there are activities in the target user that can handle the 3413 // intent. 3414 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3415 flags, sourceUserId); 3416 if (resolveInfo != null) return resolveInfo; 3417 alreadyTriedUserIds.put(targetUserId, true); 3418 } 3419 } 3420 } 3421 return null; 3422 } 3423 3424 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3425 String resolvedType, int flags, int sourceUserId) { 3426 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3427 resolvedType, flags, filter.getTargetUserId()); 3428 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3429 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3430 } 3431 return null; 3432 } 3433 3434 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3435 int sourceUserId, int targetUserId) { 3436 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3437 String className; 3438 if (targetUserId == UserHandle.USER_OWNER) { 3439 className = FORWARD_INTENT_TO_USER_OWNER; 3440 } else { 3441 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3442 } 3443 ComponentName forwardingActivityComponentName = new ComponentName( 3444 mAndroidApplication.packageName, className); 3445 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3446 sourceUserId); 3447 if (targetUserId == UserHandle.USER_OWNER) { 3448 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3449 forwardingResolveInfo.noResourceId = true; 3450 } 3451 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3452 forwardingResolveInfo.priority = 0; 3453 forwardingResolveInfo.preferredOrder = 0; 3454 forwardingResolveInfo.match = 0; 3455 forwardingResolveInfo.isDefault = true; 3456 forwardingResolveInfo.filter = filter; 3457 forwardingResolveInfo.targetUserId = targetUserId; 3458 return forwardingResolveInfo; 3459 } 3460 3461 @Override 3462 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3463 Intent[] specifics, String[] specificTypes, Intent intent, 3464 String resolvedType, int flags, int userId) { 3465 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3466 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3467 "query intent activity options"); 3468 final String resultsAction = intent.getAction(); 3469 3470 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3471 | PackageManager.GET_RESOLVED_FILTER, userId); 3472 3473 if (DEBUG_INTENT_MATCHING) { 3474 Log.v(TAG, "Query " + intent + ": " + results); 3475 } 3476 3477 int specificsPos = 0; 3478 int N; 3479 3480 // todo: note that the algorithm used here is O(N^2). This 3481 // isn't a problem in our current environment, but if we start running 3482 // into situations where we have more than 5 or 10 matches then this 3483 // should probably be changed to something smarter... 3484 3485 // First we go through and resolve each of the specific items 3486 // that were supplied, taking care of removing any corresponding 3487 // duplicate items in the generic resolve list. 3488 if (specifics != null) { 3489 for (int i=0; i<specifics.length; i++) { 3490 final Intent sintent = specifics[i]; 3491 if (sintent == null) { 3492 continue; 3493 } 3494 3495 if (DEBUG_INTENT_MATCHING) { 3496 Log.v(TAG, "Specific #" + i + ": " + sintent); 3497 } 3498 3499 String action = sintent.getAction(); 3500 if (resultsAction != null && resultsAction.equals(action)) { 3501 // If this action was explicitly requested, then don't 3502 // remove things that have it. 3503 action = null; 3504 } 3505 3506 ResolveInfo ri = null; 3507 ActivityInfo ai = null; 3508 3509 ComponentName comp = sintent.getComponent(); 3510 if (comp == null) { 3511 ri = resolveIntent( 3512 sintent, 3513 specificTypes != null ? specificTypes[i] : null, 3514 flags, userId); 3515 if (ri == null) { 3516 continue; 3517 } 3518 if (ri == mResolveInfo) { 3519 // ACK! Must do something better with this. 3520 } 3521 ai = ri.activityInfo; 3522 comp = new ComponentName(ai.applicationInfo.packageName, 3523 ai.name); 3524 } else { 3525 ai = getActivityInfo(comp, flags, userId); 3526 if (ai == null) { 3527 continue; 3528 } 3529 } 3530 3531 // Look for any generic query activities that are duplicates 3532 // of this specific one, and remove them from the results. 3533 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3534 N = results.size(); 3535 int j; 3536 for (j=specificsPos; j<N; j++) { 3537 ResolveInfo sri = results.get(j); 3538 if ((sri.activityInfo.name.equals(comp.getClassName()) 3539 && sri.activityInfo.applicationInfo.packageName.equals( 3540 comp.getPackageName())) 3541 || (action != null && sri.filter.matchAction(action))) { 3542 results.remove(j); 3543 if (DEBUG_INTENT_MATCHING) Log.v( 3544 TAG, "Removing duplicate item from " + j 3545 + " due to specific " + specificsPos); 3546 if (ri == null) { 3547 ri = sri; 3548 } 3549 j--; 3550 N--; 3551 } 3552 } 3553 3554 // Add this specific item to its proper place. 3555 if (ri == null) { 3556 ri = new ResolveInfo(); 3557 ri.activityInfo = ai; 3558 } 3559 results.add(specificsPos, ri); 3560 ri.specificIndex = i; 3561 specificsPos++; 3562 } 3563 } 3564 3565 // Now we go through the remaining generic results and remove any 3566 // duplicate actions that are found here. 3567 N = results.size(); 3568 for (int i=specificsPos; i<N-1; i++) { 3569 final ResolveInfo rii = results.get(i); 3570 if (rii.filter == null) { 3571 continue; 3572 } 3573 3574 // Iterate over all of the actions of this result's intent 3575 // filter... typically this should be just one. 3576 final Iterator<String> it = rii.filter.actionsIterator(); 3577 if (it == null) { 3578 continue; 3579 } 3580 while (it.hasNext()) { 3581 final String action = it.next(); 3582 if (resultsAction != null && resultsAction.equals(action)) { 3583 // If this action was explicitly requested, then don't 3584 // remove things that have it. 3585 continue; 3586 } 3587 for (int j=i+1; j<N; j++) { 3588 final ResolveInfo rij = results.get(j); 3589 if (rij.filter != null && rij.filter.hasAction(action)) { 3590 results.remove(j); 3591 if (DEBUG_INTENT_MATCHING) Log.v( 3592 TAG, "Removing duplicate item from " + j 3593 + " due to action " + action + " at " + i); 3594 j--; 3595 N--; 3596 } 3597 } 3598 } 3599 3600 // If the caller didn't request filter information, drop it now 3601 // so we don't have to marshall/unmarshall it. 3602 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3603 rii.filter = null; 3604 } 3605 } 3606 3607 // Filter out the caller activity if so requested. 3608 if (caller != null) { 3609 N = results.size(); 3610 for (int i=0; i<N; i++) { 3611 ActivityInfo ainfo = results.get(i).activityInfo; 3612 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3613 && caller.getClassName().equals(ainfo.name)) { 3614 results.remove(i); 3615 break; 3616 } 3617 } 3618 } 3619 3620 // If the caller didn't request filter information, 3621 // drop them now so we don't have to 3622 // marshall/unmarshall it. 3623 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3624 N = results.size(); 3625 for (int i=0; i<N; i++) { 3626 results.get(i).filter = null; 3627 } 3628 } 3629 3630 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3631 return results; 3632 } 3633 3634 @Override 3635 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3636 int userId) { 3637 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3638 ComponentName comp = intent.getComponent(); 3639 if (comp == null) { 3640 if (intent.getSelector() != null) { 3641 intent = intent.getSelector(); 3642 comp = intent.getComponent(); 3643 } 3644 } 3645 if (comp != null) { 3646 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3647 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3648 if (ai != null) { 3649 ResolveInfo ri = new ResolveInfo(); 3650 ri.activityInfo = ai; 3651 list.add(ri); 3652 } 3653 return list; 3654 } 3655 3656 // reader 3657 synchronized (mPackages) { 3658 String pkgName = intent.getPackage(); 3659 if (pkgName == null) { 3660 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3661 } 3662 final PackageParser.Package pkg = mPackages.get(pkgName); 3663 if (pkg != null) { 3664 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3665 userId); 3666 } 3667 return null; 3668 } 3669 } 3670 3671 @Override 3672 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3673 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3674 if (!sUserManager.exists(userId)) return null; 3675 if (query != null) { 3676 if (query.size() >= 1) { 3677 // If there is more than one service with the same priority, 3678 // just arbitrarily pick the first one. 3679 return query.get(0); 3680 } 3681 } 3682 return null; 3683 } 3684 3685 @Override 3686 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3687 int userId) { 3688 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3689 ComponentName comp = intent.getComponent(); 3690 if (comp == null) { 3691 if (intent.getSelector() != null) { 3692 intent = intent.getSelector(); 3693 comp = intent.getComponent(); 3694 } 3695 } 3696 if (comp != null) { 3697 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3698 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3699 if (si != null) { 3700 final ResolveInfo ri = new ResolveInfo(); 3701 ri.serviceInfo = si; 3702 list.add(ri); 3703 } 3704 return list; 3705 } 3706 3707 // reader 3708 synchronized (mPackages) { 3709 String pkgName = intent.getPackage(); 3710 if (pkgName == null) { 3711 return mServices.queryIntent(intent, resolvedType, flags, userId); 3712 } 3713 final PackageParser.Package pkg = mPackages.get(pkgName); 3714 if (pkg != null) { 3715 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3716 userId); 3717 } 3718 return null; 3719 } 3720 } 3721 3722 @Override 3723 public List<ResolveInfo> queryIntentContentProviders( 3724 Intent intent, String resolvedType, int flags, int userId) { 3725 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3726 ComponentName comp = intent.getComponent(); 3727 if (comp == null) { 3728 if (intent.getSelector() != null) { 3729 intent = intent.getSelector(); 3730 comp = intent.getComponent(); 3731 } 3732 } 3733 if (comp != null) { 3734 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3735 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3736 if (pi != null) { 3737 final ResolveInfo ri = new ResolveInfo(); 3738 ri.providerInfo = pi; 3739 list.add(ri); 3740 } 3741 return list; 3742 } 3743 3744 // reader 3745 synchronized (mPackages) { 3746 String pkgName = intent.getPackage(); 3747 if (pkgName == null) { 3748 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3749 } 3750 final PackageParser.Package pkg = mPackages.get(pkgName); 3751 if (pkg != null) { 3752 return mProviders.queryIntentForPackage( 3753 intent, resolvedType, flags, pkg.providers, userId); 3754 } 3755 return null; 3756 } 3757 } 3758 3759 @Override 3760 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3761 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3762 3763 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3764 3765 // writer 3766 synchronized (mPackages) { 3767 ArrayList<PackageInfo> list; 3768 if (listUninstalled) { 3769 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3770 for (PackageSetting ps : mSettings.mPackages.values()) { 3771 PackageInfo pi; 3772 if (ps.pkg != null) { 3773 pi = generatePackageInfo(ps.pkg, flags, userId); 3774 } else { 3775 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3776 } 3777 if (pi != null) { 3778 list.add(pi); 3779 } 3780 } 3781 } else { 3782 list = new ArrayList<PackageInfo>(mPackages.size()); 3783 for (PackageParser.Package p : mPackages.values()) { 3784 PackageInfo pi = generatePackageInfo(p, flags, userId); 3785 if (pi != null) { 3786 list.add(pi); 3787 } 3788 } 3789 } 3790 3791 return new ParceledListSlice<PackageInfo>(list); 3792 } 3793 } 3794 3795 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3796 String[] permissions, boolean[] tmp, int flags, int userId) { 3797 int numMatch = 0; 3798 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3799 for (int i=0; i<permissions.length; i++) { 3800 if (gp.grantedPermissions.contains(permissions[i])) { 3801 tmp[i] = true; 3802 numMatch++; 3803 } else { 3804 tmp[i] = false; 3805 } 3806 } 3807 if (numMatch == 0) { 3808 return; 3809 } 3810 PackageInfo pi; 3811 if (ps.pkg != null) { 3812 pi = generatePackageInfo(ps.pkg, flags, userId); 3813 } else { 3814 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3815 } 3816 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3817 if (numMatch == permissions.length) { 3818 pi.requestedPermissions = permissions; 3819 } else { 3820 pi.requestedPermissions = new String[numMatch]; 3821 numMatch = 0; 3822 for (int i=0; i<permissions.length; i++) { 3823 if (tmp[i]) { 3824 pi.requestedPermissions[numMatch] = permissions[i]; 3825 numMatch++; 3826 } 3827 } 3828 } 3829 } 3830 list.add(pi); 3831 } 3832 3833 @Override 3834 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3835 String[] permissions, int flags, int userId) { 3836 if (!sUserManager.exists(userId)) return null; 3837 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3838 3839 // writer 3840 synchronized (mPackages) { 3841 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3842 boolean[] tmpBools = new boolean[permissions.length]; 3843 if (listUninstalled) { 3844 for (PackageSetting ps : mSettings.mPackages.values()) { 3845 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3846 } 3847 } else { 3848 for (PackageParser.Package pkg : mPackages.values()) { 3849 PackageSetting ps = (PackageSetting)pkg.mExtras; 3850 if (ps != null) { 3851 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3852 userId); 3853 } 3854 } 3855 } 3856 3857 return new ParceledListSlice<PackageInfo>(list); 3858 } 3859 } 3860 3861 @Override 3862 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3863 if (!sUserManager.exists(userId)) return null; 3864 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3865 3866 // writer 3867 synchronized (mPackages) { 3868 ArrayList<ApplicationInfo> list; 3869 if (listUninstalled) { 3870 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3871 for (PackageSetting ps : mSettings.mPackages.values()) { 3872 ApplicationInfo ai; 3873 if (ps.pkg != null) { 3874 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3875 ps.readUserState(userId), userId); 3876 } else { 3877 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3878 } 3879 if (ai != null) { 3880 list.add(ai); 3881 } 3882 } 3883 } else { 3884 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3885 for (PackageParser.Package p : mPackages.values()) { 3886 if (p.mExtras != null) { 3887 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3888 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3889 if (ai != null) { 3890 list.add(ai); 3891 } 3892 } 3893 } 3894 } 3895 3896 return new ParceledListSlice<ApplicationInfo>(list); 3897 } 3898 } 3899 3900 public List<ApplicationInfo> getPersistentApplications(int flags) { 3901 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3902 3903 // reader 3904 synchronized (mPackages) { 3905 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3906 final int userId = UserHandle.getCallingUserId(); 3907 while (i.hasNext()) { 3908 final PackageParser.Package p = i.next(); 3909 if (p.applicationInfo != null 3910 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3911 && (!mSafeMode || isSystemApp(p))) { 3912 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3913 if (ps != null) { 3914 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3915 ps.readUserState(userId), userId); 3916 if (ai != null) { 3917 finalList.add(ai); 3918 } 3919 } 3920 } 3921 } 3922 } 3923 3924 return finalList; 3925 } 3926 3927 @Override 3928 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3929 if (!sUserManager.exists(userId)) return null; 3930 // reader 3931 synchronized (mPackages) { 3932 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3933 PackageSetting ps = provider != null 3934 ? mSettings.mPackages.get(provider.owner.packageName) 3935 : null; 3936 return ps != null 3937 && mSettings.isEnabledLPr(provider.info, flags, userId) 3938 && (!mSafeMode || (provider.info.applicationInfo.flags 3939 &ApplicationInfo.FLAG_SYSTEM) != 0) 3940 ? PackageParser.generateProviderInfo(provider, flags, 3941 ps.readUserState(userId), userId) 3942 : null; 3943 } 3944 } 3945 3946 /** 3947 * @deprecated 3948 */ 3949 @Deprecated 3950 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3951 // reader 3952 synchronized (mPackages) { 3953 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3954 .entrySet().iterator(); 3955 final int userId = UserHandle.getCallingUserId(); 3956 while (i.hasNext()) { 3957 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3958 PackageParser.Provider p = entry.getValue(); 3959 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3960 3961 if (ps != null && p.syncable 3962 && (!mSafeMode || (p.info.applicationInfo.flags 3963 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3964 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3965 ps.readUserState(userId), userId); 3966 if (info != null) { 3967 outNames.add(entry.getKey()); 3968 outInfo.add(info); 3969 } 3970 } 3971 } 3972 } 3973 } 3974 3975 @Override 3976 public List<ProviderInfo> queryContentProviders(String processName, 3977 int uid, int flags) { 3978 ArrayList<ProviderInfo> finalList = null; 3979 // reader 3980 synchronized (mPackages) { 3981 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3982 final int userId = processName != null ? 3983 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3984 while (i.hasNext()) { 3985 final PackageParser.Provider p = i.next(); 3986 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3987 if (ps != null && p.info.authority != null 3988 && (processName == null 3989 || (p.info.processName.equals(processName) 3990 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3991 && mSettings.isEnabledLPr(p.info, flags, userId) 3992 && (!mSafeMode 3993 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3994 if (finalList == null) { 3995 finalList = new ArrayList<ProviderInfo>(3); 3996 } 3997 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3998 ps.readUserState(userId), userId); 3999 if (info != null) { 4000 finalList.add(info); 4001 } 4002 } 4003 } 4004 } 4005 4006 if (finalList != null) { 4007 Collections.sort(finalList, mProviderInitOrderSorter); 4008 } 4009 4010 return finalList; 4011 } 4012 4013 @Override 4014 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4015 int flags) { 4016 // reader 4017 synchronized (mPackages) { 4018 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4019 return PackageParser.generateInstrumentationInfo(i, flags); 4020 } 4021 } 4022 4023 @Override 4024 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4025 int flags) { 4026 ArrayList<InstrumentationInfo> finalList = 4027 new ArrayList<InstrumentationInfo>(); 4028 4029 // reader 4030 synchronized (mPackages) { 4031 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4032 while (i.hasNext()) { 4033 final PackageParser.Instrumentation p = i.next(); 4034 if (targetPackage == null 4035 || targetPackage.equals(p.info.targetPackage)) { 4036 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4037 flags); 4038 if (ii != null) { 4039 finalList.add(ii); 4040 } 4041 } 4042 } 4043 } 4044 4045 return finalList; 4046 } 4047 4048 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4049 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4050 if (overlays == null) { 4051 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4052 return; 4053 } 4054 for (PackageParser.Package opkg : overlays.values()) { 4055 // Not much to do if idmap fails: we already logged the error 4056 // and we certainly don't want to abort installation of pkg simply 4057 // because an overlay didn't fit properly. For these reasons, 4058 // ignore the return value of createIdmapForPackagePairLI. 4059 createIdmapForPackagePairLI(pkg, opkg); 4060 } 4061 } 4062 4063 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4064 PackageParser.Package opkg) { 4065 if (!opkg.mTrustedOverlay) { 4066 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4067 opkg.baseCodePath + ": overlay not trusted"); 4068 return false; 4069 } 4070 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4071 if (overlaySet == null) { 4072 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4073 opkg.baseCodePath + " but target package has no known overlays"); 4074 return false; 4075 } 4076 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4077 // TODO: generate idmap for split APKs 4078 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4079 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4080 + opkg.baseCodePath); 4081 return false; 4082 } 4083 PackageParser.Package[] overlayArray = 4084 overlaySet.values().toArray(new PackageParser.Package[0]); 4085 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4086 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4087 return p1.mOverlayPriority - p2.mOverlayPriority; 4088 } 4089 }; 4090 Arrays.sort(overlayArray, cmp); 4091 4092 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4093 int i = 0; 4094 for (PackageParser.Package p : overlayArray) { 4095 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4096 } 4097 return true; 4098 } 4099 4100 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4101 final File[] files = dir.listFiles(); 4102 if (ArrayUtils.isEmpty(files)) { 4103 Log.d(TAG, "No files in app dir " + dir); 4104 return; 4105 } 4106 4107 if (DEBUG_PACKAGE_SCANNING) { 4108 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4109 + " flags=0x" + Integer.toHexString(flags)); 4110 } 4111 4112 for (File file : files) { 4113 final boolean isPackage = isApkFile(file) || file.isDirectory(); 4114 if (!isPackage) { 4115 // Ignore entries which are not apk's 4116 continue; 4117 } 4118 PackageParser.Package pkg = scanPackageLI(file, 4119 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null, null); 4120 // Don't mess around with apps in system partition. 4121 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4122 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) { 4123 // Delete the apk 4124 Slog.w(TAG, "Cleaning up failed install of " + file); 4125 file.delete(); 4126 } 4127 } 4128 } 4129 4130 private static File getSettingsProblemFile() { 4131 File dataDir = Environment.getDataDirectory(); 4132 File systemDir = new File(dataDir, "system"); 4133 File fname = new File(systemDir, "uiderrors.txt"); 4134 return fname; 4135 } 4136 4137 static void reportSettingsProblem(int priority, String msg) { 4138 try { 4139 File fname = getSettingsProblemFile(); 4140 FileOutputStream out = new FileOutputStream(fname, true); 4141 PrintWriter pw = new FastPrintWriter(out); 4142 SimpleDateFormat formatter = new SimpleDateFormat(); 4143 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4144 pw.println(dateString + ": " + msg); 4145 pw.close(); 4146 FileUtils.setPermissions( 4147 fname.toString(), 4148 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4149 -1, -1); 4150 } catch (java.io.IOException e) { 4151 } 4152 Slog.println(priority, TAG, msg); 4153 } 4154 4155 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps, 4156 PackageParser.Package pkg, File srcFile, int parseFlags) { 4157 if (ps != null 4158 && ps.codePath.equals(srcFile) 4159 && ps.timeStamp == srcFile.lastModified() 4160 && !isCompatSignatureUpdateNeeded(pkg)) { 4161 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4162 if (ps.signatures.mSignatures != null 4163 && ps.signatures.mSignatures.length != 0 4164 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4165 // Optimization: reuse the existing cached certificates 4166 // if the package appears to be unchanged. 4167 pkg.mSignatures = ps.signatures.mSignatures; 4168 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4169 pkg.mSigningKeys = ksms.getPublicKeysFromKeySet(mSigningKeySetId); 4170 return true; 4171 } 4172 4173 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them."); 4174 } else { 4175 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4176 } 4177 4178 try { 4179 pp.collectCertificates(pkg, parseFlags); 4180 pp.collectManifestDigest(pkg); 4181 } catch (PackageParserException e) { 4182 mLastScanError = e.error; 4183 return false; 4184 } 4185 return true; 4186 } 4187 4188 /* 4189 * Scan a package and return the newly parsed package. 4190 * Returns null in case of errors and the error code is stored in mLastScanError 4191 */ 4192 private PackageParser.Package scanPackageLI(File scanFile, 4193 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 4194 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 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 mLastScanError = e.error; 4211 return null; 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 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4264 return null; 4265 } else { 4266 // The current app on the system partition is better than 4267 // what we have updated to on the data partition; switch 4268 // back to the system partition version. 4269 // At this point, its safely assumed that package installation for 4270 // apps in system partition will go through. If not there won't be a working 4271 // version of the app 4272 // writer 4273 synchronized (mPackages) { 4274 // Just remove the loaded entries from package lists. 4275 mPackages.remove(ps.name); 4276 } 4277 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4278 + "reverting from " + ps.codePathString 4279 + ": new version " + pkg.mVersionCode 4280 + " better than installed " + ps.versionCode); 4281 4282 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4283 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4284 getAppInstructionSetFromSettings(ps)); 4285 synchronized (mInstallLock) { 4286 args.cleanUpResourcesLI(); 4287 } 4288 synchronized (mPackages) { 4289 mSettings.enableSystemPackageLPw(ps.name); 4290 } 4291 updatedPkgBetter = true; 4292 } 4293 } 4294 } 4295 4296 if (updatedPkg != null) { 4297 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4298 // initially 4299 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4300 4301 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4302 // flag set initially 4303 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4304 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4305 } 4306 } 4307 // Verify certificates against what was last scanned 4308 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) { 4309 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName); 4310 return null; 4311 } 4312 4313 /* 4314 * A new system app appeared, but we already had a non-system one of the 4315 * same name installed earlier. 4316 */ 4317 boolean shouldHideSystemApp = false; 4318 if (updatedPkg == null && ps != null 4319 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4320 /* 4321 * Check to make sure the signatures match first. If they don't, 4322 * wipe the installed application and its data. 4323 */ 4324 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4325 != PackageManager.SIGNATURE_MATCH) { 4326 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4327 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4328 ps = null; 4329 } else { 4330 /* 4331 * If the newly-added system app is an older version than the 4332 * already installed version, hide it. It will be scanned later 4333 * and re-added like an update. 4334 */ 4335 if (pkg.mVersionCode < ps.versionCode) { 4336 shouldHideSystemApp = true; 4337 } else { 4338 /* 4339 * The newly found system app is a newer version that the 4340 * one previously installed. Simply remove the 4341 * already-installed application and replace it with our own 4342 * while keeping the application data. 4343 */ 4344 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4345 + ps.codePathString + ": new version " + pkg.mVersionCode 4346 + " better than installed " + ps.versionCode); 4347 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4348 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4349 getAppInstructionSetFromSettings(ps)); 4350 synchronized (mInstallLock) { 4351 args.cleanUpResourcesLI(); 4352 } 4353 } 4354 } 4355 } 4356 4357 // The apk is forward locked (not public) if its code and resources 4358 // are kept in different files. (except for app in either system or 4359 // vendor path). 4360 // TODO grab this value from PackageSettings 4361 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4362 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4363 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4364 } 4365 } 4366 4367 // TODO: extend to support forward-locked splits 4368 String resourcePath = null; 4369 String baseResourcePath = null; 4370 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4371 if (ps != null && ps.resourcePathString != null) { 4372 resourcePath = ps.resourcePathString; 4373 baseResourcePath = ps.resourcePathString; 4374 } else { 4375 // Should not happen at all. Just log an error. 4376 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4377 } 4378 } else { 4379 resourcePath = pkg.codePath; 4380 baseResourcePath = pkg.baseCodePath; 4381 } 4382 4383 // Set application objects path explicitly. 4384 pkg.applicationInfo.setCodePath(pkg.codePath); 4385 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4386 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4387 pkg.applicationInfo.setResourcePath(resourcePath); 4388 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4389 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4390 4391 // Note that we invoke the following method only if we are about to unpack an application 4392 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4393 | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride); 4394 4395 /* 4396 * If the system app should be overridden by a previously installed 4397 * data, hide the system app now and let the /data/app scan pick it up 4398 * again. 4399 */ 4400 if (shouldHideSystemApp) { 4401 synchronized (mPackages) { 4402 /* 4403 * We have to grant systems permissions before we hide, because 4404 * grantPermissions will assume the package update is trying to 4405 * expand its permissions. 4406 */ 4407 grantPermissionsLPw(pkg, true); 4408 mSettings.disableSystemPackageLPw(pkg.packageName); 4409 } 4410 } 4411 4412 return scannedPkg; 4413 } 4414 4415 private static String fixProcessName(String defProcessName, 4416 String processName, int uid) { 4417 if (processName == null) { 4418 return defProcessName; 4419 } 4420 return processName; 4421 } 4422 4423 private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) { 4424 if (pkgSetting.signatures.mSignatures != null) { 4425 // Already existing package. Make sure signatures match 4426 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4427 == PackageManager.SIGNATURE_MATCH; 4428 if (!match) { 4429 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4430 == PackageManager.SIGNATURE_MATCH; 4431 } 4432 if (!match) { 4433 Slog.e(TAG, "Package " + pkg.packageName 4434 + " signatures do not match the previously installed version; ignoring!"); 4435 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 4436 return false; 4437 } 4438 } 4439 4440 // Check for shared user signatures 4441 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4442 // Already existing package. Make sure signatures match 4443 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4444 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4445 if (!match) { 4446 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4447 == PackageManager.SIGNATURE_MATCH; 4448 } 4449 if (!match) { 4450 Slog.e(TAG, "Package " + pkg.packageName 4451 + " has no signatures that match those in shared user " 4452 + pkgSetting.sharedUser.name + "; ignoring!"); 4453 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 4454 return false; 4455 } 4456 } 4457 return true; 4458 } 4459 4460 /** 4461 * Enforces that only the system UID or root's UID can call a method exposed 4462 * via Binder. 4463 * 4464 * @param message used as message if SecurityException is thrown 4465 * @throws SecurityException if the caller is not system or root 4466 */ 4467 private static final void enforceSystemOrRoot(String message) { 4468 final int uid = Binder.getCallingUid(); 4469 if (uid != Process.SYSTEM_UID && uid != 0) { 4470 throw new SecurityException(message); 4471 } 4472 } 4473 4474 @Override 4475 public void performBootDexOpt() { 4476 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4477 4478 final HashSet<PackageParser.Package> pkgs; 4479 synchronized (mPackages) { 4480 pkgs = mDeferredDexOpt; 4481 mDeferredDexOpt = null; 4482 } 4483 4484 if (pkgs != null) { 4485 // Filter out packages that aren't recently used. 4486 // 4487 // The exception is first boot of a non-eng device, which 4488 // should do a full dexopt. 4489 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4490 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4491 // TODO: add a property to control this? 4492 long dexOptLRUThresholdInMinutes; 4493 if (eng) { 4494 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4495 } else { 4496 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4497 } 4498 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4499 4500 int total = pkgs.size(); 4501 int skipped = 0; 4502 long now = System.currentTimeMillis(); 4503 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4504 PackageParser.Package pkg = i.next(); 4505 long then = pkg.mLastPackageUsageTimeInMills; 4506 if (then + dexOptLRUThresholdInMills < now) { 4507 if (DEBUG_DEXOPT) { 4508 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4509 ((then == 0) ? "never" : new Date(then))); 4510 } 4511 i.remove(); 4512 skipped++; 4513 } 4514 } 4515 if (DEBUG_DEXOPT) { 4516 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4517 } 4518 } 4519 4520 int i = 0; 4521 for (PackageParser.Package pkg : pkgs) { 4522 i++; 4523 if (DEBUG_DEXOPT) { 4524 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4525 + ": " + pkg.packageName); 4526 } 4527 if (!isFirstBoot()) { 4528 try { 4529 ActivityManagerNative.getDefault().showBootMessage( 4530 mContext.getResources().getString( 4531 R.string.android_upgrading_apk, 4532 i, pkgs.size()), true); 4533 } catch (RemoteException e) { 4534 } 4535 } 4536 PackageParser.Package p = pkg; 4537 synchronized (mInstallLock) { 4538 if (p.mDexOptNeeded) { 4539 performDexOptLI(p, false /* force dex */, false /* defer */, 4540 true /* include dependencies */); 4541 } 4542 } 4543 } 4544 } 4545 } 4546 4547 @Override 4548 public boolean performDexOpt(String packageName) { 4549 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4550 return performDexOpt(packageName, true); 4551 } 4552 4553 public boolean performDexOpt(String packageName, boolean updateUsage) { 4554 4555 PackageParser.Package p; 4556 synchronized (mPackages) { 4557 p = mPackages.get(packageName); 4558 if (p == null) { 4559 return false; 4560 } 4561 if (updateUsage) { 4562 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4563 } 4564 mPackageUsage.write(false); 4565 if (!p.mDexOptNeeded) { 4566 return false; 4567 } 4568 } 4569 4570 synchronized (mInstallLock) { 4571 return performDexOptLI(p, false /* force dex */, false /* defer */, 4572 true /* include dependencies */) == DEX_OPT_PERFORMED; 4573 } 4574 } 4575 4576 public HashSet<String> getPackagesThatNeedDexOpt() { 4577 HashSet<String> pkgs = null; 4578 synchronized (mPackages) { 4579 for (PackageParser.Package p : mPackages.values()) { 4580 if (DEBUG_DEXOPT) { 4581 Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded); 4582 } 4583 if (!p.mDexOptNeeded) { 4584 continue; 4585 } 4586 if (pkgs == null) { 4587 pkgs = new HashSet<String>(); 4588 } 4589 pkgs.add(p.packageName); 4590 } 4591 } 4592 return pkgs; 4593 } 4594 4595 public void shutdown() { 4596 mPackageUsage.write(true); 4597 } 4598 4599 private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet, 4600 boolean forceDex, boolean defer, HashSet<String> done) { 4601 for (int i=0; i<libs.size(); i++) { 4602 PackageParser.Package libPkg; 4603 String libName; 4604 synchronized (mPackages) { 4605 libName = libs.get(i); 4606 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4607 if (lib != null && lib.apk != null) { 4608 libPkg = mPackages.get(lib.apk); 4609 } else { 4610 libPkg = null; 4611 } 4612 } 4613 if (libPkg != null && !done.contains(libName)) { 4614 performDexOptLI(libPkg, instructionSet, forceDex, defer, done); 4615 } 4616 } 4617 } 4618 4619 static final int DEX_OPT_SKIPPED = 0; 4620 static final int DEX_OPT_PERFORMED = 1; 4621 static final int DEX_OPT_DEFERRED = 2; 4622 static final int DEX_OPT_FAILED = -1; 4623 4624 private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride, 4625 boolean forceDex, boolean defer, HashSet<String> done) { 4626 final String instructionSet = instructionSetOverride != null ? 4627 instructionSetOverride : getAppInstructionSet(pkg.applicationInfo); 4628 4629 if (done != null) { 4630 done.add(pkg.packageName); 4631 if (pkg.usesLibraries != null) { 4632 performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done); 4633 } 4634 if (pkg.usesOptionalLibraries != null) { 4635 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done); 4636 } 4637 } 4638 4639 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0) { 4640 final Collection<String> paths = pkg.getAllCodePaths(); 4641 for (String path : paths) { 4642 try { 4643 boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path, 4644 pkg.packageName, instructionSet, defer); 4645 // There are three basic cases here: 4646 // 1.) we need to dexopt, either because we are forced or it is needed 4647 // 2.) we are defering a needed dexopt 4648 // 3.) we are skipping an unneeded dexopt 4649 if (forceDex || (!defer && isDexOptNeededInternal)) { 4650 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName); 4651 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4652 int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4653 pkg.packageName, instructionSet); 4654 // Note that we ran dexopt, since rerunning will 4655 // probably just result in an error again. 4656 pkg.mDexOptNeeded = false; 4657 if (ret < 0) { 4658 return DEX_OPT_FAILED; 4659 } 4660 return DEX_OPT_PERFORMED; 4661 } 4662 if (defer && isDexOptNeededInternal) { 4663 if (mDeferredDexOpt == null) { 4664 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4665 } 4666 mDeferredDexOpt.add(pkg); 4667 return DEX_OPT_DEFERRED; 4668 } 4669 pkg.mDexOptNeeded = false; 4670 return DEX_OPT_SKIPPED; 4671 } catch (FileNotFoundException e) { 4672 Slog.w(TAG, "Apk not found for dexopt: " + path); 4673 return DEX_OPT_FAILED; 4674 } catch (IOException e) { 4675 Slog.w(TAG, "IOException reading apk: " + path, e); 4676 return DEX_OPT_FAILED; 4677 } catch (StaleDexCacheError e) { 4678 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4679 return DEX_OPT_FAILED; 4680 } catch (Exception e) { 4681 Slog.w(TAG, "Exception when doing dexopt : ", e); 4682 return DEX_OPT_FAILED; 4683 } 4684 } 4685 } 4686 return DEX_OPT_SKIPPED; 4687 } 4688 4689 private String getAppInstructionSet(ApplicationInfo info) { 4690 String instructionSet = getPreferredInstructionSet(); 4691 4692 if (info.cpuAbi != null) { 4693 instructionSet = VMRuntime.getInstructionSet(info.cpuAbi); 4694 } 4695 4696 return instructionSet; 4697 } 4698 4699 private String getAppInstructionSetFromSettings(PackageSetting ps) { 4700 String instructionSet = getPreferredInstructionSet(); 4701 4702 if (ps.cpuAbiString != null) { 4703 instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString); 4704 } 4705 4706 return instructionSet; 4707 } 4708 4709 private static String getPreferredInstructionSet() { 4710 if (sPreferredInstructionSet == null) { 4711 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4712 } 4713 4714 return sPreferredInstructionSet; 4715 } 4716 4717 private static List<String> getAllInstructionSets() { 4718 final String[] allAbis = Build.SUPPORTED_ABIS; 4719 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4720 4721 for (String abi : allAbis) { 4722 final String instructionSet = VMRuntime.getInstructionSet(abi); 4723 if (!allInstructionSets.contains(instructionSet)) { 4724 allInstructionSets.add(instructionSet); 4725 } 4726 } 4727 4728 return allInstructionSets; 4729 } 4730 4731 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer, 4732 boolean inclDependencies) { 4733 HashSet<String> done; 4734 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4735 done = new HashSet<String>(); 4736 done.add(pkg.packageName); 4737 } else { 4738 done = null; 4739 } 4740 return performDexOptLI(pkg, null /* instruction set override */, forceDex, defer, done); 4741 } 4742 4743 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4744 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4745 Slog.w(TAG, "Unable to update from " + oldPkg.name 4746 + " to " + newPkg.packageName 4747 + ": old package not in system partition"); 4748 return false; 4749 } else if (mPackages.get(oldPkg.name) != null) { 4750 Slog.w(TAG, "Unable to update from " + oldPkg.name 4751 + " to " + newPkg.packageName 4752 + ": old package still exists"); 4753 return false; 4754 } 4755 return true; 4756 } 4757 4758 File getDataPathForUser(int userId) { 4759 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4760 } 4761 4762 private File getDataPathForPackage(String packageName, int userId) { 4763 /* 4764 * Until we fully support multiple users, return the directory we 4765 * previously would have. The PackageManagerTests will need to be 4766 * revised when this is changed back.. 4767 */ 4768 if (userId == 0) { 4769 return new File(mAppDataDir, packageName); 4770 } else { 4771 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4772 + File.separator + packageName); 4773 } 4774 } 4775 4776 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4777 int[] users = sUserManager.getUserIds(); 4778 int res = mInstaller.install(packageName, uid, uid, seinfo); 4779 if (res < 0) { 4780 return res; 4781 } 4782 for (int user : users) { 4783 if (user != 0) { 4784 res = mInstaller.createUserData(packageName, 4785 UserHandle.getUid(user, uid), user, seinfo); 4786 if (res < 0) { 4787 return res; 4788 } 4789 } 4790 } 4791 return res; 4792 } 4793 4794 private int removeDataDirsLI(String packageName) { 4795 int[] users = sUserManager.getUserIds(); 4796 int res = 0; 4797 for (int user : users) { 4798 int resInner = mInstaller.remove(packageName, user); 4799 if (resInner < 0) { 4800 res = resInner; 4801 } 4802 } 4803 4804 final File nativeLibraryFile = new File(mAppLibInstallDir, packageName); 4805 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 4806 if (!nativeLibraryFile.delete()) { 4807 Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath()); 4808 } 4809 4810 return res; 4811 } 4812 4813 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4814 PackageParser.Package changingLib) { 4815 if (file.path != null) { 4816 usesLibraryFiles.add(file.path); 4817 return; 4818 } 4819 PackageParser.Package p = mPackages.get(file.apk); 4820 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4821 // If we are doing this while in the middle of updating a library apk, 4822 // then we need to make sure to use that new apk for determining the 4823 // dependencies here. (We haven't yet finished committing the new apk 4824 // to the package manager state.) 4825 if (p == null || p.packageName.equals(changingLib.packageName)) { 4826 p = changingLib; 4827 } 4828 } 4829 if (p != null) { 4830 usesLibraryFiles.addAll(p.getAllCodePaths()); 4831 } 4832 } 4833 4834 private boolean updateSharedLibrariesLPw(PackageParser.Package pkg, 4835 PackageParser.Package changingLib) { 4836 // We might be upgrading from a version of the platform that did not 4837 // provide per-package native library directories for system apps. 4838 // Fix that up here. 4839 if (isSystemApp(pkg)) { 4840 PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName); 4841 setInternalAppNativeLibraryPath(pkg, ps); 4842 } 4843 4844 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4845 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4846 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4847 for (int i=0; i<N; i++) { 4848 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4849 if (file == null) { 4850 Slog.e(TAG, "Package " + pkg.packageName 4851 + " requires unavailable shared library " 4852 + pkg.usesLibraries.get(i) + "; failing!"); 4853 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 4854 return false; 4855 } 4856 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4857 } 4858 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4859 for (int i=0; i<N; i++) { 4860 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4861 if (file == null) { 4862 Slog.w(TAG, "Package " + pkg.packageName 4863 + " desires unavailable shared library " 4864 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4865 } else { 4866 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4867 } 4868 } 4869 N = usesLibraryFiles.size(); 4870 if (N > 0) { 4871 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4872 } else { 4873 pkg.usesLibraryFiles = null; 4874 } 4875 } 4876 return true; 4877 } 4878 4879 private static boolean hasString(List<String> list, List<String> which) { 4880 if (list == null) { 4881 return false; 4882 } 4883 for (int i=list.size()-1; i>=0; i--) { 4884 for (int j=which.size()-1; j>=0; j--) { 4885 if (which.get(j).equals(list.get(i))) { 4886 return true; 4887 } 4888 } 4889 } 4890 return false; 4891 } 4892 4893 private void updateAllSharedLibrariesLPw() { 4894 for (PackageParser.Package pkg : mPackages.values()) { 4895 updateSharedLibrariesLPw(pkg, null); 4896 } 4897 } 4898 4899 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4900 PackageParser.Package changingPkg) { 4901 ArrayList<PackageParser.Package> res = null; 4902 for (PackageParser.Package pkg : mPackages.values()) { 4903 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4904 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4905 if (res == null) { 4906 res = new ArrayList<PackageParser.Package>(); 4907 } 4908 res.add(pkg); 4909 updateSharedLibrariesLPw(pkg, changingPkg); 4910 } 4911 } 4912 return res; 4913 } 4914 4915 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, 4916 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 4917 final File scanFile = new File(pkg.codePath); 4918 if (pkg.applicationInfo.getCodePath() == null || 4919 pkg.applicationInfo.getResourcePath() == null) { 4920 // Bail out. The resource and code paths haven't been set. 4921 Slog.w(TAG, " Code and resource paths haven't been set correctly"); 4922 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK; 4923 return null; 4924 } 4925 4926 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4927 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4928 } 4929 4930 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4931 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4932 } 4933 4934 if (mCustomResolverComponentName != null && 4935 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4936 setUpCustomResolverActivity(pkg); 4937 } 4938 4939 if (pkg.packageName.equals("android")) { 4940 synchronized (mPackages) { 4941 if (mAndroidApplication != null) { 4942 Slog.w(TAG, "*************************************************"); 4943 Slog.w(TAG, "Core android package being redefined. Skipping."); 4944 Slog.w(TAG, " file=" + scanFile); 4945 Slog.w(TAG, "*************************************************"); 4946 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4947 return null; 4948 } 4949 4950 // Set up information for our fall-back user intent resolution activity. 4951 mPlatformPackage = pkg; 4952 pkg.mVersionCode = mSdkVersion; 4953 mAndroidApplication = pkg.applicationInfo; 4954 4955 if (!mResolverReplaced) { 4956 mResolveActivity.applicationInfo = mAndroidApplication; 4957 mResolveActivity.name = ResolverActivity.class.getName(); 4958 mResolveActivity.packageName = mAndroidApplication.packageName; 4959 mResolveActivity.processName = "system:ui"; 4960 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 4961 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 4962 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 4963 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 4964 mResolveActivity.exported = true; 4965 mResolveActivity.enabled = true; 4966 mResolveInfo.activityInfo = mResolveActivity; 4967 mResolveInfo.priority = 0; 4968 mResolveInfo.preferredOrder = 0; 4969 mResolveInfo.match = 0; 4970 mResolveComponentName = new ComponentName( 4971 mAndroidApplication.packageName, mResolveActivity.name); 4972 } 4973 } 4974 } 4975 4976 if (DEBUG_PACKAGE_SCANNING) { 4977 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4978 Log.d(TAG, "Scanning package " + pkg.packageName); 4979 } 4980 4981 if (mPackages.containsKey(pkg.packageName) 4982 || mSharedLibraries.containsKey(pkg.packageName)) { 4983 Slog.w(TAG, "Application package " + pkg.packageName 4984 + " already installed. Skipping duplicate."); 4985 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4986 return null; 4987 } 4988 4989 // Initialize package source and resource directories 4990 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 4991 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 4992 4993 SharedUserSetting suid = null; 4994 PackageSetting pkgSetting = null; 4995 4996 if (!isSystemApp(pkg)) { 4997 // Only system apps can use these features. 4998 pkg.mOriginalPackages = null; 4999 pkg.mRealPackage = null; 5000 pkg.mAdoptPermissions = null; 5001 } 5002 5003 // writer 5004 synchronized (mPackages) { 5005 if (pkg.mSharedUserId != null) { 5006 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5007 if (suid == null) { 5008 Slog.w(TAG, "Creating application package " + pkg.packageName 5009 + " for shared user failed"); 5010 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5011 return null; 5012 } 5013 if (DEBUG_PACKAGE_SCANNING) { 5014 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5015 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5016 + "): packages=" + suid.packages); 5017 } 5018 } 5019 5020 // Check if we are renaming from an original package name. 5021 PackageSetting origPackage = null; 5022 String realName = null; 5023 if (pkg.mOriginalPackages != null) { 5024 // This package may need to be renamed to a previously 5025 // installed name. Let's check on that... 5026 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5027 if (pkg.mOriginalPackages.contains(renamed)) { 5028 // This package had originally been installed as the 5029 // original name, and we have already taken care of 5030 // transitioning to the new one. Just update the new 5031 // one to continue using the old name. 5032 realName = pkg.mRealPackage; 5033 if (!pkg.packageName.equals(renamed)) { 5034 // Callers into this function may have already taken 5035 // care of renaming the package; only do it here if 5036 // it is not already done. 5037 pkg.setPackageName(renamed); 5038 } 5039 5040 } else { 5041 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5042 if ((origPackage = mSettings.peekPackageLPr( 5043 pkg.mOriginalPackages.get(i))) != null) { 5044 // We do have the package already installed under its 5045 // original name... should we use it? 5046 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5047 // New package is not compatible with original. 5048 origPackage = null; 5049 continue; 5050 } else if (origPackage.sharedUser != null) { 5051 // Make sure uid is compatible between packages. 5052 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5053 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5054 + " to " + pkg.packageName + ": old uid " 5055 + origPackage.sharedUser.name 5056 + " differs from " + pkg.mSharedUserId); 5057 origPackage = null; 5058 continue; 5059 } 5060 } else { 5061 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5062 + pkg.packageName + " to old name " + origPackage.name); 5063 } 5064 break; 5065 } 5066 } 5067 } 5068 } 5069 5070 if (mTransferedPackages.contains(pkg.packageName)) { 5071 Slog.w(TAG, "Package " + pkg.packageName 5072 + " was transferred to another, but its .apk remains"); 5073 } 5074 5075 // Just create the setting, don't add it yet. For already existing packages 5076 // the PkgSetting exists already and doesn't have to be created. 5077 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5078 destResourceFile, pkg.applicationInfo.nativeLibraryDir, 5079 pkg.applicationInfo.cpuAbi, 5080 pkg.applicationInfo.flags, user, false); 5081 if (pkgSetting == null) { 5082 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed"); 5083 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5084 return null; 5085 } 5086 5087 if (pkgSetting.origPackage != null) { 5088 // If we are first transitioning from an original package, 5089 // fix up the new package's name now. We need to do this after 5090 // looking up the package under its new name, so getPackageLP 5091 // can take care of fiddling things correctly. 5092 pkg.setPackageName(origPackage.name); 5093 5094 // File a report about this. 5095 String msg = "New package " + pkgSetting.realName 5096 + " renamed to replace old package " + pkgSetting.name; 5097 reportSettingsProblem(Log.WARN, msg); 5098 5099 // Make a note of it. 5100 mTransferedPackages.add(origPackage.name); 5101 5102 // No longer need to retain this. 5103 pkgSetting.origPackage = null; 5104 } 5105 5106 if (realName != null) { 5107 // Make a note of it. 5108 mTransferedPackages.add(pkg.packageName); 5109 } 5110 5111 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5112 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5113 } 5114 5115 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5116 // Check all shared libraries and map to their actual file path. 5117 // We only do this here for apps not on a system dir, because those 5118 // are the only ones that can fail an install due to this. We 5119 // will take care of the system apps by updating all of their 5120 // library paths after the scan is done. 5121 if (!updateSharedLibrariesLPw(pkg, null)) { 5122 return null; 5123 } 5124 } 5125 5126 if (mFoundPolicyFile) { 5127 SELinuxMMAC.assignSeinfoValue(pkg); 5128 } 5129 5130 pkg.applicationInfo.uid = pkgSetting.appId; 5131 pkg.mExtras = pkgSetting; 5132 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5133 if (!verifySignaturesLP(pkgSetting, pkg)) { 5134 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5135 return null; 5136 } 5137 // The signature has changed, but this package is in the system 5138 // image... let's recover! 5139 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5140 // However... if this package is part of a shared user, but it 5141 // doesn't match the signature of the shared user, let's fail. 5142 // What this means is that you can't change the signatures 5143 // associated with an overall shared user, which doesn't seem all 5144 // that unreasonable. 5145 if (pkgSetting.sharedUser != null) { 5146 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5147 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5148 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser); 5149 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 5150 return null; 5151 } 5152 } 5153 // File a report about this. 5154 String msg = "System package " + pkg.packageName 5155 + " signature changed; retaining data."; 5156 reportSettingsProblem(Log.WARN, msg); 5157 } 5158 } else { 5159 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5160 Slog.e(TAG, "Package " + pkg.packageName 5161 + " upgrade keys do not match the previously installed version; "); 5162 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 5163 return null; 5164 } else { 5165 // signatures may have changed as result of upgrade 5166 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5167 } 5168 } 5169 // Verify that this new package doesn't have any content providers 5170 // that conflict with existing packages. Only do this if the 5171 // package isn't already installed, since we don't want to break 5172 // things that are installed. 5173 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5174 final int N = pkg.providers.size(); 5175 int i; 5176 for (i=0; i<N; i++) { 5177 PackageParser.Provider p = pkg.providers.get(i); 5178 if (p.info.authority != null) { 5179 String names[] = p.info.authority.split(";"); 5180 for (int j = 0; j < names.length; j++) { 5181 if (mProvidersByAuthority.containsKey(names[j])) { 5182 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5183 Slog.w(TAG, "Can't install because provider name " + names[j] + 5184 " (in package " + pkg.applicationInfo.packageName + 5185 ") is already used by " 5186 + ((other != null && other.getComponentName() != null) 5187 ? other.getComponentName().getPackageName() : "?")); 5188 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 5189 return null; 5190 } 5191 } 5192 } 5193 } 5194 } 5195 5196 if (pkg.mAdoptPermissions != null) { 5197 // This package wants to adopt ownership of permissions from 5198 // another package. 5199 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5200 final String origName = pkg.mAdoptPermissions.get(i); 5201 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5202 if (orig != null) { 5203 if (verifyPackageUpdateLPr(orig, pkg)) { 5204 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5205 + pkg.packageName); 5206 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5207 } 5208 } 5209 } 5210 } 5211 } 5212 5213 final String pkgName = pkg.packageName; 5214 5215 final long scanFileTime = scanFile.lastModified(); 5216 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5217 pkg.applicationInfo.processName = fixProcessName( 5218 pkg.applicationInfo.packageName, 5219 pkg.applicationInfo.processName, 5220 pkg.applicationInfo.uid); 5221 5222 File dataPath; 5223 if (mPlatformPackage == pkg) { 5224 // The system package is special. 5225 dataPath = new File (Environment.getDataDirectory(), "system"); 5226 pkg.applicationInfo.dataDir = dataPath.getPath(); 5227 } else { 5228 // This is a normal package, need to make its data directory. 5229 dataPath = getDataPathForPackage(pkg.packageName, 0); 5230 5231 boolean uidError = false; 5232 5233 if (dataPath.exists()) { 5234 int currentUid = 0; 5235 try { 5236 StructStat stat = Os.stat(dataPath.getPath()); 5237 currentUid = stat.st_uid; 5238 } catch (ErrnoException e) { 5239 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5240 } 5241 5242 // If we have mismatched owners for the data path, we have a problem. 5243 if (currentUid != pkg.applicationInfo.uid) { 5244 boolean recovered = false; 5245 if (currentUid == 0) { 5246 // The directory somehow became owned by root. Wow. 5247 // This is probably because the system was stopped while 5248 // installd was in the middle of messing with its libs 5249 // directory. Ask installd to fix that. 5250 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5251 pkg.applicationInfo.uid); 5252 if (ret >= 0) { 5253 recovered = true; 5254 String msg = "Package " + pkg.packageName 5255 + " unexpectedly changed to uid 0; recovered to " + 5256 + pkg.applicationInfo.uid; 5257 reportSettingsProblem(Log.WARN, msg); 5258 } 5259 } 5260 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5261 || (scanMode&SCAN_BOOTING) != 0)) { 5262 // If this is a system app, we can at least delete its 5263 // current data so the application will still work. 5264 int ret = removeDataDirsLI(pkgName); 5265 if (ret >= 0) { 5266 // TODO: Kill the processes first 5267 // Old data gone! 5268 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5269 ? "System package " : "Third party package "; 5270 String msg = prefix + pkg.packageName 5271 + " has changed from uid: " 5272 + currentUid + " to " 5273 + pkg.applicationInfo.uid + "; old data erased"; 5274 reportSettingsProblem(Log.WARN, msg); 5275 recovered = true; 5276 5277 // And now re-install the app. 5278 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5279 pkg.applicationInfo.seinfo); 5280 if (ret == -1) { 5281 // Ack should not happen! 5282 msg = prefix + pkg.packageName 5283 + " could not have data directory re-created after delete."; 5284 reportSettingsProblem(Log.WARN, msg); 5285 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5286 return null; 5287 } 5288 } 5289 if (!recovered) { 5290 mHasSystemUidErrors = true; 5291 } 5292 } else if (!recovered) { 5293 // If we allow this install to proceed, we will be broken. 5294 // Abort, abort! 5295 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED; 5296 return null; 5297 } 5298 if (!recovered) { 5299 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5300 + pkg.applicationInfo.uid + "/fs_" 5301 + currentUid; 5302 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5303 String msg = "Package " + pkg.packageName 5304 + " has mismatched uid: " 5305 + currentUid + " on disk, " 5306 + pkg.applicationInfo.uid + " in settings"; 5307 // writer 5308 synchronized (mPackages) { 5309 mSettings.mReadMessages.append(msg); 5310 mSettings.mReadMessages.append('\n'); 5311 uidError = true; 5312 if (!pkgSetting.uidError) { 5313 reportSettingsProblem(Log.ERROR, msg); 5314 } 5315 } 5316 } 5317 } 5318 pkg.applicationInfo.dataDir = dataPath.getPath(); 5319 if (mShouldRestoreconData) { 5320 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5321 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5322 pkg.applicationInfo.uid); 5323 } 5324 } else { 5325 if (DEBUG_PACKAGE_SCANNING) { 5326 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5327 Log.v(TAG, "Want this data dir: " + dataPath); 5328 } 5329 //invoke installer to do the actual installation 5330 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5331 pkg.applicationInfo.seinfo); 5332 if (ret < 0) { 5333 // Error from installer 5334 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5335 return null; 5336 } 5337 5338 if (dataPath.exists()) { 5339 pkg.applicationInfo.dataDir = dataPath.getPath(); 5340 } else { 5341 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5342 pkg.applicationInfo.dataDir = null; 5343 } 5344 } 5345 5346 /* 5347 * Set the data dir to the default "/data/data/<package name>/lib" 5348 * if we got here without anyone telling us different (e.g., apps 5349 * stored on SD card have their native libraries stored in the ASEC 5350 * container with the APK). 5351 * 5352 * This happens during an upgrade from a package settings file that 5353 * doesn't have a native library path attribute at all. 5354 */ 5355 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) { 5356 if (pkgSetting.nativeLibraryPathString == null) { 5357 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5358 } else { 5359 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString; 5360 } 5361 } 5362 pkgSetting.uidError = uidError; 5363 } 5364 5365 final String path = scanFile.getPath(); 5366 /* Note: We don't want to unpack the native binaries for 5367 * system applications, unless they have been updated 5368 * (the binaries are already under /system/lib). 5369 * Also, don't unpack libs for apps on the external card 5370 * since they should have their libraries in the ASEC 5371 * container already. 5372 * 5373 * In other words, we're going to unpack the binaries 5374 * only for non-system apps and system app upgrades. 5375 */ 5376 if (pkg.applicationInfo.nativeLibraryDir != null) { 5377 NativeLibraryHelper.Handle handle = null; 5378 try { 5379 handle = NativeLibraryHelper.Handle.create(scanFile); 5380 // Enable gross and lame hacks for apps that are built with old 5381 // SDK tools. We must scan their APKs for renderscript bitcode and 5382 // not launch them if it's present. Don't bother checking on devices 5383 // that don't have 64 bit support. 5384 String[] abiList = Build.SUPPORTED_ABIS; 5385 boolean hasLegacyRenderscriptBitcode = false; 5386 if (abiOverride != null) { 5387 abiList = new String[] { abiOverride }; 5388 } else if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && 5389 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5390 abiList = Build.SUPPORTED_32_BIT_ABIS; 5391 hasLegacyRenderscriptBitcode = true; 5392 } 5393 5394 File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5395 final String dataPathString = dataPath.getCanonicalPath(); 5396 5397 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5398 /* 5399 * Upgrading from a previous version of the OS sometimes 5400 * leaves native libraries in the /data/data/<app>/lib 5401 * directory for system apps even when they shouldn't be. 5402 * Recent changes in the JNI library search path 5403 * necessitates we remove those to match previous behavior. 5404 */ 5405 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) { 5406 Log.i(TAG, "removed obsolete native libraries for system package " 5407 + path); 5408 } 5409 if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5410 pkg.applicationInfo.cpuAbi = abiList[0]; 5411 pkgSetting.cpuAbiString = abiList[0]; 5412 } else { 5413 setInternalAppAbi(pkg, pkgSetting); 5414 } 5415 } else { 5416 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 5417 /* 5418 * Update native library dir if it starts with 5419 * /data/data 5420 */ 5421 if (nativeLibraryDir.getPath().startsWith(dataPathString)) { 5422 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5423 nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5424 } 5425 5426 try { 5427 int copyRet = copyNativeLibrariesForInternalApp(handle, 5428 nativeLibraryDir, abiList); 5429 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5430 Slog.e(TAG, "Unable to copy native libraries"); 5431 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5432 return null; 5433 } 5434 5435 // We've successfully copied native libraries across, so we make a 5436 // note of what ABI we're using 5437 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5438 pkg.applicationInfo.cpuAbi = abiList[copyRet]; 5439 } else if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5440 pkg.applicationInfo.cpuAbi = abiList[0]; 5441 } else { 5442 pkg.applicationInfo.cpuAbi = null; 5443 } 5444 } catch (IOException e) { 5445 Slog.e(TAG, "Unable to copy native libraries", e); 5446 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5447 return null; 5448 } 5449 } else { 5450 // We don't have to copy the shared libraries if we're in the ASEC container 5451 // but we still need to scan the file to figure out what ABI the app needs. 5452 // 5453 // TODO: This duplicates work done in the default container service. It's possible 5454 // to clean this up but we'll need to change the interface between this service 5455 // and IMediaContainerService (but doing so will spread this logic out, rather 5456 // than centralizing it). 5457 final int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5458 if (abi >= 0) { 5459 pkg.applicationInfo.cpuAbi = abiList[abi]; 5460 } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) { 5461 // Note that (non upgraded) system apps will not have any native 5462 // libraries bundled in their APK, but we're guaranteed not to be 5463 // such an app at this point. 5464 if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5465 pkg.applicationInfo.cpuAbi = abiList[0]; 5466 } else { 5467 pkg.applicationInfo.cpuAbi = null; 5468 } 5469 } else { 5470 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5471 return null; 5472 } 5473 } 5474 5475 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5476 final int[] userIds = sUserManager.getUserIds(); 5477 synchronized (mInstallLock) { 5478 for (int userId : userIds) { 5479 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 5480 pkg.applicationInfo.nativeLibraryDir, userId) < 0) { 5481 Slog.w(TAG, "Failed linking native library dir (user=" + userId 5482 + ")"); 5483 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5484 return null; 5485 } 5486 } 5487 } 5488 } 5489 5490 pkgSetting.cpuAbiString = pkg.applicationInfo.cpuAbi; 5491 } catch (IOException ioe) { 5492 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5493 } finally { 5494 IoUtils.closeQuietly(handle); 5495 } 5496 } 5497 5498 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5499 // We don't do this here during boot because we can do it all 5500 // at once after scanning all existing packages. 5501 // 5502 // We also do this *before* we perform dexopt on this package, so that 5503 // we can avoid redundant dexopts, and also to make sure we've got the 5504 // code and package path correct. 5505 if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5506 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) { 5507 mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE; 5508 return null; 5509 } 5510 } 5511 5512 if ((scanMode&SCAN_NO_DEX) == 0) { 5513 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5514 == DEX_OPT_FAILED) { 5515 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5516 removeDataDirsLI(pkg.packageName); 5517 } 5518 5519 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5520 return null; 5521 } 5522 } 5523 5524 if (mFactoryTest && pkg.requestedPermissions.contains( 5525 android.Manifest.permission.FACTORY_TEST)) { 5526 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5527 } 5528 5529 ArrayList<PackageParser.Package> clientLibPkgs = null; 5530 5531 // writer 5532 synchronized (mPackages) { 5533 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5534 // Only system apps can add new shared libraries. 5535 if (pkg.libraryNames != null) { 5536 for (int i=0; i<pkg.libraryNames.size(); i++) { 5537 String name = pkg.libraryNames.get(i); 5538 boolean allowed = false; 5539 if (isUpdatedSystemApp(pkg)) { 5540 // New library entries can only be added through the 5541 // system image. This is important to get rid of a lot 5542 // of nasty edge cases: for example if we allowed a non- 5543 // system update of the app to add a library, then uninstalling 5544 // the update would make the library go away, and assumptions 5545 // we made such as through app install filtering would now 5546 // have allowed apps on the device which aren't compatible 5547 // with it. Better to just have the restriction here, be 5548 // conservative, and create many fewer cases that can negatively 5549 // impact the user experience. 5550 final PackageSetting sysPs = mSettings 5551 .getDisabledSystemPkgLPr(pkg.packageName); 5552 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5553 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5554 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5555 allowed = true; 5556 allowed = true; 5557 break; 5558 } 5559 } 5560 } 5561 } else { 5562 allowed = true; 5563 } 5564 if (allowed) { 5565 if (!mSharedLibraries.containsKey(name)) { 5566 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5567 } else if (!name.equals(pkg.packageName)) { 5568 Slog.w(TAG, "Package " + pkg.packageName + " library " 5569 + name + " already exists; skipping"); 5570 } 5571 } else { 5572 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5573 + name + " that is not declared on system image; skipping"); 5574 } 5575 } 5576 if ((scanMode&SCAN_BOOTING) == 0) { 5577 // If we are not booting, we need to update any applications 5578 // that are clients of our shared library. If we are booting, 5579 // this will all be done once the scan is complete. 5580 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5581 } 5582 } 5583 } 5584 } 5585 5586 // We also need to dexopt any apps that are dependent on this library. Note that 5587 // if these fail, we should abort the install since installing the library will 5588 // result in some apps being broken. 5589 if (clientLibPkgs != null) { 5590 if ((scanMode&SCAN_NO_DEX) == 0) { 5591 for (int i=0; i<clientLibPkgs.size(); i++) { 5592 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5593 if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5594 == DEX_OPT_FAILED) { 5595 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5596 removeDataDirsLI(pkg.packageName); 5597 } 5598 5599 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5600 return null; 5601 } 5602 } 5603 } 5604 } 5605 5606 // Request the ActivityManager to kill the process(only for existing packages) 5607 // so that we do not end up in a confused state while the user is still using the older 5608 // version of the application while the new one gets installed. 5609 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5610 // If the package lives in an asec, tell everyone that the container is going 5611 // away so they can clean up any references to its resources (which would prevent 5612 // vold from being able to unmount the asec) 5613 if (isForwardLocked(pkg) || isExternal(pkg)) { 5614 if (DEBUG_INSTALL) { 5615 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5616 } 5617 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5618 final ArrayList<String> pkgList = new ArrayList<String>(1); 5619 pkgList.add(pkg.applicationInfo.packageName); 5620 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5621 } 5622 5623 // Post the request that it be killed now that the going-away broadcast is en route 5624 killApplication(pkg.applicationInfo.packageName, 5625 pkg.applicationInfo.uid, "update pkg"); 5626 } 5627 5628 // Also need to kill any apps that are dependent on the library. 5629 if (clientLibPkgs != null) { 5630 for (int i=0; i<clientLibPkgs.size(); i++) { 5631 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5632 killApplication(clientPkg.applicationInfo.packageName, 5633 clientPkg.applicationInfo.uid, "update lib"); 5634 } 5635 } 5636 5637 // writer 5638 synchronized (mPackages) { 5639 // We don't expect installation to fail beyond this point, 5640 if ((scanMode&SCAN_MONITOR) != 0) { 5641 mAppDirs.put(pkg.codePath, pkg); 5642 } 5643 // Add the new setting to mSettings 5644 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5645 // Add the new setting to mPackages 5646 mPackages.put(pkg.applicationInfo.packageName, pkg); 5647 // Make sure we don't accidentally delete its data. 5648 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5649 while (iter.hasNext()) { 5650 PackageCleanItem item = iter.next(); 5651 if (pkgName.equals(item.packageName)) { 5652 iter.remove(); 5653 } 5654 } 5655 5656 // Take care of first install / last update times. 5657 if (currentTime != 0) { 5658 if (pkgSetting.firstInstallTime == 0) { 5659 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5660 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5661 pkgSetting.lastUpdateTime = currentTime; 5662 } 5663 } else if (pkgSetting.firstInstallTime == 0) { 5664 // We need *something*. Take time time stamp of the file. 5665 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5666 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5667 if (scanFileTime != pkgSetting.timeStamp) { 5668 // A package on the system image has changed; consider this 5669 // to be an update. 5670 pkgSetting.lastUpdateTime = scanFileTime; 5671 } 5672 } 5673 5674 // Add the package's KeySets to the global KeySetManagerService 5675 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5676 try { 5677 // Old KeySetData no longer valid. 5678 ksms.removeAppKeySetData(pkg.packageName); 5679 ksms.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys); 5680 if (pkg.mKeySetMapping != null) { 5681 for (Map.Entry<String, Set<PublicKey>> entry : 5682 pkg.mKeySetMapping.entrySet()) { 5683 if (entry.getValue() != null) { 5684 ksms.addDefinedKeySetToPackage(pkg.packageName, 5685 entry.getValue(), entry.getKey()); 5686 } 5687 } 5688 if (pkg.mUpgradeKeySets != null 5689 && pkg.mKeySetMapping.keySet().containsAll(pkg.mUpgradeKeySets)) { 5690 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5691 ksms.addUpgradeKeySetToPackage(pkg.packageName, upgradeAlias); 5692 } 5693 } 5694 } 5695 } catch (NullPointerException e) { 5696 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5697 } catch (IllegalArgumentException e) { 5698 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5699 } 5700 5701 int N = pkg.providers.size(); 5702 StringBuilder r = null; 5703 int i; 5704 for (i=0; i<N; i++) { 5705 PackageParser.Provider p = pkg.providers.get(i); 5706 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5707 p.info.processName, pkg.applicationInfo.uid); 5708 mProviders.addProvider(p); 5709 p.syncable = p.info.isSyncable; 5710 if (p.info.authority != null) { 5711 String names[] = p.info.authority.split(";"); 5712 p.info.authority = null; 5713 for (int j = 0; j < names.length; j++) { 5714 if (j == 1 && p.syncable) { 5715 // We only want the first authority for a provider to possibly be 5716 // syncable, so if we already added this provider using a different 5717 // authority clear the syncable flag. We copy the provider before 5718 // changing it because the mProviders object contains a reference 5719 // to a provider that we don't want to change. 5720 // Only do this for the second authority since the resulting provider 5721 // object can be the same for all future authorities for this provider. 5722 p = new PackageParser.Provider(p); 5723 p.syncable = false; 5724 } 5725 if (!mProvidersByAuthority.containsKey(names[j])) { 5726 mProvidersByAuthority.put(names[j], p); 5727 if (p.info.authority == null) { 5728 p.info.authority = names[j]; 5729 } else { 5730 p.info.authority = p.info.authority + ";" + names[j]; 5731 } 5732 if (DEBUG_PACKAGE_SCANNING) { 5733 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5734 Log.d(TAG, "Registered content provider: " + names[j] 5735 + ", className = " + p.info.name + ", isSyncable = " 5736 + p.info.isSyncable); 5737 } 5738 } else { 5739 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5740 Slog.w(TAG, "Skipping provider name " + names[j] + 5741 " (in package " + pkg.applicationInfo.packageName + 5742 "): name already used by " 5743 + ((other != null && other.getComponentName() != null) 5744 ? other.getComponentName().getPackageName() : "?")); 5745 } 5746 } 5747 } 5748 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5749 if (r == null) { 5750 r = new StringBuilder(256); 5751 } else { 5752 r.append(' '); 5753 } 5754 r.append(p.info.name); 5755 } 5756 } 5757 if (r != null) { 5758 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5759 } 5760 5761 N = pkg.services.size(); 5762 r = null; 5763 for (i=0; i<N; i++) { 5764 PackageParser.Service s = pkg.services.get(i); 5765 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5766 s.info.processName, pkg.applicationInfo.uid); 5767 mServices.addService(s); 5768 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5769 if (r == null) { 5770 r = new StringBuilder(256); 5771 } else { 5772 r.append(' '); 5773 } 5774 r.append(s.info.name); 5775 } 5776 } 5777 if (r != null) { 5778 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5779 } 5780 5781 N = pkg.receivers.size(); 5782 r = null; 5783 for (i=0; i<N; i++) { 5784 PackageParser.Activity a = pkg.receivers.get(i); 5785 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5786 a.info.processName, pkg.applicationInfo.uid); 5787 mReceivers.addActivity(a, "receiver"); 5788 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5789 if (r == null) { 5790 r = new StringBuilder(256); 5791 } else { 5792 r.append(' '); 5793 } 5794 r.append(a.info.name); 5795 } 5796 } 5797 if (r != null) { 5798 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5799 } 5800 5801 N = pkg.activities.size(); 5802 r = null; 5803 for (i=0; i<N; i++) { 5804 PackageParser.Activity a = pkg.activities.get(i); 5805 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5806 a.info.processName, pkg.applicationInfo.uid); 5807 mActivities.addActivity(a, "activity"); 5808 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5809 if (r == null) { 5810 r = new StringBuilder(256); 5811 } else { 5812 r.append(' '); 5813 } 5814 r.append(a.info.name); 5815 } 5816 } 5817 if (r != null) { 5818 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5819 } 5820 5821 N = pkg.permissionGroups.size(); 5822 r = null; 5823 for (i=0; i<N; i++) { 5824 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5825 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5826 if (cur == null) { 5827 mPermissionGroups.put(pg.info.name, pg); 5828 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5829 if (r == null) { 5830 r = new StringBuilder(256); 5831 } else { 5832 r.append(' '); 5833 } 5834 r.append(pg.info.name); 5835 } 5836 } else { 5837 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5838 + pg.info.packageName + " ignored: original from " 5839 + cur.info.packageName); 5840 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5841 if (r == null) { 5842 r = new StringBuilder(256); 5843 } else { 5844 r.append(' '); 5845 } 5846 r.append("DUP:"); 5847 r.append(pg.info.name); 5848 } 5849 } 5850 } 5851 if (r != null) { 5852 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5853 } 5854 5855 N = pkg.permissions.size(); 5856 r = null; 5857 for (i=0; i<N; i++) { 5858 PackageParser.Permission p = pkg.permissions.get(i); 5859 HashMap<String, BasePermission> permissionMap = 5860 p.tree ? mSettings.mPermissionTrees 5861 : mSettings.mPermissions; 5862 p.group = mPermissionGroups.get(p.info.group); 5863 if (p.info.group == null || p.group != null) { 5864 BasePermission bp = permissionMap.get(p.info.name); 5865 if (bp == null) { 5866 bp = new BasePermission(p.info.name, p.info.packageName, 5867 BasePermission.TYPE_NORMAL); 5868 permissionMap.put(p.info.name, bp); 5869 } 5870 if (bp.perm == null) { 5871 if (bp.sourcePackage != null 5872 && !bp.sourcePackage.equals(p.info.packageName)) { 5873 // If this is a permission that was formerly defined by a non-system 5874 // app, but is now defined by a system app (following an upgrade), 5875 // discard the previous declaration and consider the system's to be 5876 // canonical. 5877 if (isSystemApp(p.owner)) { 5878 String msg = "New decl " + p.owner + " of permission " 5879 + p.info.name + " is system"; 5880 reportSettingsProblem(Log.WARN, msg); 5881 bp.sourcePackage = null; 5882 } 5883 } 5884 if (bp.sourcePackage == null 5885 || bp.sourcePackage.equals(p.info.packageName)) { 5886 BasePermission tree = findPermissionTreeLP(p.info.name); 5887 if (tree == null 5888 || tree.sourcePackage.equals(p.info.packageName)) { 5889 bp.packageSetting = pkgSetting; 5890 bp.perm = p; 5891 bp.uid = pkg.applicationInfo.uid; 5892 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5893 if (r == null) { 5894 r = new StringBuilder(256); 5895 } else { 5896 r.append(' '); 5897 } 5898 r.append(p.info.name); 5899 } 5900 } else { 5901 Slog.w(TAG, "Permission " + p.info.name + " from package " 5902 + p.info.packageName + " ignored: base tree " 5903 + tree.name + " is from package " 5904 + tree.sourcePackage); 5905 } 5906 } else { 5907 Slog.w(TAG, "Permission " + p.info.name + " from package " 5908 + p.info.packageName + " ignored: original from " 5909 + bp.sourcePackage); 5910 } 5911 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5912 if (r == null) { 5913 r = new StringBuilder(256); 5914 } else { 5915 r.append(' '); 5916 } 5917 r.append("DUP:"); 5918 r.append(p.info.name); 5919 } 5920 if (bp.perm == p) { 5921 bp.protectionLevel = p.info.protectionLevel; 5922 } 5923 } else { 5924 Slog.w(TAG, "Permission " + p.info.name + " from package " 5925 + p.info.packageName + " ignored: no group " 5926 + p.group); 5927 } 5928 } 5929 if (r != null) { 5930 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 5931 } 5932 5933 N = pkg.instrumentation.size(); 5934 r = null; 5935 for (i=0; i<N; i++) { 5936 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5937 a.info.packageName = pkg.applicationInfo.packageName; 5938 a.info.sourceDir = pkg.applicationInfo.sourceDir; 5939 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 5940 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 5941 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 5942 a.info.dataDir = pkg.applicationInfo.dataDir; 5943 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 5944 mInstrumentation.put(a.getComponentName(), a); 5945 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5946 if (r == null) { 5947 r = new StringBuilder(256); 5948 } else { 5949 r.append(' '); 5950 } 5951 r.append(a.info.name); 5952 } 5953 } 5954 if (r != null) { 5955 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 5956 } 5957 5958 if (pkg.protectedBroadcasts != null) { 5959 N = pkg.protectedBroadcasts.size(); 5960 for (i=0; i<N; i++) { 5961 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 5962 } 5963 } 5964 5965 pkgSetting.setTimeStamp(scanFileTime); 5966 5967 // Create idmap files for pairs of (packages, overlay packages). 5968 // Note: "android", ie framework-res.apk, is handled by native layers. 5969 if (pkg.mOverlayTarget != null) { 5970 // This is an overlay package. 5971 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 5972 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 5973 mOverlays.put(pkg.mOverlayTarget, 5974 new HashMap<String, PackageParser.Package>()); 5975 } 5976 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 5977 map.put(pkg.packageName, pkg); 5978 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 5979 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 5980 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 5981 return null; 5982 } 5983 } 5984 } else if (mOverlays.containsKey(pkg.packageName) && 5985 !pkg.packageName.equals("android")) { 5986 // This is a regular package, with one or more known overlay packages. 5987 createIdmapsForPackageLI(pkg); 5988 } 5989 } 5990 5991 return pkg; 5992 } 5993 5994 /** 5995 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 5996 * i.e, so that all packages can be run inside a single process if required. 5997 * 5998 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 5999 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6000 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6001 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6002 * updating a package that belongs to a shared user. 6003 */ 6004 private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6005 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6006 String requiredInstructionSet = null; 6007 if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) { 6008 requiredInstructionSet = VMRuntime.getInstructionSet( 6009 scannedPackage.applicationInfo.cpuAbi); 6010 } 6011 6012 PackageSetting requirer = null; 6013 for (PackageSetting ps : packagesForUser) { 6014 // If packagesForUser contains scannedPackage, we skip it. This will happen 6015 // when scannedPackage is an update of an existing package. Without this check, 6016 // we will never be able to change the ABI of any package belonging to a shared 6017 // user, even if it's compatible with other packages. 6018 if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) { 6019 if (ps.cpuAbiString == null) { 6020 continue; 6021 } 6022 6023 final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString); 6024 if (requiredInstructionSet != null) { 6025 if (!instructionSet.equals(requiredInstructionSet)) { 6026 // We have a mismatch between instruction sets (say arm vs arm64). 6027 // bail out. 6028 String errorMessage = "Instruction set mismatch, " 6029 + ((requirer == null) ? "[caller]" : requirer) 6030 + " requires " + requiredInstructionSet + " whereas " + ps 6031 + " requires " + instructionSet; 6032 Slog.e(TAG, errorMessage); 6033 6034 reportSettingsProblem(Log.WARN, errorMessage); 6035 // Give up, don't bother making any other changes to the package settings. 6036 return false; 6037 } 6038 } else { 6039 requiredInstructionSet = instructionSet; 6040 requirer = ps; 6041 } 6042 } 6043 } 6044 6045 if (requiredInstructionSet != null) { 6046 String adjustedAbi; 6047 if (requirer != null) { 6048 // requirer != null implies that either scannedPackage was null or that scannedPackage 6049 // did not require an ABI, in which case we have to adjust scannedPackage to match 6050 // the ABI of the set (which is the same as requirer's ABI) 6051 adjustedAbi = requirer.cpuAbiString; 6052 if (scannedPackage != null) { 6053 scannedPackage.applicationInfo.cpuAbi = adjustedAbi; 6054 } 6055 } else { 6056 // requirer == null implies that we're updating all ABIs in the set to 6057 // match scannedPackage. 6058 adjustedAbi = scannedPackage.applicationInfo.cpuAbi; 6059 } 6060 6061 for (PackageSetting ps : packagesForUser) { 6062 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6063 if (ps.cpuAbiString != null) { 6064 continue; 6065 } 6066 6067 ps.cpuAbiString = adjustedAbi; 6068 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6069 ps.pkg.applicationInfo.cpuAbi = adjustedAbi; 6070 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6071 6072 if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) { 6073 ps.cpuAbiString = null; 6074 ps.pkg.applicationInfo.cpuAbi = null; 6075 return false; 6076 } else { 6077 mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet()); 6078 } 6079 } 6080 } 6081 } 6082 } 6083 6084 return true; 6085 } 6086 6087 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6088 synchronized (mPackages) { 6089 mResolverReplaced = true; 6090 // Set up information for custom user intent resolution activity. 6091 mResolveActivity.applicationInfo = pkg.applicationInfo; 6092 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6093 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6094 mResolveActivity.processName = null; 6095 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6096 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6097 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6098 mResolveActivity.theme = 0; 6099 mResolveActivity.exported = true; 6100 mResolveActivity.enabled = true; 6101 mResolveInfo.activityInfo = mResolveActivity; 6102 mResolveInfo.priority = 0; 6103 mResolveInfo.preferredOrder = 0; 6104 mResolveInfo.match = 0; 6105 mResolveComponentName = mCustomResolverComponentName; 6106 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6107 mResolveComponentName); 6108 } 6109 } 6110 6111 private String calculateApkRoot(final String codePathString) { 6112 final File codePath = new File(codePathString); 6113 final File codeRoot; 6114 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6115 codeRoot = Environment.getRootDirectory(); 6116 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6117 codeRoot = Environment.getOemDirectory(); 6118 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6119 codeRoot = Environment.getVendorDirectory(); 6120 } else { 6121 // Unrecognized code path; take its top real segment as the apk root: 6122 // e.g. /something/app/blah.apk => /something 6123 try { 6124 File f = codePath.getCanonicalFile(); 6125 File parent = f.getParentFile(); // non-null because codePath is a file 6126 File tmp; 6127 while ((tmp = parent.getParentFile()) != null) { 6128 f = parent; 6129 parent = tmp; 6130 } 6131 codeRoot = f; 6132 Slog.w(TAG, "Unrecognized code path " 6133 + codePath + " - using " + codeRoot); 6134 } catch (IOException e) { 6135 // Can't canonicalize the lib path -- shenanigans? 6136 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6137 return Environment.getRootDirectory().getPath(); 6138 } 6139 } 6140 return codeRoot.getPath(); 6141 } 6142 6143 // This is the initial scan-time determination of how to handle a given 6144 // package for purposes of native library location. 6145 private void setInternalAppNativeLibraryPath(PackageParser.Package pkg, 6146 PackageSetting pkgSetting) { 6147 // "bundled" here means system-installed with no overriding update 6148 final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg); 6149 final File codeFile = new File(pkg.applicationInfo.getCodePath()); 6150 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6151 6152 String nativeLibraryPath = null; 6153 if (bundledApk) { 6154 // If "/system/lib64/apkname" exists, assume that is the per-package 6155 // native library directory to use; otherwise use "/system/lib/apkname". 6156 String apkRoot = calculateApkRoot(pkg.applicationInfo.getCodePath()); 6157 File lib64 = new File(apkRoot, LIB64_DIR_NAME); 6158 File packLib64 = new File(lib64, apkName); 6159 File libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME); 6160 nativeLibraryPath = (new File(libDir, apkName)).getAbsolutePath(); 6161 } else { 6162 // Upgraded system app; derive its library path by inspecting. 6163 // TODO: pipe through abiOverride 6164 String[] abiList = Build.SUPPORTED_ABIS; 6165 NativeLibraryHelper.Handle handle = null; 6166 try { 6167 handle = NativeLibraryHelper.Handle.create(codeFile); 6168 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && 6169 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6170 abiList = Build.SUPPORTED_32_BIT_ABIS; 6171 } 6172 6173 final int abiIndex = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6174 if (abiIndex >= 0) { 6175 final File baseLibFile = new File(codeFile, LIB_DIR_NAME); 6176 final String abi = Build.SUPPORTED_ABIS[abiIndex]; 6177 final String instructionSet = VMRuntime.getInstructionSet(abi); 6178 nativeLibraryPath = new File(baseLibFile, instructionSet).getAbsolutePath(); 6179 } 6180 } catch (IOException e) { 6181 Slog.e(TAG, "Failed to detect native libraries", e); 6182 } finally { 6183 IoUtils.closeQuietly(handle); 6184 } 6185 } 6186 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath; 6187 // pkgSetting might be null during rescan following uninstall of updates 6188 // to a bundled app, so accommodate that possibility. The settings in 6189 // that case will be established later from the parsed package. 6190 if (pkgSetting != null) { 6191 pkgSetting.nativeLibraryPathString = nativeLibraryPath; 6192 } 6193 } 6194 6195 // Deduces the required ABI of an upgraded system app. 6196 private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) { 6197 final String apkRoot = calculateApkRoot(pkg.applicationInfo.getCodePath()); 6198 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6199 6200 // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>" 6201 // or similar. 6202 final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath()); 6203 final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath()); 6204 6205 // Assume that the bundled native libraries always correspond to the 6206 // most preferred 32 or 64 bit ABI. 6207 if (lib64.exists()) { 6208 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6209 pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0]; 6210 } else if (lib.exists()) { 6211 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6212 pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0]; 6213 } else { 6214 // This is the case where the app has no native code. 6215 pkg.applicationInfo.cpuAbi = null; 6216 pkgSetting.cpuAbiString = null; 6217 } 6218 } 6219 6220 private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle, 6221 final File nativeLibraryDir, String[] abiList) throws IOException { 6222 if (!nativeLibraryDir.isDirectory()) { 6223 nativeLibraryDir.delete(); 6224 6225 if (!nativeLibraryDir.mkdir()) { 6226 throw new IOException("Cannot create " + nativeLibraryDir.getPath()); 6227 } 6228 6229 try { 6230 Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6231 } catch (ErrnoException e) { 6232 throw new IOException("Cannot chmod native library directory " 6233 + nativeLibraryDir.getPath(), e); 6234 } 6235 } else if (!SELinux.restorecon(nativeLibraryDir)) { 6236 throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath()); 6237 } 6238 6239 /* 6240 * If this is an internal application or our nativeLibraryPath points to 6241 * the app-lib directory, unpack the libraries if necessary. 6242 */ 6243 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6244 if (abi >= 0) { 6245 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, 6246 nativeLibraryDir, Build.SUPPORTED_ABIS[abi]); 6247 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6248 return copyRet; 6249 } 6250 } 6251 6252 return abi; 6253 } 6254 6255 private void killApplication(String pkgName, int appId, String reason) { 6256 // Request the ActivityManager to kill the process(only for existing packages) 6257 // so that we do not end up in a confused state while the user is still using the older 6258 // version of the application while the new one gets installed. 6259 IActivityManager am = ActivityManagerNative.getDefault(); 6260 if (am != null) { 6261 try { 6262 am.killApplicationWithAppId(pkgName, appId, reason); 6263 } catch (RemoteException e) { 6264 } 6265 } 6266 } 6267 6268 void removePackageLI(PackageSetting ps, boolean chatty) { 6269 if (DEBUG_INSTALL) { 6270 if (chatty) 6271 Log.d(TAG, "Removing package " + ps.name); 6272 } 6273 6274 // writer 6275 synchronized (mPackages) { 6276 mPackages.remove(ps.name); 6277 if (ps.codePathString != null) { 6278 mAppDirs.remove(ps.codePathString); 6279 } 6280 6281 final PackageParser.Package pkg = ps.pkg; 6282 if (pkg != null) { 6283 cleanPackageDataStructuresLILPw(pkg, chatty); 6284 } 6285 } 6286 } 6287 6288 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6289 if (DEBUG_INSTALL) { 6290 if (chatty) 6291 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6292 } 6293 6294 // writer 6295 synchronized (mPackages) { 6296 mPackages.remove(pkg.applicationInfo.packageName); 6297 if (pkg.codePath != null) { 6298 mAppDirs.remove(pkg.codePath); 6299 } 6300 cleanPackageDataStructuresLILPw(pkg, chatty); 6301 } 6302 } 6303 6304 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6305 int N = pkg.providers.size(); 6306 StringBuilder r = null; 6307 int i; 6308 for (i=0; i<N; i++) { 6309 PackageParser.Provider p = pkg.providers.get(i); 6310 mProviders.removeProvider(p); 6311 if (p.info.authority == null) { 6312 6313 /* There was another ContentProvider with this authority when 6314 * this app was installed so this authority is null, 6315 * Ignore it as we don't have to unregister the provider. 6316 */ 6317 continue; 6318 } 6319 String names[] = p.info.authority.split(";"); 6320 for (int j = 0; j < names.length; j++) { 6321 if (mProvidersByAuthority.get(names[j]) == p) { 6322 mProvidersByAuthority.remove(names[j]); 6323 if (DEBUG_REMOVE) { 6324 if (chatty) 6325 Log.d(TAG, "Unregistered content provider: " + names[j] 6326 + ", className = " + p.info.name + ", isSyncable = " 6327 + p.info.isSyncable); 6328 } 6329 } 6330 } 6331 if (DEBUG_REMOVE && chatty) { 6332 if (r == null) { 6333 r = new StringBuilder(256); 6334 } else { 6335 r.append(' '); 6336 } 6337 r.append(p.info.name); 6338 } 6339 } 6340 if (r != null) { 6341 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6342 } 6343 6344 N = pkg.services.size(); 6345 r = null; 6346 for (i=0; i<N; i++) { 6347 PackageParser.Service s = pkg.services.get(i); 6348 mServices.removeService(s); 6349 if (chatty) { 6350 if (r == null) { 6351 r = new StringBuilder(256); 6352 } else { 6353 r.append(' '); 6354 } 6355 r.append(s.info.name); 6356 } 6357 } 6358 if (r != null) { 6359 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6360 } 6361 6362 N = pkg.receivers.size(); 6363 r = null; 6364 for (i=0; i<N; i++) { 6365 PackageParser.Activity a = pkg.receivers.get(i); 6366 mReceivers.removeActivity(a, "receiver"); 6367 if (DEBUG_REMOVE && chatty) { 6368 if (r == null) { 6369 r = new StringBuilder(256); 6370 } else { 6371 r.append(' '); 6372 } 6373 r.append(a.info.name); 6374 } 6375 } 6376 if (r != null) { 6377 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6378 } 6379 6380 N = pkg.activities.size(); 6381 r = null; 6382 for (i=0; i<N; i++) { 6383 PackageParser.Activity a = pkg.activities.get(i); 6384 mActivities.removeActivity(a, "activity"); 6385 if (DEBUG_REMOVE && chatty) { 6386 if (r == null) { 6387 r = new StringBuilder(256); 6388 } else { 6389 r.append(' '); 6390 } 6391 r.append(a.info.name); 6392 } 6393 } 6394 if (r != null) { 6395 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6396 } 6397 6398 N = pkg.permissions.size(); 6399 r = null; 6400 for (i=0; i<N; i++) { 6401 PackageParser.Permission p = pkg.permissions.get(i); 6402 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6403 if (bp == null) { 6404 bp = mSettings.mPermissionTrees.get(p.info.name); 6405 } 6406 if (bp != null && bp.perm == p) { 6407 bp.perm = null; 6408 if (DEBUG_REMOVE && chatty) { 6409 if (r == null) { 6410 r = new StringBuilder(256); 6411 } else { 6412 r.append(' '); 6413 } 6414 r.append(p.info.name); 6415 } 6416 } 6417 } 6418 if (r != null) { 6419 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6420 } 6421 6422 N = pkg.instrumentation.size(); 6423 r = null; 6424 for (i=0; i<N; i++) { 6425 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6426 mInstrumentation.remove(a.getComponentName()); 6427 if (DEBUG_REMOVE && chatty) { 6428 if (r == null) { 6429 r = new StringBuilder(256); 6430 } else { 6431 r.append(' '); 6432 } 6433 r.append(a.info.name); 6434 } 6435 } 6436 if (r != null) { 6437 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6438 } 6439 6440 r = null; 6441 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6442 // Only system apps can hold shared libraries. 6443 if (pkg.libraryNames != null) { 6444 for (i=0; i<pkg.libraryNames.size(); i++) { 6445 String name = pkg.libraryNames.get(i); 6446 SharedLibraryEntry cur = mSharedLibraries.get(name); 6447 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6448 mSharedLibraries.remove(name); 6449 if (DEBUG_REMOVE && chatty) { 6450 if (r == null) { 6451 r = new StringBuilder(256); 6452 } else { 6453 r.append(' '); 6454 } 6455 r.append(name); 6456 } 6457 } 6458 } 6459 } 6460 } 6461 if (r != null) { 6462 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6463 } 6464 } 6465 6466 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6467 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6468 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6469 return true; 6470 } 6471 } 6472 return false; 6473 } 6474 6475 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6476 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6477 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6478 6479 private void updatePermissionsLPw(String changingPkg, 6480 PackageParser.Package pkgInfo, int flags) { 6481 // Make sure there are no dangling permission trees. 6482 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6483 while (it.hasNext()) { 6484 final BasePermission bp = it.next(); 6485 if (bp.packageSetting == null) { 6486 // We may not yet have parsed the package, so just see if 6487 // we still know about its settings. 6488 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6489 } 6490 if (bp.packageSetting == null) { 6491 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6492 + " from package " + bp.sourcePackage); 6493 it.remove(); 6494 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6495 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6496 Slog.i(TAG, "Removing old permission tree: " + bp.name 6497 + " from package " + bp.sourcePackage); 6498 flags |= UPDATE_PERMISSIONS_ALL; 6499 it.remove(); 6500 } 6501 } 6502 } 6503 6504 // Make sure all dynamic permissions have been assigned to a package, 6505 // and make sure there are no dangling permissions. 6506 it = mSettings.mPermissions.values().iterator(); 6507 while (it.hasNext()) { 6508 final BasePermission bp = it.next(); 6509 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6510 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6511 + bp.name + " pkg=" + bp.sourcePackage 6512 + " info=" + bp.pendingInfo); 6513 if (bp.packageSetting == null && bp.pendingInfo != null) { 6514 final BasePermission tree = findPermissionTreeLP(bp.name); 6515 if (tree != null && tree.perm != null) { 6516 bp.packageSetting = tree.packageSetting; 6517 bp.perm = new PackageParser.Permission(tree.perm.owner, 6518 new PermissionInfo(bp.pendingInfo)); 6519 bp.perm.info.packageName = tree.perm.info.packageName; 6520 bp.perm.info.name = bp.name; 6521 bp.uid = tree.uid; 6522 } 6523 } 6524 } 6525 if (bp.packageSetting == null) { 6526 // We may not yet have parsed the package, so just see if 6527 // we still know about its settings. 6528 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6529 } 6530 if (bp.packageSetting == null) { 6531 Slog.w(TAG, "Removing dangling permission: " + bp.name 6532 + " from package " + bp.sourcePackage); 6533 it.remove(); 6534 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6535 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6536 Slog.i(TAG, "Removing old permission: " + bp.name 6537 + " from package " + bp.sourcePackage); 6538 flags |= UPDATE_PERMISSIONS_ALL; 6539 it.remove(); 6540 } 6541 } 6542 } 6543 6544 // Now update the permissions for all packages, in particular 6545 // replace the granted permissions of the system packages. 6546 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6547 for (PackageParser.Package pkg : mPackages.values()) { 6548 if (pkg != pkgInfo) { 6549 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6550 } 6551 } 6552 } 6553 6554 if (pkgInfo != null) { 6555 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6556 } 6557 } 6558 6559 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6560 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6561 if (ps == null) { 6562 return; 6563 } 6564 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6565 HashSet<String> origPermissions = gp.grantedPermissions; 6566 boolean changedPermission = false; 6567 6568 if (replace) { 6569 ps.permissionsFixed = false; 6570 if (gp == ps) { 6571 origPermissions = new HashSet<String>(gp.grantedPermissions); 6572 gp.grantedPermissions.clear(); 6573 gp.gids = mGlobalGids; 6574 } 6575 } 6576 6577 if (gp.gids == null) { 6578 gp.gids = mGlobalGids; 6579 } 6580 6581 final int N = pkg.requestedPermissions.size(); 6582 for (int i=0; i<N; i++) { 6583 final String name = pkg.requestedPermissions.get(i); 6584 final boolean required = pkg.requestedPermissionsRequired.get(i); 6585 final BasePermission bp = mSettings.mPermissions.get(name); 6586 if (DEBUG_INSTALL) { 6587 if (gp != ps) { 6588 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6589 } 6590 } 6591 6592 if (bp == null || bp.packageSetting == null) { 6593 Slog.w(TAG, "Unknown permission " + name 6594 + " in package " + pkg.packageName); 6595 continue; 6596 } 6597 6598 final String perm = bp.name; 6599 boolean allowed; 6600 boolean allowedSig = false; 6601 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6602 if (level == PermissionInfo.PROTECTION_NORMAL 6603 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6604 // We grant a normal or dangerous permission if any of the following 6605 // are true: 6606 // 1) The permission is required 6607 // 2) The permission is optional, but was granted in the past 6608 // 3) The permission is optional, but was requested by an 6609 // app in /system (not /data) 6610 // 6611 // Otherwise, reject the permission. 6612 allowed = (required || origPermissions.contains(perm) 6613 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6614 } else if (bp.packageSetting == null) { 6615 // This permission is invalid; skip it. 6616 allowed = false; 6617 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6618 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6619 if (allowed) { 6620 allowedSig = true; 6621 } 6622 } else { 6623 allowed = false; 6624 } 6625 if (DEBUG_INSTALL) { 6626 if (gp != ps) { 6627 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6628 } 6629 } 6630 if (allowed) { 6631 if (!isSystemApp(ps) && ps.permissionsFixed) { 6632 // If this is an existing, non-system package, then 6633 // we can't add any new permissions to it. 6634 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6635 // Except... if this is a permission that was added 6636 // to the platform (note: need to only do this when 6637 // updating the platform). 6638 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6639 } 6640 } 6641 if (allowed) { 6642 if (!gp.grantedPermissions.contains(perm)) { 6643 changedPermission = true; 6644 gp.grantedPermissions.add(perm); 6645 gp.gids = appendInts(gp.gids, bp.gids); 6646 } else if (!ps.haveGids) { 6647 gp.gids = appendInts(gp.gids, bp.gids); 6648 } 6649 } else { 6650 Slog.w(TAG, "Not granting permission " + perm 6651 + " to package " + pkg.packageName 6652 + " because it was previously installed without"); 6653 } 6654 } else { 6655 if (gp.grantedPermissions.remove(perm)) { 6656 changedPermission = true; 6657 gp.gids = removeInts(gp.gids, bp.gids); 6658 Slog.i(TAG, "Un-granting permission " + perm 6659 + " from package " + pkg.packageName 6660 + " (protectionLevel=" + bp.protectionLevel 6661 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6662 + ")"); 6663 } else { 6664 Slog.w(TAG, "Not granting permission " + perm 6665 + " to package " + pkg.packageName 6666 + " (protectionLevel=" + bp.protectionLevel 6667 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6668 + ")"); 6669 } 6670 } 6671 } 6672 6673 if ((changedPermission || replace) && !ps.permissionsFixed && 6674 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6675 // This is the first that we have heard about this package, so the 6676 // permissions we have now selected are fixed until explicitly 6677 // changed. 6678 ps.permissionsFixed = true; 6679 } 6680 ps.haveGids = true; 6681 } 6682 6683 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6684 boolean allowed = false; 6685 final int NP = PackageParser.NEW_PERMISSIONS.length; 6686 for (int ip=0; ip<NP; ip++) { 6687 final PackageParser.NewPermissionInfo npi 6688 = PackageParser.NEW_PERMISSIONS[ip]; 6689 if (npi.name.equals(perm) 6690 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6691 allowed = true; 6692 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6693 + pkg.packageName); 6694 break; 6695 } 6696 } 6697 return allowed; 6698 } 6699 6700 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6701 BasePermission bp, HashSet<String> origPermissions) { 6702 boolean allowed; 6703 allowed = (compareSignatures( 6704 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6705 == PackageManager.SIGNATURE_MATCH) 6706 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6707 == PackageManager.SIGNATURE_MATCH); 6708 if (!allowed && (bp.protectionLevel 6709 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6710 if (isSystemApp(pkg)) { 6711 // For updated system applications, a system permission 6712 // is granted only if it had been defined by the original application. 6713 if (isUpdatedSystemApp(pkg)) { 6714 final PackageSetting sysPs = mSettings 6715 .getDisabledSystemPkgLPr(pkg.packageName); 6716 final GrantedPermissions origGp = sysPs.sharedUser != null 6717 ? sysPs.sharedUser : sysPs; 6718 6719 if (origGp.grantedPermissions.contains(perm)) { 6720 // If the original was granted this permission, we take 6721 // that grant decision as read and propagate it to the 6722 // update. 6723 allowed = true; 6724 } else { 6725 // The system apk may have been updated with an older 6726 // version of the one on the data partition, but which 6727 // granted a new system permission that it didn't have 6728 // before. In this case we do want to allow the app to 6729 // now get the new permission if the ancestral apk is 6730 // privileged to get it. 6731 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6732 for (int j=0; 6733 j<sysPs.pkg.requestedPermissions.size(); j++) { 6734 if (perm.equals( 6735 sysPs.pkg.requestedPermissions.get(j))) { 6736 allowed = true; 6737 break; 6738 } 6739 } 6740 } 6741 } 6742 } else { 6743 allowed = isPrivilegedApp(pkg); 6744 } 6745 } 6746 } 6747 if (!allowed && (bp.protectionLevel 6748 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6749 // For development permissions, a development permission 6750 // is granted only if it was already granted. 6751 allowed = origPermissions.contains(perm); 6752 } 6753 return allowed; 6754 } 6755 6756 final class ActivityIntentResolver 6757 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6758 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6759 boolean defaultOnly, int userId) { 6760 if (!sUserManager.exists(userId)) return null; 6761 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6762 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6763 } 6764 6765 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6766 int userId) { 6767 if (!sUserManager.exists(userId)) return null; 6768 mFlags = flags; 6769 return super.queryIntent(intent, resolvedType, 6770 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6771 } 6772 6773 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6774 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6775 if (!sUserManager.exists(userId)) return null; 6776 if (packageActivities == null) { 6777 return null; 6778 } 6779 mFlags = flags; 6780 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6781 final int N = packageActivities.size(); 6782 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6783 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6784 6785 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6786 for (int i = 0; i < N; ++i) { 6787 intentFilters = packageActivities.get(i).intents; 6788 if (intentFilters != null && intentFilters.size() > 0) { 6789 PackageParser.ActivityIntentInfo[] array = 6790 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6791 intentFilters.toArray(array); 6792 listCut.add(array); 6793 } 6794 } 6795 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6796 } 6797 6798 public final void addActivity(PackageParser.Activity a, String type) { 6799 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6800 mActivities.put(a.getComponentName(), a); 6801 if (DEBUG_SHOW_INFO) 6802 Log.v( 6803 TAG, " " + type + " " + 6804 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6805 if (DEBUG_SHOW_INFO) 6806 Log.v(TAG, " Class=" + a.info.name); 6807 final int NI = a.intents.size(); 6808 for (int j=0; j<NI; j++) { 6809 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6810 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6811 intent.setPriority(0); 6812 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6813 + a.className + " with priority > 0, forcing to 0"); 6814 } 6815 if (DEBUG_SHOW_INFO) { 6816 Log.v(TAG, " IntentFilter:"); 6817 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6818 } 6819 if (!intent.debugCheck()) { 6820 Log.w(TAG, "==> For Activity " + a.info.name); 6821 } 6822 addFilter(intent); 6823 } 6824 } 6825 6826 public final void removeActivity(PackageParser.Activity a, String type) { 6827 mActivities.remove(a.getComponentName()); 6828 if (DEBUG_SHOW_INFO) { 6829 Log.v(TAG, " " + type + " " 6830 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6831 : a.info.name) + ":"); 6832 Log.v(TAG, " Class=" + a.info.name); 6833 } 6834 final int NI = a.intents.size(); 6835 for (int j=0; j<NI; j++) { 6836 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6837 if (DEBUG_SHOW_INFO) { 6838 Log.v(TAG, " IntentFilter:"); 6839 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6840 } 6841 removeFilter(intent); 6842 } 6843 } 6844 6845 @Override 6846 protected boolean allowFilterResult( 6847 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 6848 ActivityInfo filterAi = filter.activity.info; 6849 for (int i=dest.size()-1; i>=0; i--) { 6850 ActivityInfo destAi = dest.get(i).activityInfo; 6851 if (destAi.name == filterAi.name 6852 && destAi.packageName == filterAi.packageName) { 6853 return false; 6854 } 6855 } 6856 return true; 6857 } 6858 6859 @Override 6860 protected ActivityIntentInfo[] newArray(int size) { 6861 return new ActivityIntentInfo[size]; 6862 } 6863 6864 @Override 6865 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 6866 if (!sUserManager.exists(userId)) return true; 6867 PackageParser.Package p = filter.activity.owner; 6868 if (p != null) { 6869 PackageSetting ps = (PackageSetting)p.mExtras; 6870 if (ps != null) { 6871 // System apps are never considered stopped for purposes of 6872 // filtering, because there may be no way for the user to 6873 // actually re-launch them. 6874 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 6875 && ps.getStopped(userId); 6876 } 6877 } 6878 return false; 6879 } 6880 6881 @Override 6882 protected boolean isPackageForFilter(String packageName, 6883 PackageParser.ActivityIntentInfo info) { 6884 return packageName.equals(info.activity.owner.packageName); 6885 } 6886 6887 @Override 6888 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 6889 int match, int userId) { 6890 if (!sUserManager.exists(userId)) return null; 6891 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 6892 return null; 6893 } 6894 final PackageParser.Activity activity = info.activity; 6895 if (mSafeMode && (activity.info.applicationInfo.flags 6896 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6897 return null; 6898 } 6899 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 6900 if (ps == null) { 6901 return null; 6902 } 6903 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 6904 ps.readUserState(userId), userId); 6905 if (ai == null) { 6906 return null; 6907 } 6908 final ResolveInfo res = new ResolveInfo(); 6909 res.activityInfo = ai; 6910 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 6911 res.filter = info; 6912 } 6913 res.priority = info.getPriority(); 6914 res.preferredOrder = activity.owner.mPreferredOrder; 6915 //System.out.println("Result: " + res.activityInfo.className + 6916 // " = " + res.priority); 6917 res.match = match; 6918 res.isDefault = info.hasDefault; 6919 res.labelRes = info.labelRes; 6920 res.nonLocalizedLabel = info.nonLocalizedLabel; 6921 if (userNeedsBadging(userId)) { 6922 res.noResourceId = true; 6923 } else { 6924 res.icon = info.icon; 6925 } 6926 res.system = isSystemApp(res.activityInfo.applicationInfo); 6927 return res; 6928 } 6929 6930 @Override 6931 protected void sortResults(List<ResolveInfo> results) { 6932 Collections.sort(results, mResolvePrioritySorter); 6933 } 6934 6935 @Override 6936 protected void dumpFilter(PrintWriter out, String prefix, 6937 PackageParser.ActivityIntentInfo filter) { 6938 out.print(prefix); out.print( 6939 Integer.toHexString(System.identityHashCode(filter.activity))); 6940 out.print(' '); 6941 filter.activity.printComponentShortName(out); 6942 out.print(" filter "); 6943 out.println(Integer.toHexString(System.identityHashCode(filter))); 6944 } 6945 6946// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 6947// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 6948// final List<ResolveInfo> retList = Lists.newArrayList(); 6949// while (i.hasNext()) { 6950// final ResolveInfo resolveInfo = i.next(); 6951// if (isEnabledLP(resolveInfo.activityInfo)) { 6952// retList.add(resolveInfo); 6953// } 6954// } 6955// return retList; 6956// } 6957 6958 // Keys are String (activity class name), values are Activity. 6959 private final HashMap<ComponentName, PackageParser.Activity> mActivities 6960 = new HashMap<ComponentName, PackageParser.Activity>(); 6961 private int mFlags; 6962 } 6963 6964 private final class ServiceIntentResolver 6965 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 6966 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6967 boolean defaultOnly, int userId) { 6968 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6969 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6970 } 6971 6972 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6973 int userId) { 6974 if (!sUserManager.exists(userId)) return null; 6975 mFlags = flags; 6976 return super.queryIntent(intent, resolvedType, 6977 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6978 } 6979 6980 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6981 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 6982 if (!sUserManager.exists(userId)) return null; 6983 if (packageServices == null) { 6984 return null; 6985 } 6986 mFlags = flags; 6987 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6988 final int N = packageServices.size(); 6989 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 6990 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 6991 6992 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 6993 for (int i = 0; i < N; ++i) { 6994 intentFilters = packageServices.get(i).intents; 6995 if (intentFilters != null && intentFilters.size() > 0) { 6996 PackageParser.ServiceIntentInfo[] array = 6997 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 6998 intentFilters.toArray(array); 6999 listCut.add(array); 7000 } 7001 } 7002 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7003 } 7004 7005 public final void addService(PackageParser.Service s) { 7006 mServices.put(s.getComponentName(), s); 7007 if (DEBUG_SHOW_INFO) { 7008 Log.v(TAG, " " 7009 + (s.info.nonLocalizedLabel != null 7010 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7011 Log.v(TAG, " Class=" + s.info.name); 7012 } 7013 final int NI = s.intents.size(); 7014 int j; 7015 for (j=0; j<NI; j++) { 7016 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7017 if (DEBUG_SHOW_INFO) { 7018 Log.v(TAG, " IntentFilter:"); 7019 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7020 } 7021 if (!intent.debugCheck()) { 7022 Log.w(TAG, "==> For Service " + s.info.name); 7023 } 7024 addFilter(intent); 7025 } 7026 } 7027 7028 public final void removeService(PackageParser.Service s) { 7029 mServices.remove(s.getComponentName()); 7030 if (DEBUG_SHOW_INFO) { 7031 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7032 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7033 Log.v(TAG, " Class=" + s.info.name); 7034 } 7035 final int NI = s.intents.size(); 7036 int j; 7037 for (j=0; j<NI; j++) { 7038 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7039 if (DEBUG_SHOW_INFO) { 7040 Log.v(TAG, " IntentFilter:"); 7041 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7042 } 7043 removeFilter(intent); 7044 } 7045 } 7046 7047 @Override 7048 protected boolean allowFilterResult( 7049 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7050 ServiceInfo filterSi = filter.service.info; 7051 for (int i=dest.size()-1; i>=0; i--) { 7052 ServiceInfo destAi = dest.get(i).serviceInfo; 7053 if (destAi.name == filterSi.name 7054 && destAi.packageName == filterSi.packageName) { 7055 return false; 7056 } 7057 } 7058 return true; 7059 } 7060 7061 @Override 7062 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7063 return new PackageParser.ServiceIntentInfo[size]; 7064 } 7065 7066 @Override 7067 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7068 if (!sUserManager.exists(userId)) return true; 7069 PackageParser.Package p = filter.service.owner; 7070 if (p != null) { 7071 PackageSetting ps = (PackageSetting)p.mExtras; 7072 if (ps != null) { 7073 // System apps are never considered stopped for purposes of 7074 // filtering, because there may be no way for the user to 7075 // actually re-launch them. 7076 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7077 && ps.getStopped(userId); 7078 } 7079 } 7080 return false; 7081 } 7082 7083 @Override 7084 protected boolean isPackageForFilter(String packageName, 7085 PackageParser.ServiceIntentInfo info) { 7086 return packageName.equals(info.service.owner.packageName); 7087 } 7088 7089 @Override 7090 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7091 int match, int userId) { 7092 if (!sUserManager.exists(userId)) return null; 7093 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7094 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7095 return null; 7096 } 7097 final PackageParser.Service service = info.service; 7098 if (mSafeMode && (service.info.applicationInfo.flags 7099 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7100 return null; 7101 } 7102 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7103 if (ps == null) { 7104 return null; 7105 } 7106 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7107 ps.readUserState(userId), userId); 7108 if (si == null) { 7109 return null; 7110 } 7111 final ResolveInfo res = new ResolveInfo(); 7112 res.serviceInfo = si; 7113 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7114 res.filter = filter; 7115 } 7116 res.priority = info.getPriority(); 7117 res.preferredOrder = service.owner.mPreferredOrder; 7118 //System.out.println("Result: " + res.activityInfo.className + 7119 // " = " + res.priority); 7120 res.match = match; 7121 res.isDefault = info.hasDefault; 7122 res.labelRes = info.labelRes; 7123 res.nonLocalizedLabel = info.nonLocalizedLabel; 7124 res.icon = info.icon; 7125 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7126 return res; 7127 } 7128 7129 @Override 7130 protected void sortResults(List<ResolveInfo> results) { 7131 Collections.sort(results, mResolvePrioritySorter); 7132 } 7133 7134 @Override 7135 protected void dumpFilter(PrintWriter out, String prefix, 7136 PackageParser.ServiceIntentInfo filter) { 7137 out.print(prefix); out.print( 7138 Integer.toHexString(System.identityHashCode(filter.service))); 7139 out.print(' '); 7140 filter.service.printComponentShortName(out); 7141 out.print(" filter "); 7142 out.println(Integer.toHexString(System.identityHashCode(filter))); 7143 } 7144 7145// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7146// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7147// final List<ResolveInfo> retList = Lists.newArrayList(); 7148// while (i.hasNext()) { 7149// final ResolveInfo resolveInfo = (ResolveInfo) i; 7150// if (isEnabledLP(resolveInfo.serviceInfo)) { 7151// retList.add(resolveInfo); 7152// } 7153// } 7154// return retList; 7155// } 7156 7157 // Keys are String (activity class name), values are Activity. 7158 private final HashMap<ComponentName, PackageParser.Service> mServices 7159 = new HashMap<ComponentName, PackageParser.Service>(); 7160 private int mFlags; 7161 }; 7162 7163 private final class ProviderIntentResolver 7164 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7165 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7166 boolean defaultOnly, int userId) { 7167 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7168 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7169 } 7170 7171 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7172 int userId) { 7173 if (!sUserManager.exists(userId)) 7174 return null; 7175 mFlags = flags; 7176 return super.queryIntent(intent, resolvedType, 7177 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7178 } 7179 7180 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7181 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7182 if (!sUserManager.exists(userId)) 7183 return null; 7184 if (packageProviders == null) { 7185 return null; 7186 } 7187 mFlags = flags; 7188 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7189 final int N = packageProviders.size(); 7190 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7191 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7192 7193 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7194 for (int i = 0; i < N; ++i) { 7195 intentFilters = packageProviders.get(i).intents; 7196 if (intentFilters != null && intentFilters.size() > 0) { 7197 PackageParser.ProviderIntentInfo[] array = 7198 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7199 intentFilters.toArray(array); 7200 listCut.add(array); 7201 } 7202 } 7203 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7204 } 7205 7206 public final void addProvider(PackageParser.Provider p) { 7207 if (mProviders.containsKey(p.getComponentName())) { 7208 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7209 return; 7210 } 7211 7212 mProviders.put(p.getComponentName(), p); 7213 if (DEBUG_SHOW_INFO) { 7214 Log.v(TAG, " " 7215 + (p.info.nonLocalizedLabel != null 7216 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7217 Log.v(TAG, " Class=" + p.info.name); 7218 } 7219 final int NI = p.intents.size(); 7220 int j; 7221 for (j = 0; j < NI; j++) { 7222 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7223 if (DEBUG_SHOW_INFO) { 7224 Log.v(TAG, " IntentFilter:"); 7225 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7226 } 7227 if (!intent.debugCheck()) { 7228 Log.w(TAG, "==> For Provider " + p.info.name); 7229 } 7230 addFilter(intent); 7231 } 7232 } 7233 7234 public final void removeProvider(PackageParser.Provider p) { 7235 mProviders.remove(p.getComponentName()); 7236 if (DEBUG_SHOW_INFO) { 7237 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7238 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7239 Log.v(TAG, " Class=" + p.info.name); 7240 } 7241 final int NI = p.intents.size(); 7242 int j; 7243 for (j = 0; j < NI; j++) { 7244 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7245 if (DEBUG_SHOW_INFO) { 7246 Log.v(TAG, " IntentFilter:"); 7247 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7248 } 7249 removeFilter(intent); 7250 } 7251 } 7252 7253 @Override 7254 protected boolean allowFilterResult( 7255 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7256 ProviderInfo filterPi = filter.provider.info; 7257 for (int i = dest.size() - 1; i >= 0; i--) { 7258 ProviderInfo destPi = dest.get(i).providerInfo; 7259 if (destPi.name == filterPi.name 7260 && destPi.packageName == filterPi.packageName) { 7261 return false; 7262 } 7263 } 7264 return true; 7265 } 7266 7267 @Override 7268 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7269 return new PackageParser.ProviderIntentInfo[size]; 7270 } 7271 7272 @Override 7273 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7274 if (!sUserManager.exists(userId)) 7275 return true; 7276 PackageParser.Package p = filter.provider.owner; 7277 if (p != null) { 7278 PackageSetting ps = (PackageSetting) p.mExtras; 7279 if (ps != null) { 7280 // System apps are never considered stopped for purposes of 7281 // filtering, because there may be no way for the user to 7282 // actually re-launch them. 7283 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7284 && ps.getStopped(userId); 7285 } 7286 } 7287 return false; 7288 } 7289 7290 @Override 7291 protected boolean isPackageForFilter(String packageName, 7292 PackageParser.ProviderIntentInfo info) { 7293 return packageName.equals(info.provider.owner.packageName); 7294 } 7295 7296 @Override 7297 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7298 int match, int userId) { 7299 if (!sUserManager.exists(userId)) 7300 return null; 7301 final PackageParser.ProviderIntentInfo info = filter; 7302 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7303 return null; 7304 } 7305 final PackageParser.Provider provider = info.provider; 7306 if (mSafeMode && (provider.info.applicationInfo.flags 7307 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7308 return null; 7309 } 7310 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7311 if (ps == null) { 7312 return null; 7313 } 7314 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7315 ps.readUserState(userId), userId); 7316 if (pi == null) { 7317 return null; 7318 } 7319 final ResolveInfo res = new ResolveInfo(); 7320 res.providerInfo = pi; 7321 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7322 res.filter = filter; 7323 } 7324 res.priority = info.getPriority(); 7325 res.preferredOrder = provider.owner.mPreferredOrder; 7326 res.match = match; 7327 res.isDefault = info.hasDefault; 7328 res.labelRes = info.labelRes; 7329 res.nonLocalizedLabel = info.nonLocalizedLabel; 7330 res.icon = info.icon; 7331 res.system = isSystemApp(res.providerInfo.applicationInfo); 7332 return res; 7333 } 7334 7335 @Override 7336 protected void sortResults(List<ResolveInfo> results) { 7337 Collections.sort(results, mResolvePrioritySorter); 7338 } 7339 7340 @Override 7341 protected void dumpFilter(PrintWriter out, String prefix, 7342 PackageParser.ProviderIntentInfo filter) { 7343 out.print(prefix); 7344 out.print( 7345 Integer.toHexString(System.identityHashCode(filter.provider))); 7346 out.print(' '); 7347 filter.provider.printComponentShortName(out); 7348 out.print(" filter "); 7349 out.println(Integer.toHexString(System.identityHashCode(filter))); 7350 } 7351 7352 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7353 = new HashMap<ComponentName, PackageParser.Provider>(); 7354 private int mFlags; 7355 }; 7356 7357 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7358 new Comparator<ResolveInfo>() { 7359 public int compare(ResolveInfo r1, ResolveInfo r2) { 7360 int v1 = r1.priority; 7361 int v2 = r2.priority; 7362 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7363 if (v1 != v2) { 7364 return (v1 > v2) ? -1 : 1; 7365 } 7366 v1 = r1.preferredOrder; 7367 v2 = r2.preferredOrder; 7368 if (v1 != v2) { 7369 return (v1 > v2) ? -1 : 1; 7370 } 7371 if (r1.isDefault != r2.isDefault) { 7372 return r1.isDefault ? -1 : 1; 7373 } 7374 v1 = r1.match; 7375 v2 = r2.match; 7376 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7377 if (v1 != v2) { 7378 return (v1 > v2) ? -1 : 1; 7379 } 7380 if (r1.system != r2.system) { 7381 return r1.system ? -1 : 1; 7382 } 7383 return 0; 7384 } 7385 }; 7386 7387 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7388 new Comparator<ProviderInfo>() { 7389 public int compare(ProviderInfo p1, ProviderInfo p2) { 7390 final int v1 = p1.initOrder; 7391 final int v2 = p2.initOrder; 7392 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7393 } 7394 }; 7395 7396 static final void sendPackageBroadcast(String action, String pkg, 7397 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7398 int[] userIds) { 7399 IActivityManager am = ActivityManagerNative.getDefault(); 7400 if (am != null) { 7401 try { 7402 if (userIds == null) { 7403 userIds = am.getRunningUserIds(); 7404 } 7405 for (int id : userIds) { 7406 final Intent intent = new Intent(action, 7407 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7408 if (extras != null) { 7409 intent.putExtras(extras); 7410 } 7411 if (targetPkg != null) { 7412 intent.setPackage(targetPkg); 7413 } 7414 // Modify the UID when posting to other users 7415 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7416 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7417 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7418 intent.putExtra(Intent.EXTRA_UID, uid); 7419 } 7420 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7421 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7422 if (DEBUG_BROADCASTS) { 7423 RuntimeException here = new RuntimeException("here"); 7424 here.fillInStackTrace(); 7425 Slog.d(TAG, "Sending to user " + id + ": " 7426 + intent.toShortString(false, true, false, false) 7427 + " " + intent.getExtras(), here); 7428 } 7429 am.broadcastIntent(null, intent, null, finishedReceiver, 7430 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7431 finishedReceiver != null, false, id); 7432 } 7433 } catch (RemoteException ex) { 7434 } 7435 } 7436 } 7437 7438 /** 7439 * Check if the external storage media is available. This is true if there 7440 * is a mounted external storage medium or if the external storage is 7441 * emulated. 7442 */ 7443 private boolean isExternalMediaAvailable() { 7444 return mMediaMounted || Environment.isExternalStorageEmulated(); 7445 } 7446 7447 @Override 7448 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7449 // writer 7450 synchronized (mPackages) { 7451 if (!isExternalMediaAvailable()) { 7452 // If the external storage is no longer mounted at this point, 7453 // the caller may not have been able to delete all of this 7454 // packages files and can not delete any more. Bail. 7455 return null; 7456 } 7457 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7458 if (lastPackage != null) { 7459 pkgs.remove(lastPackage); 7460 } 7461 if (pkgs.size() > 0) { 7462 return pkgs.get(0); 7463 } 7464 } 7465 return null; 7466 } 7467 7468 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7469 if (false) { 7470 RuntimeException here = new RuntimeException("here"); 7471 here.fillInStackTrace(); 7472 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7473 + " andCode=" + andCode, here); 7474 } 7475 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7476 userId, andCode ? 1 : 0, packageName)); 7477 } 7478 7479 void startCleaningPackages() { 7480 // reader 7481 synchronized (mPackages) { 7482 if (!isExternalMediaAvailable()) { 7483 return; 7484 } 7485 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7486 return; 7487 } 7488 } 7489 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7490 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7491 IActivityManager am = ActivityManagerNative.getDefault(); 7492 if (am != null) { 7493 try { 7494 am.startService(null, intent, null, UserHandle.USER_OWNER); 7495 } catch (RemoteException e) { 7496 } 7497 } 7498 } 7499 7500 private final class AppDirObserver extends FileObserver { 7501 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 7502 super(path, mask); 7503 mRootDir = path; 7504 mIsRom = isrom; 7505 mIsPrivileged = isPrivileged; 7506 } 7507 7508 public void onEvent(int event, String path) { 7509 String removedPackage = null; 7510 int removedAppId = -1; 7511 int[] removedUsers = null; 7512 String addedPackage = null; 7513 int addedAppId = -1; 7514 int[] addedUsers = null; 7515 7516 // TODO post a message to the handler to obtain serial ordering 7517 synchronized (mInstallLock) { 7518 String fullPathStr = null; 7519 File fullPath = null; 7520 if (path != null) { 7521 fullPath = new File(mRootDir, path); 7522 fullPathStr = fullPath.getPath(); 7523 } 7524 7525 if (DEBUG_APP_DIR_OBSERVER) 7526 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 7527 7528 if (!isApkFile(fullPath)) { 7529 if (DEBUG_APP_DIR_OBSERVER) 7530 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 7531 return; 7532 } 7533 7534 // Ignore packages that are being installed or 7535 // have just been installed. 7536 if (ignoreCodePath(fullPathStr)) { 7537 return; 7538 } 7539 PackageParser.Package p = null; 7540 PackageSetting ps = null; 7541 // reader 7542 synchronized (mPackages) { 7543 p = mAppDirs.get(fullPathStr); 7544 if (p != null) { 7545 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 7546 if (ps != null) { 7547 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7548 } else { 7549 removedUsers = sUserManager.getUserIds(); 7550 } 7551 } 7552 addedUsers = sUserManager.getUserIds(); 7553 } 7554 if ((event&REMOVE_EVENTS) != 0) { 7555 if (ps != null) { 7556 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 7557 removePackageLI(ps, true); 7558 removedPackage = ps.name; 7559 removedAppId = ps.appId; 7560 } 7561 } 7562 7563 if ((event&ADD_EVENTS) != 0) { 7564 if (p == null) { 7565 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 7566 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 7567 if (mIsRom) { 7568 flags |= PackageParser.PARSE_IS_SYSTEM 7569 | PackageParser.PARSE_IS_SYSTEM_DIR; 7570 if (mIsPrivileged) { 7571 flags |= PackageParser.PARSE_IS_PRIVILEGED; 7572 } 7573 } 7574 p = scanPackageLI(fullPath, flags, 7575 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 7576 System.currentTimeMillis(), UserHandle.ALL, null); 7577 if (p != null) { 7578 /* 7579 * TODO this seems dangerous as the package may have 7580 * changed since we last acquired the mPackages 7581 * lock. 7582 */ 7583 // writer 7584 synchronized (mPackages) { 7585 updatePermissionsLPw(p.packageName, p, 7586 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 7587 } 7588 addedPackage = p.applicationInfo.packageName; 7589 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 7590 } 7591 } 7592 } 7593 7594 // reader 7595 synchronized (mPackages) { 7596 mSettings.writeLPr(); 7597 } 7598 } 7599 7600 if (removedPackage != null) { 7601 Bundle extras = new Bundle(1); 7602 extras.putInt(Intent.EXTRA_UID, removedAppId); 7603 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 7604 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7605 extras, null, null, removedUsers); 7606 } 7607 if (addedPackage != null) { 7608 Bundle extras = new Bundle(1); 7609 extras.putInt(Intent.EXTRA_UID, addedAppId); 7610 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 7611 extras, null, null, addedUsers); 7612 } 7613 } 7614 7615 private final String mRootDir; 7616 private final boolean mIsRom; 7617 private final boolean mIsPrivileged; 7618 } 7619 7620 /* 7621 * The old-style observer methods all just trampoline to the newer signature with 7622 * expanded install observer API. The older API continues to work but does not 7623 * supply the additional details of the Observer2 API. 7624 */ 7625 7626 /* Called when a downloaded package installation has been confirmed by the user */ 7627 public void installPackage( 7628 final Uri packageURI, final IPackageInstallObserver observer, final int flags) { 7629 installPackageEtc(packageURI, observer, null, flags, null); 7630 } 7631 7632 /* Called when a downloaded package installation has been confirmed by the user */ 7633 @Override 7634 public void installPackage( 7635 final Uri packageURI, final IPackageInstallObserver observer, final int flags, 7636 final String installerPackageName) { 7637 installPackageWithVerificationEtc(packageURI, observer, null, flags, 7638 installerPackageName, null, null, null); 7639 } 7640 7641 @Override 7642 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer, 7643 int flags, String installerPackageName, Uri verificationURI, 7644 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7645 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7646 VerificationParams.NO_UID, manifestDigest); 7647 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7648 installerPackageName, verificationParams, encryptionParams); 7649 } 7650 7651 @Override 7652 public void installPackageWithVerificationAndEncryption(Uri packageURI, 7653 IPackageInstallObserver observer, int flags, String installerPackageName, 7654 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7655 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7656 installerPackageName, verificationParams, encryptionParams); 7657 } 7658 7659 /* 7660 * And here are the "live" versions that take both observer arguments 7661 */ 7662 public void installPackageEtc( 7663 final Uri packageURI, final IPackageInstallObserver observer, 7664 IPackageInstallObserver2 observer2, final int flags) { 7665 installPackageEtc(packageURI, observer, observer2, flags, null); 7666 } 7667 7668 public void installPackageEtc( 7669 final Uri packageURI, final IPackageInstallObserver observer, 7670 final IPackageInstallObserver2 observer2, final int flags, 7671 final String installerPackageName) { 7672 installPackageWithVerificationEtc(packageURI, observer, observer2, flags, 7673 installerPackageName, null, null, null); 7674 } 7675 7676 @Override 7677 public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer, 7678 IPackageInstallObserver2 observer2, 7679 int flags, String installerPackageName, Uri verificationURI, 7680 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7681 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7682 VerificationParams.NO_UID, manifestDigest); 7683 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags, 7684 installerPackageName, verificationParams, encryptionParams); 7685 } 7686 7687 /* 7688 * All of the installPackage...*() methods redirect to this one for the master implementation 7689 */ 7690 public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI, 7691 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7692 int flags, String installerPackageName, 7693 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7694 if (observer == null && observer2 == null) { 7695 throw new IllegalArgumentException("No install observer supplied"); 7696 } 7697 installPackageWithVerificationEncryptionAndAbiOverrideEtc(packageURI, observer, observer2, 7698 flags, installerPackageName, verificationParams, encryptionParams, null); 7699 } 7700 7701 @Override 7702 public void installPackageWithVerificationEncryptionAndAbiOverrideEtc(Uri packageURI, 7703 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7704 int flags, String installerPackageName, 7705 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams, 7706 String packageAbiOverride) { 7707 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7708 null); 7709 7710 final int uid = Binder.getCallingUid(); 7711 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7712 try { 7713 if (observer != null) { 7714 observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7715 } 7716 if (observer2 != null) { 7717 observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7718 } 7719 } catch (RemoteException re) { 7720 } 7721 return; 7722 } 7723 7724 UserHandle user; 7725 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7726 user = UserHandle.ALL; 7727 } else { 7728 user = new UserHandle(UserHandle.getUserId(uid)); 7729 } 7730 7731 final int filteredFlags; 7732 7733 if (uid == Process.SHELL_UID || uid == 0) { 7734 if (DEBUG_INSTALL) { 7735 Slog.v(TAG, "Install from ADB"); 7736 } 7737 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7738 } else { 7739 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7740 } 7741 7742 verificationParams.setInstallerUid(uid); 7743 7744 if (!"file".equals(packageURI.getScheme())) { 7745 throw new UnsupportedOperationException("Only file:// URIs are supported"); 7746 } 7747 final File fromFile = new File(packageURI.getPath()); 7748 7749 if (encryptionParams != null) { 7750 throw new UnsupportedOperationException("ContainerEncryptionParams not supported"); 7751 } 7752 7753 final Message msg = mHandler.obtainMessage(INIT_COPY); 7754 msg.obj = new InstallParams(fromFile, observer, observer2, filteredFlags, 7755 installerPackageName, verificationParams, user, packageAbiOverride); 7756 mHandler.sendMessage(msg); 7757 } 7758 7759 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7760 Bundle extras = new Bundle(1); 7761 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7762 7763 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7764 packageName, extras, null, null, new int[] {userId}); 7765 try { 7766 IActivityManager am = ActivityManagerNative.getDefault(); 7767 final boolean isSystem = 7768 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7769 if (isSystem && am.isUserRunning(userId, false)) { 7770 // The just-installed/enabled app is bundled on the system, so presumed 7771 // to be able to run automatically without needing an explicit launch. 7772 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7773 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7774 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7775 .setPackage(packageName); 7776 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7777 android.app.AppOpsManager.OP_NONE, false, false, userId); 7778 } 7779 } catch (RemoteException e) { 7780 // shouldn't happen 7781 Slog.w(TAG, "Unable to bootstrap installed package", e); 7782 } 7783 } 7784 7785 @Override 7786 public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked, 7787 int userId) { 7788 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7789 PackageSetting pkgSetting; 7790 final int uid = Binder.getCallingUid(); 7791 if (UserHandle.getUserId(uid) != userId) { 7792 mContext.enforceCallingOrSelfPermission( 7793 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7794 "setApplicationBlockedSetting for user " + userId); 7795 } 7796 7797 if (blocked && isPackageDeviceAdmin(packageName, userId)) { 7798 Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin"); 7799 return false; 7800 } 7801 7802 long callingId = Binder.clearCallingIdentity(); 7803 try { 7804 boolean sendAdded = false; 7805 boolean sendRemoved = false; 7806 // writer 7807 synchronized (mPackages) { 7808 pkgSetting = mSettings.mPackages.get(packageName); 7809 if (pkgSetting == null) { 7810 return false; 7811 } 7812 if (pkgSetting.getBlocked(userId) != blocked) { 7813 pkgSetting.setBlocked(blocked, userId); 7814 mSettings.writePackageRestrictionsLPr(userId); 7815 if (blocked) { 7816 sendRemoved = true; 7817 } else { 7818 sendAdded = true; 7819 } 7820 } 7821 } 7822 if (sendAdded) { 7823 sendPackageAddedForUser(packageName, pkgSetting, userId); 7824 return true; 7825 } 7826 if (sendRemoved) { 7827 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7828 "blocking pkg"); 7829 sendPackageBlockedForUser(packageName, pkgSetting, userId); 7830 } 7831 } finally { 7832 Binder.restoreCallingIdentity(callingId); 7833 } 7834 return false; 7835 } 7836 7837 private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting, 7838 int userId) { 7839 final PackageRemovedInfo info = new PackageRemovedInfo(); 7840 info.removedPackage = packageName; 7841 info.removedUsers = new int[] {userId}; 7842 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7843 info.sendBroadcast(false, false, false); 7844 } 7845 7846 /** 7847 * Returns true if application is not found or there was an error. Otherwise it returns 7848 * the blocked state of the package for the given user. 7849 */ 7850 @Override 7851 public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) { 7852 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7853 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7854 "getApplicationBlocked for user " + userId); 7855 PackageSetting pkgSetting; 7856 long callingId = Binder.clearCallingIdentity(); 7857 try { 7858 // writer 7859 synchronized (mPackages) { 7860 pkgSetting = mSettings.mPackages.get(packageName); 7861 if (pkgSetting == null) { 7862 return true; 7863 } 7864 return pkgSetting.getBlocked(userId); 7865 } 7866 } finally { 7867 Binder.restoreCallingIdentity(callingId); 7868 } 7869 } 7870 7871 void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer2, 7872 PackageInstallerParams params, String installerPackageName, int installerUid, 7873 UserHandle user) { 7874 Slog.e(TAG, "TODO: install stage!"); 7875 try { 7876 observer2.packageInstalled(packageName, null, 7877 PackageManager.INSTALL_FAILED_INTERNAL_ERROR); 7878 } catch (RemoteException ignored) { 7879 } 7880 } 7881 7882 /** 7883 * @hide 7884 */ 7885 @Override 7886 public int installExistingPackageAsUser(String packageName, int userId) { 7887 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7888 null); 7889 PackageSetting pkgSetting; 7890 final int uid = Binder.getCallingUid(); 7891 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7892 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7893 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7894 } 7895 7896 long callingId = Binder.clearCallingIdentity(); 7897 try { 7898 boolean sendAdded = false; 7899 Bundle extras = new Bundle(1); 7900 7901 // writer 7902 synchronized (mPackages) { 7903 pkgSetting = mSettings.mPackages.get(packageName); 7904 if (pkgSetting == null) { 7905 return PackageManager.INSTALL_FAILED_INVALID_URI; 7906 } 7907 if (!pkgSetting.getInstalled(userId)) { 7908 pkgSetting.setInstalled(true, userId); 7909 pkgSetting.setBlocked(false, userId); 7910 mSettings.writePackageRestrictionsLPr(userId); 7911 sendAdded = true; 7912 } 7913 } 7914 7915 if (sendAdded) { 7916 sendPackageAddedForUser(packageName, pkgSetting, userId); 7917 } 7918 } finally { 7919 Binder.restoreCallingIdentity(callingId); 7920 } 7921 7922 return PackageManager.INSTALL_SUCCEEDED; 7923 } 7924 7925 boolean isUserRestricted(int userId, String restrictionKey) { 7926 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7927 if (restrictions.getBoolean(restrictionKey, false)) { 7928 Log.w(TAG, "User is restricted: " + restrictionKey); 7929 return true; 7930 } 7931 return false; 7932 } 7933 7934 @Override 7935 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7936 mContext.enforceCallingOrSelfPermission( 7937 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7938 "Only package verification agents can verify applications"); 7939 7940 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7941 final PackageVerificationResponse response = new PackageVerificationResponse( 7942 verificationCode, Binder.getCallingUid()); 7943 msg.arg1 = id; 7944 msg.obj = response; 7945 mHandler.sendMessage(msg); 7946 } 7947 7948 @Override 7949 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7950 long millisecondsToDelay) { 7951 mContext.enforceCallingOrSelfPermission( 7952 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7953 "Only package verification agents can extend verification timeouts"); 7954 7955 final PackageVerificationState state = mPendingVerification.get(id); 7956 final PackageVerificationResponse response = new PackageVerificationResponse( 7957 verificationCodeAtTimeout, Binder.getCallingUid()); 7958 7959 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7960 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7961 } 7962 if (millisecondsToDelay < 0) { 7963 millisecondsToDelay = 0; 7964 } 7965 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7966 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7967 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7968 } 7969 7970 if ((state != null) && !state.timeoutExtended()) { 7971 state.extendTimeout(); 7972 7973 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7974 msg.arg1 = id; 7975 msg.obj = response; 7976 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7977 } 7978 } 7979 7980 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7981 int verificationCode, UserHandle user) { 7982 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7983 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7984 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7985 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7986 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 7987 7988 mContext.sendBroadcastAsUser(intent, user, 7989 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 7990 } 7991 7992 private ComponentName matchComponentForVerifier(String packageName, 7993 List<ResolveInfo> receivers) { 7994 ActivityInfo targetReceiver = null; 7995 7996 final int NR = receivers.size(); 7997 for (int i = 0; i < NR; i++) { 7998 final ResolveInfo info = receivers.get(i); 7999 if (info.activityInfo == null) { 8000 continue; 8001 } 8002 8003 if (packageName.equals(info.activityInfo.packageName)) { 8004 targetReceiver = info.activityInfo; 8005 break; 8006 } 8007 } 8008 8009 if (targetReceiver == null) { 8010 return null; 8011 } 8012 8013 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8014 } 8015 8016 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8017 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8018 if (pkgInfo.verifiers.length == 0) { 8019 return null; 8020 } 8021 8022 final int N = pkgInfo.verifiers.length; 8023 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8024 for (int i = 0; i < N; i++) { 8025 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8026 8027 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8028 receivers); 8029 if (comp == null) { 8030 continue; 8031 } 8032 8033 final int verifierUid = getUidForVerifier(verifierInfo); 8034 if (verifierUid == -1) { 8035 continue; 8036 } 8037 8038 if (DEBUG_VERIFY) { 8039 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8040 + " with the correct signature"); 8041 } 8042 sufficientVerifiers.add(comp); 8043 verificationState.addSufficientVerifier(verifierUid); 8044 } 8045 8046 return sufficientVerifiers; 8047 } 8048 8049 private int getUidForVerifier(VerifierInfo verifierInfo) { 8050 synchronized (mPackages) { 8051 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8052 if (pkg == null) { 8053 return -1; 8054 } else if (pkg.mSignatures.length != 1) { 8055 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8056 + " has more than one signature; ignoring"); 8057 return -1; 8058 } 8059 8060 /* 8061 * If the public key of the package's signature does not match 8062 * our expected public key, then this is a different package and 8063 * we should skip. 8064 */ 8065 8066 final byte[] expectedPublicKey; 8067 try { 8068 final Signature verifierSig = pkg.mSignatures[0]; 8069 final PublicKey publicKey = verifierSig.getPublicKey(); 8070 expectedPublicKey = publicKey.getEncoded(); 8071 } catch (CertificateException e) { 8072 return -1; 8073 } 8074 8075 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8076 8077 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8078 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8079 + " does not have the expected public key; ignoring"); 8080 return -1; 8081 } 8082 8083 return pkg.applicationInfo.uid; 8084 } 8085 } 8086 8087 @Override 8088 public void finishPackageInstall(int token) { 8089 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8090 8091 if (DEBUG_INSTALL) { 8092 Slog.v(TAG, "BM finishing package install for " + token); 8093 } 8094 8095 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8096 mHandler.sendMessage(msg); 8097 } 8098 8099 /** 8100 * Get the verification agent timeout. 8101 * 8102 * @return verification timeout in milliseconds 8103 */ 8104 private long getVerificationTimeout() { 8105 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8106 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8107 DEFAULT_VERIFICATION_TIMEOUT); 8108 } 8109 8110 /** 8111 * Get the default verification agent response code. 8112 * 8113 * @return default verification response code 8114 */ 8115 private int getDefaultVerificationResponse() { 8116 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8117 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8118 DEFAULT_VERIFICATION_RESPONSE); 8119 } 8120 8121 /** 8122 * Check whether or not package verification has been enabled. 8123 * 8124 * @return true if verification should be performed 8125 */ 8126 private boolean isVerificationEnabled(int userId, int flags) { 8127 if (!DEFAULT_VERIFY_ENABLE) { 8128 return false; 8129 } 8130 8131 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8132 8133 // Check if installing from ADB 8134 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8135 // Do not run verification in a test harness environment 8136 if (ActivityManager.isRunningInTestHarness()) { 8137 return false; 8138 } 8139 if (ensureVerifyAppsEnabled) { 8140 return true; 8141 } 8142 // Check if the developer does not want package verification for ADB installs 8143 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8144 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8145 return false; 8146 } 8147 } 8148 8149 if (ensureVerifyAppsEnabled) { 8150 return true; 8151 } 8152 8153 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8154 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8155 } 8156 8157 /** 8158 * Get the "allow unknown sources" setting. 8159 * 8160 * @return the current "allow unknown sources" setting 8161 */ 8162 private int getUnknownSourcesSettings() { 8163 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8164 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8165 -1); 8166 } 8167 8168 @Override 8169 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8170 final int uid = Binder.getCallingUid(); 8171 // writer 8172 synchronized (mPackages) { 8173 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8174 if (targetPackageSetting == null) { 8175 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8176 } 8177 8178 PackageSetting installerPackageSetting; 8179 if (installerPackageName != null) { 8180 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8181 if (installerPackageSetting == null) { 8182 throw new IllegalArgumentException("Unknown installer package: " 8183 + installerPackageName); 8184 } 8185 } else { 8186 installerPackageSetting = null; 8187 } 8188 8189 Signature[] callerSignature; 8190 Object obj = mSettings.getUserIdLPr(uid); 8191 if (obj != null) { 8192 if (obj instanceof SharedUserSetting) { 8193 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8194 } else if (obj instanceof PackageSetting) { 8195 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8196 } else { 8197 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8198 } 8199 } else { 8200 throw new SecurityException("Unknown calling uid " + uid); 8201 } 8202 8203 // Verify: can't set installerPackageName to a package that is 8204 // not signed with the same cert as the caller. 8205 if (installerPackageSetting != null) { 8206 if (compareSignatures(callerSignature, 8207 installerPackageSetting.signatures.mSignatures) 8208 != PackageManager.SIGNATURE_MATCH) { 8209 throw new SecurityException( 8210 "Caller does not have same cert as new installer package " 8211 + installerPackageName); 8212 } 8213 } 8214 8215 // Verify: if target already has an installer package, it must 8216 // be signed with the same cert as the caller. 8217 if (targetPackageSetting.installerPackageName != null) { 8218 PackageSetting setting = mSettings.mPackages.get( 8219 targetPackageSetting.installerPackageName); 8220 // If the currently set package isn't valid, then it's always 8221 // okay to change it. 8222 if (setting != null) { 8223 if (compareSignatures(callerSignature, 8224 setting.signatures.mSignatures) 8225 != PackageManager.SIGNATURE_MATCH) { 8226 throw new SecurityException( 8227 "Caller does not have same cert as old installer package " 8228 + targetPackageSetting.installerPackageName); 8229 } 8230 } 8231 } 8232 8233 // Okay! 8234 targetPackageSetting.installerPackageName = installerPackageName; 8235 scheduleWriteSettingsLocked(); 8236 } 8237 } 8238 8239 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8240 // Queue up an async operation since the package installation may take a little while. 8241 mHandler.post(new Runnable() { 8242 public void run() { 8243 mHandler.removeCallbacks(this); 8244 // Result object to be returned 8245 PackageInstalledInfo res = new PackageInstalledInfo(); 8246 res.returnCode = currentStatus; 8247 res.uid = -1; 8248 res.pkg = null; 8249 res.removedInfo = new PackageRemovedInfo(); 8250 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8251 args.doPreInstall(res.returnCode); 8252 synchronized (mInstallLock) { 8253 installPackageLI(args, true, res); 8254 } 8255 args.doPostInstall(res.returnCode, res.uid); 8256 } 8257 8258 // A restore should be performed at this point if (a) the install 8259 // succeeded, (b) the operation is not an update, and (c) the new 8260 // package has a backupAgent defined. 8261 final boolean update = res.removedInfo.removedPackage != null; 8262 boolean doRestore = (!update 8263 && res.pkg != null 8264 && res.pkg.applicationInfo.backupAgentName != null); 8265 8266 // Set up the post-install work request bookkeeping. This will be used 8267 // and cleaned up by the post-install event handling regardless of whether 8268 // there's a restore pass performed. Token values are >= 1. 8269 int token; 8270 if (mNextInstallToken < 0) mNextInstallToken = 1; 8271 token = mNextInstallToken++; 8272 8273 PostInstallData data = new PostInstallData(args, res); 8274 mRunningInstalls.put(token, data); 8275 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8276 8277 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8278 // Pass responsibility to the Backup Manager. It will perform a 8279 // restore if appropriate, then pass responsibility back to the 8280 // Package Manager to run the post-install observer callbacks 8281 // and broadcasts. 8282 IBackupManager bm = IBackupManager.Stub.asInterface( 8283 ServiceManager.getService(Context.BACKUP_SERVICE)); 8284 if (bm != null) { 8285 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8286 + " to BM for possible restore"); 8287 try { 8288 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8289 } catch (RemoteException e) { 8290 // can't happen; the backup manager is local 8291 } catch (Exception e) { 8292 Slog.e(TAG, "Exception trying to enqueue restore", e); 8293 doRestore = false; 8294 } 8295 } else { 8296 Slog.e(TAG, "Backup Manager not found!"); 8297 doRestore = false; 8298 } 8299 } 8300 8301 if (!doRestore) { 8302 // No restore possible, or the Backup Manager was mysteriously not 8303 // available -- just fire the post-install work request directly. 8304 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8305 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8306 mHandler.sendMessage(msg); 8307 } 8308 } 8309 }); 8310 } 8311 8312 private abstract class HandlerParams { 8313 private static final int MAX_RETRIES = 4; 8314 8315 /** 8316 * Number of times startCopy() has been attempted and had a non-fatal 8317 * error. 8318 */ 8319 private int mRetries = 0; 8320 8321 /** User handle for the user requesting the information or installation. */ 8322 private final UserHandle mUser; 8323 8324 HandlerParams(UserHandle user) { 8325 mUser = user; 8326 } 8327 8328 UserHandle getUser() { 8329 return mUser; 8330 } 8331 8332 final boolean startCopy() { 8333 boolean res; 8334 try { 8335 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8336 8337 if (++mRetries > MAX_RETRIES) { 8338 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8339 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8340 handleServiceError(); 8341 return false; 8342 } else { 8343 handleStartCopy(); 8344 res = true; 8345 } 8346 } catch (RemoteException e) { 8347 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8348 mHandler.sendEmptyMessage(MCS_RECONNECT); 8349 res = false; 8350 } 8351 handleReturnCode(); 8352 return res; 8353 } 8354 8355 final void serviceError() { 8356 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8357 handleServiceError(); 8358 handleReturnCode(); 8359 } 8360 8361 abstract void handleStartCopy() throws RemoteException; 8362 abstract void handleServiceError(); 8363 abstract void handleReturnCode(); 8364 } 8365 8366 class MeasureParams extends HandlerParams { 8367 private final PackageStats mStats; 8368 private boolean mSuccess; 8369 8370 private final IPackageStatsObserver mObserver; 8371 8372 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8373 super(new UserHandle(stats.userHandle)); 8374 mObserver = observer; 8375 mStats = stats; 8376 } 8377 8378 @Override 8379 public String toString() { 8380 return "MeasureParams{" 8381 + Integer.toHexString(System.identityHashCode(this)) 8382 + " " + mStats.packageName + "}"; 8383 } 8384 8385 @Override 8386 void handleStartCopy() throws RemoteException { 8387 synchronized (mInstallLock) { 8388 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8389 } 8390 8391 if (mSuccess) { 8392 final boolean mounted; 8393 if (Environment.isExternalStorageEmulated()) { 8394 mounted = true; 8395 } else { 8396 final String status = Environment.getExternalStorageState(); 8397 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8398 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8399 } 8400 8401 if (mounted) { 8402 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8403 8404 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8405 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8406 8407 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8408 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8409 8410 // Always subtract cache size, since it's a subdirectory 8411 mStats.externalDataSize -= mStats.externalCacheSize; 8412 8413 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8414 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8415 8416 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8417 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8418 } 8419 } 8420 } 8421 8422 @Override 8423 void handleReturnCode() { 8424 if (mObserver != null) { 8425 try { 8426 mObserver.onGetStatsCompleted(mStats, mSuccess); 8427 } catch (RemoteException e) { 8428 Slog.i(TAG, "Observer no longer exists."); 8429 } 8430 } 8431 } 8432 8433 @Override 8434 void handleServiceError() { 8435 Slog.e(TAG, "Could not measure application " + mStats.packageName 8436 + " external storage"); 8437 } 8438 } 8439 8440 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8441 throws RemoteException { 8442 long result = 0; 8443 for (File path : paths) { 8444 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8445 } 8446 return result; 8447 } 8448 8449 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8450 for (File path : paths) { 8451 try { 8452 mcs.clearDirectory(path.getAbsolutePath()); 8453 } catch (RemoteException e) { 8454 } 8455 } 8456 } 8457 8458 class InstallParams extends HandlerParams { 8459 /** 8460 * Location where install is coming from, before it has been 8461 * copied/renamed into place. This could be a single monolithic APK 8462 * file, or a cluster directory. This location may be untrusted. 8463 */ 8464 final File originFile; 8465 8466 /** 8467 * Flag indicating that {@link #originFile} lives in a trusted location, 8468 * meaning downstream users don't need to defensively copy the contents. 8469 */ 8470 boolean originTrusted; 8471 8472 final IPackageInstallObserver observer; 8473 final IPackageInstallObserver2 observer2; 8474 int flags; 8475 final String installerPackageName; 8476 final VerificationParams verificationParams; 8477 private InstallArgs mArgs; 8478 private int mRet; 8479 final String packageAbiOverride; 8480 final String packageInstructionSetOverride; 8481 8482 InstallParams(File originFile, IPackageInstallObserver observer, 8483 IPackageInstallObserver2 observer2, int flags, String installerPackageName, 8484 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 8485 super(user); 8486 this.originFile = Preconditions.checkNotNull(originFile); 8487 this.originTrusted = false; 8488 this.observer = observer; 8489 this.observer2 = observer2; 8490 this.flags = flags; 8491 this.installerPackageName = installerPackageName; 8492 this.verificationParams = verificationParams; 8493 this.packageAbiOverride = packageAbiOverride; 8494 this.packageInstructionSetOverride = (packageAbiOverride == null) ? 8495 packageAbiOverride : VMRuntime.getInstructionSet(packageAbiOverride); 8496 } 8497 8498 @Override 8499 public String toString() { 8500 return "InstallParams{" 8501 + Integer.toHexString(System.identityHashCode(this)) 8502 + " " + originFile + "}"; 8503 } 8504 8505 public ManifestDigest getManifestDigest() { 8506 if (verificationParams == null) { 8507 return null; 8508 } 8509 return verificationParams.getManifestDigest(); 8510 } 8511 8512 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8513 String packageName = pkgLite.packageName; 8514 int installLocation = pkgLite.installLocation; 8515 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8516 // reader 8517 synchronized (mPackages) { 8518 PackageParser.Package pkg = mPackages.get(packageName); 8519 if (pkg != null) { 8520 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8521 // Check for downgrading. 8522 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8523 if (pkgLite.versionCode < pkg.mVersionCode) { 8524 Slog.w(TAG, "Can't install update of " + packageName 8525 + " update version " + pkgLite.versionCode 8526 + " is older than installed version " 8527 + pkg.mVersionCode); 8528 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8529 } 8530 } 8531 // Check for updated system application. 8532 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8533 if (onSd) { 8534 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8535 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8536 } 8537 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8538 } else { 8539 if (onSd) { 8540 // Install flag overrides everything. 8541 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8542 } 8543 // If current upgrade specifies particular preference 8544 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8545 // Application explicitly specified internal. 8546 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8547 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8548 // App explictly prefers external. Let policy decide 8549 } else { 8550 // Prefer previous location 8551 if (isExternal(pkg)) { 8552 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8553 } 8554 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8555 } 8556 } 8557 } else { 8558 // Invalid install. Return error code 8559 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8560 } 8561 } 8562 } 8563 // All the special cases have been taken care of. 8564 // Return result based on recommended install location. 8565 if (onSd) { 8566 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8567 } 8568 return pkgLite.recommendedInstallLocation; 8569 } 8570 8571 private long getMemoryLowThreshold() { 8572 final DeviceStorageMonitorInternal 8573 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8574 if (dsm == null) { 8575 return 0L; 8576 } 8577 return dsm.getMemoryLowThreshold(); 8578 } 8579 8580 /* 8581 * Invoke remote method to get package information and install 8582 * location values. Override install location based on default 8583 * policy if needed and then create install arguments based 8584 * on the install location. 8585 */ 8586 public void handleStartCopy() throws RemoteException { 8587 int ret = PackageManager.INSTALL_SUCCEEDED; 8588 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8589 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8590 PackageInfoLite pkgLite = null; 8591 8592 if (onInt && onSd) { 8593 // Check if both bits are set. 8594 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8595 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8596 } else { 8597 final long lowThreshold = getMemoryLowThreshold(); 8598 if (lowThreshold == 0L) { 8599 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8600 } 8601 8602 // Remote call to find out default install location 8603 final String originPath = originFile.getAbsolutePath(); 8604 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold, 8605 packageAbiOverride); 8606 8607 /* 8608 * If we have too little free space, try to free cache 8609 * before giving up. 8610 */ 8611 if (pkgLite.recommendedInstallLocation 8612 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8613 final long size = mContainerService.calculateInstalledSize( 8614 originPath, isForwardLocked(), packageAbiOverride); 8615 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8616 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, 8617 lowThreshold, packageAbiOverride); 8618 } 8619 /* 8620 * The cache free must have deleted the file we 8621 * downloaded to install. 8622 * 8623 * TODO: fix the "freeCache" call to not delete 8624 * the file we care about. 8625 */ 8626 if (pkgLite.recommendedInstallLocation 8627 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8628 pkgLite.recommendedInstallLocation 8629 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8630 } 8631 } 8632 } 8633 8634 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8635 int loc = pkgLite.recommendedInstallLocation; 8636 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8637 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8638 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8639 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8640 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8641 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8642 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8643 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8644 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8645 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8646 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8647 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8648 } else { 8649 // Override with defaults if needed. 8650 loc = installLocationPolicy(pkgLite, flags); 8651 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8652 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8653 } else if (!onSd && !onInt) { 8654 // Override install location with flags 8655 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8656 // Set the flag to install on external media. 8657 flags |= PackageManager.INSTALL_EXTERNAL; 8658 flags &= ~PackageManager.INSTALL_INTERNAL; 8659 } else { 8660 // Make sure the flag for installing on external 8661 // media is unset 8662 flags |= PackageManager.INSTALL_INTERNAL; 8663 flags &= ~PackageManager.INSTALL_EXTERNAL; 8664 } 8665 } 8666 } 8667 } 8668 8669 final InstallArgs args = createInstallArgs(this); 8670 mArgs = args; 8671 8672 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8673 /* 8674 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8675 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8676 */ 8677 int userIdentifier = getUser().getIdentifier(); 8678 if (userIdentifier == UserHandle.USER_ALL 8679 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8680 userIdentifier = UserHandle.USER_OWNER; 8681 } 8682 8683 /* 8684 * Determine if we have any installed package verifiers. If we 8685 * do, then we'll defer to them to verify the packages. 8686 */ 8687 final int requiredUid = mRequiredVerifierPackage == null ? -1 8688 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8689 if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) { 8690 // TODO: send verifier the install session instead of uri 8691 final Intent verification = new Intent( 8692 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8693 verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE); 8694 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8695 8696 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8697 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8698 0 /* TODO: Which userId? */); 8699 8700 if (DEBUG_VERIFY) { 8701 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8702 + verification.toString() + " with " + pkgLite.verifiers.length 8703 + " optional verifiers"); 8704 } 8705 8706 final int verificationId = mPendingVerificationToken++; 8707 8708 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8709 8710 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8711 installerPackageName); 8712 8713 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8714 8715 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8716 pkgLite.packageName); 8717 8718 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8719 pkgLite.versionCode); 8720 8721 if (verificationParams != null) { 8722 if (verificationParams.getVerificationURI() != null) { 8723 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8724 verificationParams.getVerificationURI()); 8725 } 8726 if (verificationParams.getOriginatingURI() != null) { 8727 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8728 verificationParams.getOriginatingURI()); 8729 } 8730 if (verificationParams.getReferrer() != null) { 8731 verification.putExtra(Intent.EXTRA_REFERRER, 8732 verificationParams.getReferrer()); 8733 } 8734 if (verificationParams.getOriginatingUid() >= 0) { 8735 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8736 verificationParams.getOriginatingUid()); 8737 } 8738 if (verificationParams.getInstallerUid() >= 0) { 8739 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8740 verificationParams.getInstallerUid()); 8741 } 8742 } 8743 8744 final PackageVerificationState verificationState = new PackageVerificationState( 8745 requiredUid, args); 8746 8747 mPendingVerification.append(verificationId, verificationState); 8748 8749 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8750 receivers, verificationState); 8751 8752 /* 8753 * If any sufficient verifiers were listed in the package 8754 * manifest, attempt to ask them. 8755 */ 8756 if (sufficientVerifiers != null) { 8757 final int N = sufficientVerifiers.size(); 8758 if (N == 0) { 8759 Slog.i(TAG, "Additional verifiers required, but none installed."); 8760 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8761 } else { 8762 for (int i = 0; i < N; i++) { 8763 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8764 8765 final Intent sufficientIntent = new Intent(verification); 8766 sufficientIntent.setComponent(verifierComponent); 8767 8768 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8769 } 8770 } 8771 } 8772 8773 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8774 mRequiredVerifierPackage, receivers); 8775 if (ret == PackageManager.INSTALL_SUCCEEDED 8776 && mRequiredVerifierPackage != null) { 8777 /* 8778 * Send the intent to the required verification agent, 8779 * but only start the verification timeout after the 8780 * target BroadcastReceivers have run. 8781 */ 8782 verification.setComponent(requiredVerifierComponent); 8783 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8784 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8785 new BroadcastReceiver() { 8786 @Override 8787 public void onReceive(Context context, Intent intent) { 8788 final Message msg = mHandler 8789 .obtainMessage(CHECK_PENDING_VERIFICATION); 8790 msg.arg1 = verificationId; 8791 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8792 } 8793 }, null, 0, null, null); 8794 8795 /* 8796 * We don't want the copy to proceed until verification 8797 * succeeds, so null out this field. 8798 */ 8799 mArgs = null; 8800 } 8801 } else { 8802 /* 8803 * No package verification is enabled, so immediately start 8804 * the remote call to initiate copy using temporary file. 8805 */ 8806 ret = args.copyApk(mContainerService, true); 8807 } 8808 } 8809 8810 mRet = ret; 8811 } 8812 8813 @Override 8814 void handleReturnCode() { 8815 // If mArgs is null, then MCS couldn't be reached. When it 8816 // reconnects, it will try again to install. At that point, this 8817 // will succeed. 8818 if (mArgs != null) { 8819 processPendingInstall(mArgs, mRet); 8820 } 8821 } 8822 8823 @Override 8824 void handleServiceError() { 8825 mArgs = createInstallArgs(this); 8826 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8827 } 8828 8829 public boolean isForwardLocked() { 8830 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8831 } 8832 } 8833 8834 /* 8835 * Utility class used in movePackage api. 8836 * srcArgs and targetArgs are not set for invalid flags and make 8837 * sure to do null checks when invoking methods on them. 8838 * We probably want to return ErrorPrams for both failed installs 8839 * and moves. 8840 */ 8841 class MoveParams extends HandlerParams { 8842 final IPackageMoveObserver observer; 8843 final int flags; 8844 final String packageName; 8845 final InstallArgs srcArgs; 8846 final InstallArgs targetArgs; 8847 int uid; 8848 int mRet; 8849 8850 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8851 String packageName, String instructionSet, int uid, UserHandle user) { 8852 super(user); 8853 this.srcArgs = srcArgs; 8854 this.observer = observer; 8855 this.flags = flags; 8856 this.packageName = packageName; 8857 this.uid = uid; 8858 if (srcArgs != null) { 8859 final String codePath = srcArgs.getCodePath(); 8860 targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, 8861 instructionSet); 8862 } else { 8863 targetArgs = null; 8864 } 8865 } 8866 8867 @Override 8868 public String toString() { 8869 return "MoveParams{" 8870 + Integer.toHexString(System.identityHashCode(this)) 8871 + " " + packageName + "}"; 8872 } 8873 8874 public void handleStartCopy() throws RemoteException { 8875 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8876 // Check for storage space on target medium 8877 if (!targetArgs.checkFreeStorage(mContainerService)) { 8878 Log.w(TAG, "Insufficient storage to install"); 8879 return; 8880 } 8881 8882 mRet = srcArgs.doPreCopy(); 8883 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8884 return; 8885 } 8886 8887 mRet = targetArgs.copyApk(mContainerService, false); 8888 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8889 srcArgs.doPostCopy(uid); 8890 return; 8891 } 8892 8893 mRet = srcArgs.doPostCopy(uid); 8894 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8895 return; 8896 } 8897 8898 mRet = targetArgs.doPreInstall(mRet); 8899 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8900 return; 8901 } 8902 8903 if (DEBUG_SD_INSTALL) { 8904 StringBuilder builder = new StringBuilder(); 8905 if (srcArgs != null) { 8906 builder.append("src: "); 8907 builder.append(srcArgs.getCodePath()); 8908 } 8909 if (targetArgs != null) { 8910 builder.append(" target : "); 8911 builder.append(targetArgs.getCodePath()); 8912 } 8913 Log.i(TAG, builder.toString()); 8914 } 8915 } 8916 8917 @Override 8918 void handleReturnCode() { 8919 targetArgs.doPostInstall(mRet, uid); 8920 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8921 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8922 currentStatus = PackageManager.MOVE_SUCCEEDED; 8923 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8924 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8925 } 8926 processPendingMove(this, currentStatus); 8927 } 8928 8929 @Override 8930 void handleServiceError() { 8931 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8932 } 8933 } 8934 8935 /** 8936 * Used during creation of InstallArgs 8937 * 8938 * @param flags package installation flags 8939 * @return true if should be installed on external storage 8940 */ 8941 private static boolean installOnSd(int flags) { 8942 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8943 return false; 8944 } 8945 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8946 return true; 8947 } 8948 return false; 8949 } 8950 8951 /** 8952 * Used during creation of InstallArgs 8953 * 8954 * @param flags package installation flags 8955 * @return true if should be installed as forward locked 8956 */ 8957 private static boolean installForwardLocked(int flags) { 8958 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8959 } 8960 8961 private InstallArgs createInstallArgs(InstallParams params) { 8962 // TODO: extend to support incoming zero-copy locations 8963 8964 if (installOnSd(params.flags) || params.isForwardLocked()) { 8965 return new AsecInstallArgs(params); 8966 } else { 8967 return new FileInstallArgs(params); 8968 } 8969 } 8970 8971 /** 8972 * Create args that describe an existing installed package. Typically used 8973 * when cleaning up old installs, or used as a move source. 8974 */ 8975 private InstallArgs createInstallArgsForExisting(int flags, String codePath, 8976 String resourcePath, String nativeLibraryPath, String instructionSet) { 8977 final boolean isInAsec; 8978 if (installOnSd(flags)) { 8979 /* Apps on SD card are always in ASEC containers. */ 8980 isInAsec = true; 8981 } else if (installForwardLocked(flags) 8982 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8983 /* 8984 * Forward-locked apps are only in ASEC containers if they're the 8985 * new style 8986 */ 8987 isInAsec = true; 8988 } else { 8989 isInAsec = false; 8990 } 8991 8992 if (isInAsec) { 8993 return new AsecInstallArgs(codePath, resourcePath, nativeLibraryPath, 8994 instructionSet, installOnSd(flags), installForwardLocked(flags)); 8995 } else { 8996 return new FileInstallArgs(codePath, resourcePath, nativeLibraryPath, instructionSet); 8997 } 8998 } 8999 9000 private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName, 9001 String instructionSet) { 9002 final File codeFile = new File(codePath); 9003 if (installOnSd(flags) || installForwardLocked(flags)) { 9004 String cid = getNextCodePath(codePath, pkgName, "/" 9005 + AsecInstallArgs.RES_FILE_NAME); 9006 return new AsecInstallArgs(codeFile, cid, instructionSet, installOnSd(flags), 9007 installForwardLocked(flags)); 9008 } else { 9009 return new FileInstallArgs(codeFile, instructionSet); 9010 } 9011 } 9012 9013 static abstract class InstallArgs { 9014 /** @see InstallParams#originFile */ 9015 final File originFile; 9016 /** @see InstallParams#originTrusted */ 9017 final boolean originTrusted; 9018 9019 // TODO: define inherit location 9020 9021 final IPackageInstallObserver observer; 9022 final IPackageInstallObserver2 observer2; 9023 // Always refers to PackageManager flags only 9024 final int flags; 9025 final String installerPackageName; 9026 final ManifestDigest manifestDigest; 9027 final UserHandle user; 9028 final String instructionSet; 9029 final String abiOverride; 9030 9031 InstallArgs(File originFile, boolean originTrusted, IPackageInstallObserver observer, 9032 IPackageInstallObserver2 observer2, int flags, String installerPackageName, 9033 ManifestDigest manifestDigest, UserHandle user, String instructionSet, 9034 String abiOverride) { 9035 this.originFile = originFile; 9036 this.originTrusted = originTrusted; 9037 this.flags = flags; 9038 this.observer = observer; 9039 this.observer2 = observer2; 9040 this.installerPackageName = installerPackageName; 9041 this.manifestDigest = manifestDigest; 9042 this.user = user; 9043 this.instructionSet = instructionSet; 9044 this.abiOverride = abiOverride; 9045 } 9046 9047 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9048 abstract int doPreInstall(int status); 9049 9050 /** 9051 * Rename package into final resting place. All paths on the given 9052 * scanned package should be updated to reflect the rename. 9053 */ 9054 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9055 abstract int doPostInstall(int status, int uid); 9056 9057 /** @see PackageSettingBase#codePathString */ 9058 abstract String getCodePath(); 9059 /** @see PackageSettingBase#resourcePathString */ 9060 abstract String getResourcePath(); 9061 /** @see PackageSettingBase#nativeLibraryPathString */ 9062 abstract String getNativeLibraryPath(); 9063 9064 // Need installer lock especially for dex file removal. 9065 abstract void cleanUpResourcesLI(); 9066 abstract boolean doPostDeleteLI(boolean delete); 9067 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9068 9069 /** 9070 * Called before the source arguments are copied. This is used mostly 9071 * for MoveParams when it needs to read the source file to put it in the 9072 * destination. 9073 */ 9074 int doPreCopy() { 9075 return PackageManager.INSTALL_SUCCEEDED; 9076 } 9077 9078 /** 9079 * Called after the source arguments are copied. This is used mostly for 9080 * MoveParams when it needs to read the source file to put it in the 9081 * destination. 9082 * 9083 * @return 9084 */ 9085 int doPostCopy(int uid) { 9086 return PackageManager.INSTALL_SUCCEEDED; 9087 } 9088 9089 protected boolean isFwdLocked() { 9090 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9091 } 9092 9093 UserHandle getUser() { 9094 return user; 9095 } 9096 } 9097 9098 /** 9099 * Logic to handle installation of non-ASEC applications, including copying 9100 * and renaming logic. 9101 */ 9102 class FileInstallArgs extends InstallArgs { 9103 private File codeFile; 9104 private File resourceFile; 9105 private File nativeLibraryFile; 9106 9107 // Example topology: 9108 // /data/app/com.example/base.apk 9109 // /data/app/com.example/split_foo.apk 9110 // /data/app/com.example/lib/arm/libfoo.so 9111 // /data/app/com.example/lib/arm64/libfoo.so 9112 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9113 9114 /** New install */ 9115 FileInstallArgs(InstallParams params) { 9116 super(params.originFile, params.originTrusted, params.observer, params.observer2, 9117 params.flags, params.installerPackageName, params.getManifestDigest(), 9118 params.getUser(), params.packageInstructionSetOverride, 9119 params.packageAbiOverride); 9120 if (isFwdLocked()) { 9121 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9122 } 9123 } 9124 9125 /** Existing install */ 9126 FileInstallArgs(String codePath, String resourcePath, String nativeLibraryPath, 9127 String instructionSet) { 9128 super(null, false, null, null, 0, null, null, null, instructionSet, null); 9129 this.codeFile = (codePath != null) ? new File(codePath) : null; 9130 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9131 this.nativeLibraryFile = (nativeLibraryPath != null) ? new File(nativeLibraryPath) : null; 9132 } 9133 9134 /** New install from existing */ 9135 FileInstallArgs(File originFile, String instructionSet) { 9136 super(originFile, true, null, null, 0, null, null, null, instructionSet, null); 9137 } 9138 9139 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9140 final long lowThreshold; 9141 9142 final DeviceStorageMonitorInternal 9143 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9144 if (dsm == null) { 9145 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9146 lowThreshold = 0L; 9147 } else { 9148 if (dsm.isMemoryLow()) { 9149 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9150 return false; 9151 } 9152 9153 lowThreshold = dsm.getMemoryLowThreshold(); 9154 } 9155 9156 return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9157 lowThreshold); 9158 } 9159 9160 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9161 try { 9162 final File tempDir = createTempPackageDir(mAppInstallDir); 9163 codeFile = tempDir; 9164 resourceFile = tempDir; 9165 } catch (IOException e) { 9166 Slog.w(TAG, "Failed to create copy file: " + e); 9167 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9168 } 9169 9170 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9171 @Override 9172 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9173 if (!FileUtils.isValidExtFilename(name)) { 9174 throw new IllegalArgumentException("Invalid filename: " + name); 9175 } 9176 try { 9177 final File file = new File(codeFile, name); 9178 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9179 O_RDWR | O_CREAT, 0644); 9180 Os.chmod(file.getAbsolutePath(), 0644); 9181 return new ParcelFileDescriptor(fd); 9182 } catch (ErrnoException e) { 9183 throw new RemoteException("Failed to open: " + e.getMessage()); 9184 } 9185 } 9186 }; 9187 9188 int ret = imcs.copyPackage(originFile.getAbsolutePath(), target); 9189 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9190 Slog.e(TAG, "Failed to copy package"); 9191 return ret; 9192 } 9193 9194 String[] abiList = (abiOverride != null) ? 9195 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 9196 NativeLibraryHelper.Handle handle = null; 9197 try { 9198 handle = NativeLibraryHelper.Handle.create(codeFile); 9199 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && 9200 abiOverride == null && 9201 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9202 abiList = Build.SUPPORTED_32_BIT_ABIS; 9203 } 9204 9205 // TODO: refactor to avoid double findSupportedAbi() 9206 final int abiIndex = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9207 if (abiIndex < 0 && abiIndex != PackageManager.NO_NATIVE_LIBRARIES) { 9208 return abiIndex; 9209 } else if (abiIndex >= 0) { 9210 final File baseLibFile = new File(codeFile, LIB_DIR_NAME); 9211 baseLibFile.mkdir(); 9212 Os.chmod(baseLibFile.getAbsolutePath(), 0755); 9213 9214 final String abi = Build.SUPPORTED_ABIS[abiIndex]; 9215 final String instructionSet = VMRuntime.getInstructionSet(abi); 9216 nativeLibraryFile = new File(baseLibFile, instructionSet); 9217 nativeLibraryFile.mkdir(); 9218 Os.chmod(nativeLibraryFile.getAbsolutePath(), 0755); 9219 9220 copyNativeLibrariesForInternalApp(handle, nativeLibraryFile, abiList); 9221 } 9222 } catch (IOException | ErrnoException e) { 9223 Slog.e(TAG, "Copying native libraries failed", e); 9224 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9225 } finally { 9226 IoUtils.closeQuietly(handle); 9227 } 9228 9229 return ret; 9230 } 9231 9232 int doPreInstall(int status) { 9233 if (status != PackageManager.INSTALL_SUCCEEDED) { 9234 cleanUp(); 9235 } 9236 return status; 9237 } 9238 9239 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9240 if (status != PackageManager.INSTALL_SUCCEEDED) { 9241 cleanUp(); 9242 return false; 9243 } else { 9244 final File beforeCodeFile = codeFile; 9245 final File afterCodeFile = new File(mAppInstallDir, 9246 getNextCodePath(oldCodePath, pkg.packageName, null)); 9247 9248 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9249 if (!beforeCodeFile.renameTo(afterCodeFile)) { 9250 return false; 9251 } 9252 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9253 return false; 9254 } 9255 9256 // Reflect the rename internally 9257 codeFile = afterCodeFile; 9258 resourceFile = afterCodeFile; 9259 nativeLibraryFile = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9260 nativeLibraryFile); 9261 9262 // Reflect the rename in scanned details 9263 pkg.codePath = afterCodeFile.getAbsolutePath(); 9264 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9265 pkg.baseCodePath); 9266 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9267 pkg.splitCodePaths); 9268 9269 // Reflect the rename in app info 9270 pkg.applicationInfo.setCodePath(pkg.codePath); 9271 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9272 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9273 pkg.applicationInfo.setResourcePath(pkg.codePath); 9274 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9275 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9276 pkg.applicationInfo.nativeLibraryDir = getNativeLibraryPath(); 9277 9278 return true; 9279 } 9280 } 9281 9282 int doPostInstall(int status, int uid) { 9283 if (status != PackageManager.INSTALL_SUCCEEDED) { 9284 cleanUp(); 9285 } 9286 return status; 9287 } 9288 9289 @Override 9290 String getCodePath() { 9291 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9292 } 9293 9294 @Override 9295 String getResourcePath() { 9296 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9297 } 9298 9299 @Override 9300 String getNativeLibraryPath() { 9301 return (nativeLibraryFile != null) ? nativeLibraryFile.getAbsolutePath() : null; 9302 } 9303 9304 private boolean cleanUp() { 9305 if (codeFile == null || !codeFile.exists()) { 9306 return false; 9307 } 9308 9309 if (codeFile.isDirectory()) { 9310 FileUtils.deleteContents(codeFile); 9311 } 9312 codeFile.delete(); 9313 9314 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9315 resourceFile.delete(); 9316 } 9317 9318 if (nativeLibraryFile != null && !FileUtils.contains(codeFile, nativeLibraryFile)) { 9319 FileUtils.deleteContents(nativeLibraryFile); 9320 nativeLibraryFile.delete(); 9321 } 9322 9323 return true; 9324 } 9325 9326 void cleanUpResourcesLI() { 9327 // Try enumerating all code paths before deleting 9328 List<String> allCodePaths = Collections.EMPTY_LIST; 9329 if (codeFile != null && codeFile.exists()) { 9330 try { 9331 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9332 allCodePaths = pkg.getAllCodePaths(); 9333 } catch (PackageParserException e) { 9334 // Ignored; we tried our best 9335 } 9336 } 9337 9338 cleanUp(); 9339 9340 if (!allCodePaths.isEmpty()) { 9341 if (instructionSet == null) { 9342 throw new IllegalStateException("instructionSet == null"); 9343 } 9344 9345 for (String codePath : allCodePaths) { 9346 int retCode = mInstaller.rmdex(codePath, instructionSet); 9347 if (retCode < 0) { 9348 Slog.w(TAG, "Couldn't remove dex file for package: " 9349 + " at location " + codePath + ", retcode=" + retCode); 9350 // we don't consider this to be a failure of the core package deletion 9351 } 9352 } 9353 } 9354 } 9355 9356 boolean doPostDeleteLI(boolean delete) { 9357 // XXX err, shouldn't we respect the delete flag? 9358 cleanUpResourcesLI(); 9359 return true; 9360 } 9361 } 9362 9363 private boolean isAsecExternal(String cid) { 9364 final String asecPath = PackageHelper.getSdFilesystem(cid); 9365 return !asecPath.startsWith(mAsecInternalPath); 9366 } 9367 9368 /** 9369 * Extract the MountService "container ID" from the full code path of an 9370 * .apk. 9371 */ 9372 static String cidFromCodePath(String fullCodePath) { 9373 int eidx = fullCodePath.lastIndexOf("/"); 9374 String subStr1 = fullCodePath.substring(0, eidx); 9375 int sidx = subStr1.lastIndexOf("/"); 9376 return subStr1.substring(sidx+1, eidx); 9377 } 9378 9379 /** 9380 * Logic to handle installation of ASEC applications, including copying and 9381 * renaming logic. 9382 */ 9383 class AsecInstallArgs extends InstallArgs { 9384 // TODO: teach about handling cluster directories 9385 9386 static final String RES_FILE_NAME = "pkg.apk"; 9387 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9388 9389 String cid; 9390 String packagePath; 9391 String resourcePath; 9392 String libraryPath; 9393 9394 /** New install */ 9395 AsecInstallArgs(InstallParams params) { 9396 super(params.originFile, params.originTrusted, params.observer, params.observer2, 9397 params.flags, params.installerPackageName, params.getManifestDigest(), 9398 params.getUser(), params.packageInstructionSetOverride, 9399 params.packageAbiOverride); 9400 } 9401 9402 /** Existing install */ 9403 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 9404 String instructionSet, boolean isExternal, boolean isForwardLocked) { 9405 super(null, false, null, null, (isExternal ? INSTALL_EXTERNAL : 0) 9406 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9407 instructionSet, null); 9408 // Extract cid from fullCodePath 9409 int eidx = fullCodePath.lastIndexOf("/"); 9410 String subStr1 = fullCodePath.substring(0, eidx); 9411 int sidx = subStr1.lastIndexOf("/"); 9412 cid = subStr1.substring(sidx+1, eidx); 9413 setCachePath(subStr1); 9414 } 9415 9416 AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) { 9417 super(null, false, null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9418 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9419 instructionSet, null); 9420 this.cid = cid; 9421 setCachePath(PackageHelper.getSdDir(cid)); 9422 } 9423 9424 /** New install from existing */ 9425 AsecInstallArgs(File originPackageFile, String cid, String instructionSet, 9426 boolean isExternal, boolean isForwardLocked) { 9427 super(originPackageFile, true, null, null, (isExternal ? INSTALL_EXTERNAL : 0) 9428 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9429 instructionSet, null); 9430 this.cid = cid; 9431 } 9432 9433 void createCopyFile() { 9434 cid = getTempContainerId(); 9435 } 9436 9437 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9438 return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9439 abiOverride); 9440 } 9441 9442 private final boolean isExternal() { 9443 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9444 } 9445 9446 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9447 if (temp) { 9448 createCopyFile(); 9449 } else { 9450 /* 9451 * Pre-emptively destroy the container since it's destroyed if 9452 * copying fails due to it existing anyway. 9453 */ 9454 PackageHelper.destroySdDir(cid); 9455 } 9456 9457 final String newCachePath = imcs.copyPackageToContainer( 9458 originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9459 isFwdLocked(), abiOverride); 9460 9461 if (newCachePath != null) { 9462 setCachePath(newCachePath); 9463 return PackageManager.INSTALL_SUCCEEDED; 9464 } else { 9465 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9466 } 9467 } 9468 9469 @Override 9470 String getCodePath() { 9471 return packagePath; 9472 } 9473 9474 @Override 9475 String getResourcePath() { 9476 return resourcePath; 9477 } 9478 9479 @Override 9480 String getNativeLibraryPath() { 9481 return libraryPath; 9482 } 9483 9484 int doPreInstall(int status) { 9485 if (status != PackageManager.INSTALL_SUCCEEDED) { 9486 // Destroy container 9487 PackageHelper.destroySdDir(cid); 9488 } else { 9489 boolean mounted = PackageHelper.isContainerMounted(cid); 9490 if (!mounted) { 9491 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9492 Process.SYSTEM_UID); 9493 if (newCachePath != null) { 9494 setCachePath(newCachePath); 9495 } else { 9496 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9497 } 9498 } 9499 } 9500 return status; 9501 } 9502 9503 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9504 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9505 String newCachePath = null; 9506 if (PackageHelper.isContainerMounted(cid)) { 9507 // Unmount the container 9508 if (!PackageHelper.unMountSdDir(cid)) { 9509 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9510 return false; 9511 } 9512 } 9513 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9514 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9515 " which might be stale. Will try to clean up."); 9516 // Clean up the stale container and proceed to recreate. 9517 if (!PackageHelper.destroySdDir(newCacheId)) { 9518 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9519 return false; 9520 } 9521 // Successfully cleaned up stale container. Try to rename again. 9522 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9523 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9524 + " inspite of cleaning it up."); 9525 return false; 9526 } 9527 } 9528 if (!PackageHelper.isContainerMounted(newCacheId)) { 9529 Slog.w(TAG, "Mounting container " + newCacheId); 9530 newCachePath = PackageHelper.mountSdDir(newCacheId, 9531 getEncryptKey(), Process.SYSTEM_UID); 9532 } else { 9533 newCachePath = PackageHelper.getSdDir(newCacheId); 9534 } 9535 if (newCachePath == null) { 9536 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9537 return false; 9538 } 9539 Log.i(TAG, "Succesfully renamed " + cid + 9540 " to " + newCacheId + 9541 " at new path: " + newCachePath); 9542 cid = newCacheId; 9543 setCachePath(newCachePath); 9544 9545 // TODO: extend to support split APKs 9546 pkg.codePath = getCodePath(); 9547 pkg.baseCodePath = getCodePath(); 9548 pkg.splitCodePaths = null; 9549 9550 pkg.applicationInfo.setCodePath(getCodePath()); 9551 pkg.applicationInfo.setBaseCodePath(getCodePath()); 9552 pkg.applicationInfo.setSplitCodePaths(null); 9553 pkg.applicationInfo.setResourcePath(getResourcePath()); 9554 pkg.applicationInfo.setBaseResourcePath(getResourcePath()); 9555 pkg.applicationInfo.setSplitResourcePaths(null); 9556 pkg.applicationInfo.nativeLibraryDir = getNativeLibraryPath(); 9557 9558 return true; 9559 } 9560 9561 private void setCachePath(String newCachePath) { 9562 File cachePath = new File(newCachePath); 9563 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath(); 9564 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9565 9566 if (isFwdLocked()) { 9567 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9568 } else { 9569 resourcePath = packagePath; 9570 } 9571 } 9572 9573 int doPostInstall(int status, int uid) { 9574 if (status != PackageManager.INSTALL_SUCCEEDED) { 9575 cleanUp(); 9576 } else { 9577 final int groupOwner; 9578 final String protectedFile; 9579 if (isFwdLocked()) { 9580 groupOwner = UserHandle.getSharedAppGid(uid); 9581 protectedFile = RES_FILE_NAME; 9582 } else { 9583 groupOwner = -1; 9584 protectedFile = null; 9585 } 9586 9587 if (uid < Process.FIRST_APPLICATION_UID 9588 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9589 Slog.e(TAG, "Failed to finalize " + cid); 9590 PackageHelper.destroySdDir(cid); 9591 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9592 } 9593 9594 boolean mounted = PackageHelper.isContainerMounted(cid); 9595 if (!mounted) { 9596 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9597 } 9598 } 9599 return status; 9600 } 9601 9602 private void cleanUp() { 9603 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9604 9605 // Destroy secure container 9606 PackageHelper.destroySdDir(cid); 9607 } 9608 9609 void cleanUpResourcesLI() { 9610 String sourceFile = getCodePath(); 9611 // Remove dex file 9612 if (instructionSet == null) { 9613 throw new IllegalStateException("instructionSet == null"); 9614 } 9615 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9616 if (retCode < 0) { 9617 Slog.w(TAG, "Couldn't remove dex file for package: " 9618 + " at location " 9619 + sourceFile.toString() + ", retcode=" + retCode); 9620 // we don't consider this to be a failure of the core package deletion 9621 } 9622 cleanUp(); 9623 } 9624 9625 boolean matchContainer(String app) { 9626 if (cid.startsWith(app)) { 9627 return true; 9628 } 9629 return false; 9630 } 9631 9632 String getPackageName() { 9633 return getAsecPackageName(cid); 9634 } 9635 9636 boolean doPostDeleteLI(boolean delete) { 9637 boolean ret = false; 9638 boolean mounted = PackageHelper.isContainerMounted(cid); 9639 if (mounted) { 9640 // Unmount first 9641 ret = PackageHelper.unMountSdDir(cid); 9642 } 9643 if (ret && delete) { 9644 cleanUpResourcesLI(); 9645 } 9646 return ret; 9647 } 9648 9649 @Override 9650 int doPreCopy() { 9651 if (isFwdLocked()) { 9652 if (!PackageHelper.fixSdPermissions(cid, 9653 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9654 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9655 } 9656 } 9657 9658 return PackageManager.INSTALL_SUCCEEDED; 9659 } 9660 9661 @Override 9662 int doPostCopy(int uid) { 9663 if (isFwdLocked()) { 9664 if (uid < Process.FIRST_APPLICATION_UID 9665 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9666 RES_FILE_NAME)) { 9667 Slog.e(TAG, "Failed to finalize " + cid); 9668 PackageHelper.destroySdDir(cid); 9669 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9670 } 9671 } 9672 9673 return PackageManager.INSTALL_SUCCEEDED; 9674 } 9675 } 9676 9677 static String getAsecPackageName(String packageCid) { 9678 int idx = packageCid.lastIndexOf("-"); 9679 if (idx == -1) { 9680 return packageCid; 9681 } 9682 return packageCid.substring(0, idx); 9683 } 9684 9685 // Utility method used to create code paths based on package name and available index. 9686 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9687 String idxStr = ""; 9688 int idx = 1; 9689 // Fall back to default value of idx=1 if prefix is not 9690 // part of oldCodePath 9691 if (oldCodePath != null) { 9692 String subStr = oldCodePath; 9693 // Drop the suffix right away 9694 if (suffix != null && subStr.endsWith(suffix)) { 9695 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9696 } 9697 // If oldCodePath already contains prefix find out the 9698 // ending index to either increment or decrement. 9699 int sidx = subStr.lastIndexOf(prefix); 9700 if (sidx != -1) { 9701 subStr = subStr.substring(sidx + prefix.length()); 9702 if (subStr != null) { 9703 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9704 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9705 } 9706 try { 9707 idx = Integer.parseInt(subStr); 9708 if (idx <= 1) { 9709 idx++; 9710 } else { 9711 idx--; 9712 } 9713 } catch(NumberFormatException e) { 9714 } 9715 } 9716 } 9717 } 9718 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9719 return prefix + idxStr; 9720 } 9721 9722 // Utility method used to ignore ADD/REMOVE events 9723 // by directory observer. 9724 private static boolean ignoreCodePath(String fullPathStr) { 9725 String apkName = deriveCodePathName(fullPathStr); 9726 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9727 if (idx != -1 && ((idx+1) < apkName.length())) { 9728 // Make sure the package ends with a numeral 9729 String version = apkName.substring(idx+1); 9730 try { 9731 Integer.parseInt(version); 9732 return true; 9733 } catch (NumberFormatException e) {} 9734 } 9735 return false; 9736 } 9737 9738 // Utility method that returns the relative package path with respect 9739 // to the installation directory. Like say for /data/data/com.test-1.apk 9740 // string com.test-1 is returned. 9741 static String deriveCodePathName(String codePath) { 9742 if (codePath == null) { 9743 return null; 9744 } 9745 final File codeFile = new File(codePath); 9746 final String name = codeFile.getName(); 9747 if (codeFile.isDirectory()) { 9748 return name; 9749 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9750 final int lastDot = name.lastIndexOf('.'); 9751 return name.substring(0, lastDot); 9752 } else { 9753 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9754 return null; 9755 } 9756 } 9757 9758 class PackageInstalledInfo { 9759 String name; 9760 int uid; 9761 // The set of users that originally had this package installed. 9762 int[] origUsers; 9763 // The set of users that now have this package installed. 9764 int[] newUsers; 9765 PackageParser.Package pkg; 9766 int returnCode; 9767 PackageRemovedInfo removedInfo; 9768 9769 // In some error cases we want to convey more info back to the observer 9770 String origPackage; 9771 String origPermission; 9772 } 9773 9774 /* 9775 * Install a non-existing package. 9776 */ 9777 private void installNewPackageLI(PackageParser.Package pkg, 9778 int parseFlags, int scanMode, UserHandle user, 9779 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9780 // Remember this for later, in case we need to rollback this install 9781 String pkgName = pkg.packageName; 9782 9783 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9784 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9785 synchronized(mPackages) { 9786 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9787 // A package with the same name is already installed, though 9788 // it has been renamed to an older name. The package we 9789 // are trying to install should be installed as an update to 9790 // the existing one, but that has not been requested, so bail. 9791 Slog.w(TAG, "Attempt to re-install " + pkgName 9792 + " without first uninstalling package running as " 9793 + mSettings.mRenamedPackages.get(pkgName)); 9794 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9795 return; 9796 } 9797 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9798 // Don't allow installation over an existing package with the same name. 9799 Slog.w(TAG, "Attempt to re-install " + pkgName 9800 + " without first uninstalling."); 9801 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9802 return; 9803 } 9804 } 9805 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9806 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9807 System.currentTimeMillis(), user, abiOverride); 9808 if (newPackage == null) { 9809 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 9810 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9811 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9812 } 9813 } else { 9814 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9815 // delete the partially installed application. the data directory will have to be 9816 // restored if it was already existing 9817 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9818 // remove package from internal structures. Note that we want deletePackageX to 9819 // delete the package data and cache directories that it created in 9820 // scanPackageLocked, unless those directories existed before we even tried to 9821 // install. 9822 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9823 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9824 res.removedInfo, true); 9825 } 9826 } 9827 } 9828 9829 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9830 // Upgrade keysets are being used. Determine if new package has a superset of the 9831 // required keys. 9832 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9833 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9834 Set<Long> newSigningKeyIds = new ArraySet<Long>(); 9835 for (PublicKey pk : newPkg.mSigningKeys) { 9836 newSigningKeyIds.add(ksms.getIdForPublicKey(pk)); 9837 } 9838 //remove PUBLIC_KEY_NOT_FOUND, although not necessary 9839 newSigningKeyIds.remove(ksms.PUBLIC_KEY_NOT_FOUND); 9840 for (int i = 0; i < upgradeKeySets.length; i++) { 9841 if (newSigningKeyIds.containsAll(ksms.mKeySetMapping.get(upgradeKeySets[i]))) { 9842 return true; 9843 } 9844 } 9845 return false; 9846 } 9847 9848 private void replacePackageLI(PackageParser.Package pkg, 9849 int parseFlags, int scanMode, UserHandle user, 9850 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9851 PackageParser.Package oldPackage; 9852 String pkgName = pkg.packageName; 9853 int[] allUsers; 9854 boolean[] perUserInstalled; 9855 9856 // First find the old package info and check signatures 9857 synchronized(mPackages) { 9858 oldPackage = mPackages.get(pkgName); 9859 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9860 PackageSetting ps = mSettings.mPackages.get(pkgName); 9861 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9862 // default to original signature matching 9863 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9864 != PackageManager.SIGNATURE_MATCH) { 9865 Slog.w(TAG, "New package has a different signature: " + pkgName); 9866 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9867 return; 9868 } 9869 } else { 9870 if(!checkUpgradeKeySetLP(ps, pkg)) { 9871 Slog.w(TAG, "New package not signed by keys specified by upgrade-keysets: " 9872 + pkgName); 9873 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9874 return; 9875 } 9876 } 9877 9878 // In case of rollback, remember per-user/profile install state 9879 allUsers = sUserManager.getUserIds(); 9880 perUserInstalled = new boolean[allUsers.length]; 9881 for (int i = 0; i < allUsers.length; i++) { 9882 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9883 } 9884 } 9885 boolean sysPkg = (isSystemApp(oldPackage)); 9886 if (sysPkg) { 9887 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9888 user, allUsers, perUserInstalled, installerPackageName, res, 9889 abiOverride); 9890 } else { 9891 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9892 user, allUsers, perUserInstalled, installerPackageName, res, 9893 abiOverride); 9894 } 9895 } 9896 9897 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9898 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9899 int[] allUsers, boolean[] perUserInstalled, 9900 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9901 PackageParser.Package newPackage = null; 9902 String pkgName = deletedPackage.packageName; 9903 boolean deletedPkg = true; 9904 boolean updatedSettings = false; 9905 9906 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9907 + deletedPackage); 9908 long origUpdateTime; 9909 if (pkg.mExtras != null) { 9910 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9911 } else { 9912 origUpdateTime = 0; 9913 } 9914 9915 // First delete the existing package while retaining the data directory 9916 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9917 res.removedInfo, true)) { 9918 // If the existing package wasn't successfully deleted 9919 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9920 deletedPkg = false; 9921 } else { 9922 // Successfully deleted the old package. Now proceed with re-installation 9923 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9924 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 9925 System.currentTimeMillis(), user, abiOverride); 9926 if (newPackage == null) { 9927 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 9928 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9929 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9930 } 9931 } else { 9932 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9933 updatedSettings = true; 9934 } 9935 } 9936 9937 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9938 // remove package from internal structures. Note that we want deletePackageX to 9939 // delete the package data and cache directories that it created in 9940 // scanPackageLocked, unless those directories existed before we even tried to 9941 // install. 9942 if(updatedSettings) { 9943 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9944 deletePackageLI( 9945 pkgName, null, true, allUsers, perUserInstalled, 9946 PackageManager.DELETE_KEEP_DATA, 9947 res.removedInfo, true); 9948 } 9949 // Since we failed to install the new package we need to restore the old 9950 // package that we deleted. 9951 if (deletedPkg) { 9952 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 9953 File restoreFile = new File(deletedPackage.codePath); 9954 // Parse old package 9955 boolean oldOnSd = isExternal(deletedPackage); 9956 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 9957 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 9958 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 9959 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 9960 | SCAN_UPDATE_TIME; 9961 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 9962 origUpdateTime, null, null) == null) { 9963 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 9964 return; 9965 } 9966 // Restore of old package succeeded. Update permissions. 9967 // writer 9968 synchronized (mPackages) { 9969 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 9970 UPDATE_PERMISSIONS_ALL); 9971 // can downgrade to reader 9972 mSettings.writeLPr(); 9973 } 9974 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 9975 } 9976 } 9977 } 9978 9979 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 9980 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9981 int[] allUsers, boolean[] perUserInstalled, 9982 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9983 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 9984 + ", old=" + deletedPackage); 9985 PackageParser.Package newPackage = null; 9986 boolean updatedSettings = false; 9987 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 9988 PackageParser.PARSE_IS_SYSTEM; 9989 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 9990 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9991 } 9992 String packageName = deletedPackage.packageName; 9993 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9994 if (packageName == null) { 9995 Slog.w(TAG, "Attempt to delete null packageName."); 9996 return; 9997 } 9998 PackageParser.Package oldPkg; 9999 PackageSetting oldPkgSetting; 10000 // reader 10001 synchronized (mPackages) { 10002 oldPkg = mPackages.get(packageName); 10003 oldPkgSetting = mSettings.mPackages.get(packageName); 10004 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10005 (oldPkgSetting == null)) { 10006 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 10007 return; 10008 } 10009 } 10010 10011 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10012 10013 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10014 res.removedInfo.removedPackage = packageName; 10015 // Remove existing system package 10016 removePackageLI(oldPkgSetting, true); 10017 // writer 10018 synchronized (mPackages) { 10019 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10020 // We didn't need to disable the .apk as a current system package, 10021 // which means we are replacing another update that is already 10022 // installed. We need to make sure to delete the older one's .apk. 10023 res.removedInfo.args = createInstallArgsForExisting(0, 10024 deletedPackage.applicationInfo.getCodePath(), 10025 deletedPackage.applicationInfo.getResourcePath(), 10026 deletedPackage.applicationInfo.nativeLibraryDir, 10027 getAppInstructionSet(deletedPackage.applicationInfo)); 10028 } else { 10029 res.removedInfo.args = null; 10030 } 10031 } 10032 10033 // Successfully disabled the old package. Now proceed with re-installation 10034 res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED; 10035 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10036 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride); 10037 if (newPackage == null) { 10038 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 10039 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 10040 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 10041 } 10042 } else { 10043 if (newPackage.mExtras != null) { 10044 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 10045 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10046 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10047 10048 // is the update attempting to change shared user? that isn't going to work... 10049 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10050 Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser 10051 + " to " + newPkgSetting.sharedUser); 10052 res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 10053 updatedSettings = true; 10054 } 10055 } 10056 10057 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10058 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10059 updatedSettings = true; 10060 } 10061 } 10062 10063 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10064 // Re installation failed. Restore old information 10065 // Remove new pkg information 10066 if (newPackage != null) { 10067 removeInstalledPackageLI(newPackage, true); 10068 } 10069 // Add back the old system package 10070 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null); 10071 // Restore the old system information in Settings 10072 synchronized(mPackages) { 10073 if (updatedSettings) { 10074 mSettings.enableSystemPackageLPw(packageName); 10075 mSettings.setInstallerPackageName(packageName, 10076 oldPkgSetting.installerPackageName); 10077 } 10078 mSettings.writeLPr(); 10079 } 10080 } 10081 } 10082 10083 // Utility method used to move dex files during install. 10084 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10085 // TODO: extend to move split APK dex files 10086 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10087 final String instructionSet = getAppInstructionSet(newPackage.applicationInfo); 10088 int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath, 10089 instructionSet); 10090 if (retCode != 0) { 10091 /* 10092 * Programs may be lazily run through dexopt, so the 10093 * source may not exist. However, something seems to 10094 * have gone wrong, so note that dexopt needs to be 10095 * run again and remove the source file. In addition, 10096 * remove the target to make sure there isn't a stale 10097 * file from a previous version of the package. 10098 */ 10099 newPackage.mDexOptNeeded = true; 10100 mInstaller.rmdex(oldCodePath, instructionSet); 10101 mInstaller.rmdex(newPackage.baseCodePath, instructionSet); 10102 } 10103 } 10104 return PackageManager.INSTALL_SUCCEEDED; 10105 } 10106 10107 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10108 int[] allUsers, boolean[] perUserInstalled, 10109 PackageInstalledInfo res) { 10110 String pkgName = newPackage.packageName; 10111 synchronized (mPackages) { 10112 //write settings. the installStatus will be incomplete at this stage. 10113 //note that the new package setting would have already been 10114 //added to mPackages. It hasn't been persisted yet. 10115 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10116 mSettings.writeLPr(); 10117 } 10118 10119 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10120 10121 synchronized (mPackages) { 10122 updatePermissionsLPw(newPackage.packageName, newPackage, 10123 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10124 ? UPDATE_PERMISSIONS_ALL : 0)); 10125 // For system-bundled packages, we assume that installing an upgraded version 10126 // of the package implies that the user actually wants to run that new code, 10127 // so we enable the package. 10128 if (isSystemApp(newPackage)) { 10129 // NB: implicit assumption that system package upgrades apply to all users 10130 if (DEBUG_INSTALL) { 10131 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10132 } 10133 PackageSetting ps = mSettings.mPackages.get(pkgName); 10134 if (ps != null) { 10135 if (res.origUsers != null) { 10136 for (int userHandle : res.origUsers) { 10137 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10138 userHandle, installerPackageName); 10139 } 10140 } 10141 // Also convey the prior install/uninstall state 10142 if (allUsers != null && perUserInstalled != null) { 10143 for (int i = 0; i < allUsers.length; i++) { 10144 if (DEBUG_INSTALL) { 10145 Slog.d(TAG, " user " + allUsers[i] 10146 + " => " + perUserInstalled[i]); 10147 } 10148 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10149 } 10150 // these install state changes will be persisted in the 10151 // upcoming call to mSettings.writeLPr(). 10152 } 10153 } 10154 } 10155 res.name = pkgName; 10156 res.uid = newPackage.applicationInfo.uid; 10157 res.pkg = newPackage; 10158 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10159 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10160 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10161 //to update install status 10162 mSettings.writeLPr(); 10163 } 10164 } 10165 10166 private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) { 10167 int pFlags = args.flags; 10168 String installerPackageName = args.installerPackageName; 10169 File tmpPackageFile = new File(args.getCodePath()); 10170 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10171 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10172 boolean replace = false; 10173 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10174 | (newInstall ? SCAN_NEW_INSTALL : 0); 10175 // Result object to be returned 10176 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10177 10178 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10179 // Retrieve PackageSettings and parse package 10180 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10181 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10182 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10183 PackageParser pp = new PackageParser(); 10184 pp.setSeparateProcesses(mSeparateProcesses); 10185 pp.setDisplayMetrics(mMetrics); 10186 10187 final PackageParser.Package pkg; 10188 try { 10189 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10190 } catch (PackageParserException e) { 10191 res.returnCode = e.error; 10192 return; 10193 } 10194 10195 String pkgName = res.name = pkg.packageName; 10196 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10197 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10198 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 10199 return; 10200 } 10201 } 10202 10203 try { 10204 pp.collectCertificates(pkg, parseFlags); 10205 pp.collectManifestDigest(pkg); 10206 } catch (PackageParserException e) { 10207 res.returnCode = e.error; 10208 return; 10209 } 10210 10211 /* If the installer passed in a manifest digest, compare it now. */ 10212 if (args.manifestDigest != null) { 10213 if (DEBUG_INSTALL) { 10214 final String parsedManifest = pkg.manifestDigest == null ? "null" 10215 : pkg.manifestDigest.toString(); 10216 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10217 + parsedManifest); 10218 } 10219 10220 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10221 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 10222 return; 10223 } 10224 } else if (DEBUG_INSTALL) { 10225 final String parsedManifest = pkg.manifestDigest == null 10226 ? "null" : pkg.manifestDigest.toString(); 10227 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10228 } 10229 10230 // Get rid of all references to package scan path via parser. 10231 pp = null; 10232 String oldCodePath = null; 10233 boolean systemApp = false; 10234 synchronized (mPackages) { 10235 // Check whether the newly-scanned package wants to define an already-defined perm 10236 int N = pkg.permissions.size(); 10237 for (int i = N-1; i >= 0; i--) { 10238 PackageParser.Permission perm = pkg.permissions.get(i); 10239 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10240 if (bp != null) { 10241 // If the defining package is signed with our cert, it's okay. This 10242 // also includes the "updating the same package" case, of course. 10243 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10244 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10245 // If the owning package is the system itself, we log but allow 10246 // install to proceed; we fail the install on all other permission 10247 // redefinitions. 10248 if (!bp.sourcePackage.equals("android")) { 10249 Slog.w(TAG, "Package " + pkg.packageName 10250 + " attempting to redeclare permission " + perm.info.name 10251 + " already owned by " + bp.sourcePackage); 10252 res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 10253 res.origPermission = perm.info.name; 10254 res.origPackage = bp.sourcePackage; 10255 return; 10256 } else { 10257 Slog.w(TAG, "Package " + pkg.packageName 10258 + " attempting to redeclare system permission " 10259 + perm.info.name + "; ignoring new declaration"); 10260 pkg.permissions.remove(i); 10261 } 10262 } 10263 } 10264 } 10265 10266 // Check if installing already existing package 10267 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10268 String oldName = mSettings.mRenamedPackages.get(pkgName); 10269 if (pkg.mOriginalPackages != null 10270 && pkg.mOriginalPackages.contains(oldName) 10271 && mPackages.containsKey(oldName)) { 10272 // This package is derived from an original package, 10273 // and this device has been updating from that original 10274 // name. We must continue using the original name, so 10275 // rename the new package here. 10276 pkg.setPackageName(oldName); 10277 pkgName = pkg.packageName; 10278 replace = true; 10279 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10280 + oldName + " pkgName=" + pkgName); 10281 } else if (mPackages.containsKey(pkgName)) { 10282 // This package, under its official name, already exists 10283 // on the device; we should replace it. 10284 replace = true; 10285 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10286 } 10287 } 10288 PackageSetting ps = mSettings.mPackages.get(pkgName); 10289 if (ps != null) { 10290 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10291 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10292 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10293 systemApp = (ps.pkg.applicationInfo.flags & 10294 ApplicationInfo.FLAG_SYSTEM) != 0; 10295 } 10296 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10297 } 10298 } 10299 10300 if (systemApp && onSd) { 10301 // Disable updates to system apps on sdcard 10302 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 10303 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10304 return; 10305 } 10306 10307 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10308 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10309 return; 10310 } 10311 10312 if (replace) { 10313 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10314 installerPackageName, res, args.abiOverride); 10315 } else { 10316 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10317 installerPackageName, res, args.abiOverride); 10318 } 10319 synchronized (mPackages) { 10320 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10321 if (ps != null) { 10322 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10323 } 10324 } 10325 } 10326 10327 private static boolean isForwardLocked(PackageParser.Package pkg) { 10328 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10329 } 10330 10331 10332 private boolean isForwardLocked(PackageSetting ps) { 10333 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10334 } 10335 10336 private static boolean isExternal(PackageParser.Package pkg) { 10337 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10338 } 10339 10340 private static boolean isExternal(PackageSetting ps) { 10341 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10342 } 10343 10344 private static boolean isSystemApp(PackageParser.Package pkg) { 10345 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10346 } 10347 10348 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10349 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10350 } 10351 10352 private static boolean isSystemApp(ApplicationInfo info) { 10353 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10354 } 10355 10356 private static boolean isSystemApp(PackageSetting ps) { 10357 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10358 } 10359 10360 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10361 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10362 } 10363 10364 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10365 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10366 } 10367 10368 private int packageFlagsToInstallFlags(PackageSetting ps) { 10369 int installFlags = 0; 10370 if (isExternal(ps)) { 10371 installFlags |= PackageManager.INSTALL_EXTERNAL; 10372 } 10373 if (isForwardLocked(ps)) { 10374 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10375 } 10376 return installFlags; 10377 } 10378 10379 private void deleteTempPackageFiles() { 10380 final FilenameFilter filter = new FilenameFilter() { 10381 public boolean accept(File dir, String name) { 10382 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10383 } 10384 }; 10385 deleteTempPackageFilesInDirectory(mAppInstallDir, filter); 10386 deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter); 10387 } 10388 10389 private static final void deleteTempPackageFilesInDirectory(File directory, 10390 FilenameFilter filter) { 10391 final File[] files = directory.listFiles(filter); 10392 if (!ArrayUtils.isEmpty(files)) { 10393 for (File file : files) { 10394 if (file.isDirectory()) { 10395 FileUtils.deleteContents(file); 10396 file.delete(); 10397 } else if (file.isFile()) { 10398 file.delete(); 10399 } 10400 } 10401 } 10402 } 10403 10404 private File createTempPackageDir(File installDir) throws IOException { 10405 int n = 0; 10406 while (n++ < 32) { 10407 final File file = new File(installDir, "vmdl" + mTempFileRandom.nextInt() + ".tmp"); 10408 try { 10409 Os.mkdir(file.getAbsolutePath(), 0755); 10410 Os.chmod(file.getAbsolutePath(), 0755); 10411 if (!SELinux.restorecon(file)) { 10412 throw new IOException("Failed to restorecon"); 10413 } 10414 return file; 10415 } catch (ErrnoException e) { 10416 if (e.errno == EEXIST) continue; 10417 throw e.rethrowAsIOException(); 10418 } 10419 } 10420 throw new IOException("Failed to create temp directory"); 10421 } 10422 10423 private File createTempPackageFile(File installDir) throws IOException { 10424 int n = 0; 10425 while (n++ < 32) { 10426 final File file = new File(installDir, "vmdl" + mTempFileRandom.nextInt() + ".tmp"); 10427 try { 10428 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10429 O_RDWR | O_CREAT | O_EXCL, 0644); 10430 IoUtils.closeQuietly(fd); 10431 Os.chmod(file.getAbsolutePath(), 0644); 10432 if (!SELinux.restorecon(file)) { 10433 throw new IOException("Failed to restorecon"); 10434 } 10435 return file; 10436 } catch (ErrnoException e) { 10437 if (e.errno == EEXIST) continue; 10438 throw e.rethrowAsIOException(); 10439 } 10440 } 10441 throw new IOException("Failed to create temp file"); 10442 } 10443 10444 @Override 10445 public void deletePackageAsUser(final String packageName, 10446 final IPackageDeleteObserver observer, 10447 final int userId, final int flags) { 10448 mContext.enforceCallingOrSelfPermission( 10449 android.Manifest.permission.DELETE_PACKAGES, null); 10450 final int uid = Binder.getCallingUid(); 10451 if (UserHandle.getUserId(uid) != userId) { 10452 mContext.enforceCallingPermission( 10453 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10454 "deletePackage for user " + userId); 10455 } 10456 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10457 try { 10458 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 10459 } catch (RemoteException re) { 10460 } 10461 return; 10462 } 10463 10464 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10465 // Queue up an async operation since the package deletion may take a little while. 10466 mHandler.post(new Runnable() { 10467 public void run() { 10468 mHandler.removeCallbacks(this); 10469 final int returnCode = deletePackageX(packageName, userId, flags); 10470 if (observer != null) { 10471 try { 10472 observer.packageDeleted(packageName, returnCode); 10473 } catch (RemoteException e) { 10474 Log.i(TAG, "Observer no longer exists."); 10475 } //end catch 10476 } //end if 10477 } //end run 10478 }); 10479 } 10480 10481 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10482 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10483 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10484 try { 10485 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10486 || dpm.isDeviceOwner(packageName))) { 10487 return true; 10488 } 10489 } catch (RemoteException e) { 10490 } 10491 return false; 10492 } 10493 10494 /** 10495 * This method is an internal method that could be get invoked either 10496 * to delete an installed package or to clean up a failed installation. 10497 * After deleting an installed package, a broadcast is sent to notify any 10498 * listeners that the package has been installed. For cleaning up a failed 10499 * installation, the broadcast is not necessary since the package's 10500 * installation wouldn't have sent the initial broadcast either 10501 * The key steps in deleting a package are 10502 * deleting the package information in internal structures like mPackages, 10503 * deleting the packages base directories through installd 10504 * updating mSettings to reflect current status 10505 * persisting settings for later use 10506 * sending a broadcast if necessary 10507 */ 10508 private int deletePackageX(String packageName, int userId, int flags) { 10509 final PackageRemovedInfo info = new PackageRemovedInfo(); 10510 final boolean res; 10511 10512 if (isPackageDeviceAdmin(packageName, userId)) { 10513 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10514 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10515 } 10516 10517 boolean removedForAllUsers = false; 10518 boolean systemUpdate = false; 10519 10520 // for the uninstall-updates case and restricted profiles, remember the per- 10521 // userhandle installed state 10522 int[] allUsers; 10523 boolean[] perUserInstalled; 10524 synchronized (mPackages) { 10525 PackageSetting ps = mSettings.mPackages.get(packageName); 10526 allUsers = sUserManager.getUserIds(); 10527 perUserInstalled = new boolean[allUsers.length]; 10528 for (int i = 0; i < allUsers.length; i++) { 10529 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10530 } 10531 } 10532 10533 synchronized (mInstallLock) { 10534 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10535 res = deletePackageLI(packageName, 10536 (flags & PackageManager.DELETE_ALL_USERS) != 0 10537 ? UserHandle.ALL : new UserHandle(userId), 10538 true, allUsers, perUserInstalled, 10539 flags | REMOVE_CHATTY, info, true); 10540 systemUpdate = info.isRemovedPackageSystemUpdate; 10541 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10542 removedForAllUsers = true; 10543 } 10544 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10545 + " removedForAllUsers=" + removedForAllUsers); 10546 } 10547 10548 if (res) { 10549 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10550 10551 // If the removed package was a system update, the old system package 10552 // was re-enabled; we need to broadcast this information 10553 if (systemUpdate) { 10554 Bundle extras = new Bundle(1); 10555 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10556 ? info.removedAppId : info.uid); 10557 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10558 10559 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10560 extras, null, null, null); 10561 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10562 extras, null, null, null); 10563 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10564 null, packageName, null, null); 10565 } 10566 } 10567 // Force a gc here. 10568 Runtime.getRuntime().gc(); 10569 // Delete the resources here after sending the broadcast to let 10570 // other processes clean up before deleting resources. 10571 if (info.args != null) { 10572 synchronized (mInstallLock) { 10573 info.args.doPostDeleteLI(true); 10574 } 10575 } 10576 10577 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10578 } 10579 10580 static class PackageRemovedInfo { 10581 String removedPackage; 10582 int uid = -1; 10583 int removedAppId = -1; 10584 int[] removedUsers = null; 10585 boolean isRemovedPackageSystemUpdate = false; 10586 // Clean up resources deleted packages. 10587 InstallArgs args = null; 10588 10589 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10590 Bundle extras = new Bundle(1); 10591 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10592 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10593 if (replacing) { 10594 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10595 } 10596 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10597 if (removedPackage != null) { 10598 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10599 extras, null, null, removedUsers); 10600 if (fullRemove && !replacing) { 10601 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10602 extras, null, null, removedUsers); 10603 } 10604 } 10605 if (removedAppId >= 0) { 10606 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10607 removedUsers); 10608 } 10609 } 10610 } 10611 10612 /* 10613 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10614 * flag is not set, the data directory is removed as well. 10615 * make sure this flag is set for partially installed apps. If not its meaningless to 10616 * delete a partially installed application. 10617 */ 10618 private void removePackageDataLI(PackageSetting ps, 10619 int[] allUserHandles, boolean[] perUserInstalled, 10620 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10621 String packageName = ps.name; 10622 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10623 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10624 // Retrieve object to delete permissions for shared user later on 10625 final PackageSetting deletedPs; 10626 // reader 10627 synchronized (mPackages) { 10628 deletedPs = mSettings.mPackages.get(packageName); 10629 if (outInfo != null) { 10630 outInfo.removedPackage = packageName; 10631 outInfo.removedUsers = deletedPs != null 10632 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10633 : null; 10634 } 10635 } 10636 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10637 removeDataDirsLI(packageName); 10638 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10639 } 10640 // writer 10641 synchronized (mPackages) { 10642 if (deletedPs != null) { 10643 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10644 if (outInfo != null) { 10645 mSettings.mKeySetManagerService.removeAppKeySetData(packageName); 10646 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10647 } 10648 if (deletedPs != null) { 10649 updatePermissionsLPw(deletedPs.name, null, 0); 10650 if (deletedPs.sharedUser != null) { 10651 // remove permissions associated with package 10652 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10653 } 10654 } 10655 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10656 } 10657 // make sure to preserve per-user disabled state if this removal was just 10658 // a downgrade of a system app to the factory package 10659 if (allUserHandles != null && perUserInstalled != null) { 10660 if (DEBUG_REMOVE) { 10661 Slog.d(TAG, "Propagating install state across downgrade"); 10662 } 10663 for (int i = 0; i < allUserHandles.length; i++) { 10664 if (DEBUG_REMOVE) { 10665 Slog.d(TAG, " user " + allUserHandles[i] 10666 + " => " + perUserInstalled[i]); 10667 } 10668 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10669 } 10670 } 10671 } 10672 // can downgrade to reader 10673 if (writeSettings) { 10674 // Save settings now 10675 mSettings.writeLPr(); 10676 } 10677 } 10678 if (outInfo != null) { 10679 // A user ID was deleted here. Go through all users and remove it 10680 // from KeyStore. 10681 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10682 } 10683 } 10684 10685 static boolean locationIsPrivileged(File path) { 10686 try { 10687 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10688 .getCanonicalPath(); 10689 return path.getCanonicalPath().startsWith(privilegedAppDir); 10690 } catch (IOException e) { 10691 Slog.e(TAG, "Unable to access code path " + path); 10692 } 10693 return false; 10694 } 10695 10696 /* 10697 * Tries to delete system package. 10698 */ 10699 private boolean deleteSystemPackageLI(PackageSetting newPs, 10700 int[] allUserHandles, boolean[] perUserInstalled, 10701 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10702 final boolean applyUserRestrictions 10703 = (allUserHandles != null) && (perUserInstalled != null); 10704 PackageSetting disabledPs = null; 10705 // Confirm if the system package has been updated 10706 // An updated system app can be deleted. This will also have to restore 10707 // the system pkg from system partition 10708 // reader 10709 synchronized (mPackages) { 10710 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10711 } 10712 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10713 + " disabledPs=" + disabledPs); 10714 if (disabledPs == null) { 10715 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10716 return false; 10717 } else if (DEBUG_REMOVE) { 10718 Slog.d(TAG, "Deleting system pkg from data partition"); 10719 } 10720 if (DEBUG_REMOVE) { 10721 if (applyUserRestrictions) { 10722 Slog.d(TAG, "Remembering install states:"); 10723 for (int i = 0; i < allUserHandles.length; i++) { 10724 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10725 } 10726 } 10727 } 10728 // Delete the updated package 10729 outInfo.isRemovedPackageSystemUpdate = true; 10730 if (disabledPs.versionCode < newPs.versionCode) { 10731 // Delete data for downgrades 10732 flags &= ~PackageManager.DELETE_KEEP_DATA; 10733 } else { 10734 // Preserve data by setting flag 10735 flags |= PackageManager.DELETE_KEEP_DATA; 10736 } 10737 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10738 allUserHandles, perUserInstalled, outInfo, writeSettings); 10739 if (!ret) { 10740 return false; 10741 } 10742 // writer 10743 synchronized (mPackages) { 10744 // Reinstate the old system package 10745 mSettings.enableSystemPackageLPw(newPs.name); 10746 // Remove any native libraries from the upgraded package. 10747 NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString); 10748 } 10749 // Install the system package 10750 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10751 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10752 if (locationIsPrivileged(disabledPs.codePath)) { 10753 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10754 } 10755 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath, 10756 parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null); 10757 10758 if (newPkg == null) { 10759 Slog.w(TAG, "Failed to restore system package:" + newPs.name 10760 + " with error:" + mLastScanError); 10761 return false; 10762 } 10763 // writer 10764 synchronized (mPackages) { 10765 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10766 setInternalAppNativeLibraryPath(newPkg, ps); 10767 updatePermissionsLPw(newPkg.packageName, newPkg, 10768 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10769 if (applyUserRestrictions) { 10770 if (DEBUG_REMOVE) { 10771 Slog.d(TAG, "Propagating install state across reinstall"); 10772 } 10773 for (int i = 0; i < allUserHandles.length; i++) { 10774 if (DEBUG_REMOVE) { 10775 Slog.d(TAG, " user " + allUserHandles[i] 10776 + " => " + perUserInstalled[i]); 10777 } 10778 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10779 } 10780 // Regardless of writeSettings we need to ensure that this restriction 10781 // state propagation is persisted 10782 mSettings.writeAllUsersPackageRestrictionsLPr(); 10783 } 10784 // can downgrade to reader here 10785 if (writeSettings) { 10786 mSettings.writeLPr(); 10787 } 10788 } 10789 return true; 10790 } 10791 10792 private boolean deleteInstalledPackageLI(PackageSetting ps, 10793 boolean deleteCodeAndResources, int flags, 10794 int[] allUserHandles, boolean[] perUserInstalled, 10795 PackageRemovedInfo outInfo, boolean writeSettings) { 10796 if (outInfo != null) { 10797 outInfo.uid = ps.appId; 10798 } 10799 10800 // Delete package data from internal structures and also remove data if flag is set 10801 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10802 10803 // Delete application code and resources 10804 if (deleteCodeAndResources && (outInfo != null)) { 10805 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10806 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 10807 getAppInstructionSetFromSettings(ps)); 10808 } 10809 return true; 10810 } 10811 10812 @Override 10813 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10814 int userId) { 10815 mContext.enforceCallingOrSelfPermission( 10816 android.Manifest.permission.DELETE_PACKAGES, null); 10817 synchronized (mPackages) { 10818 PackageSetting ps = mSettings.mPackages.get(packageName); 10819 if (ps == null) { 10820 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10821 return false; 10822 } 10823 if (!ps.getInstalled(userId)) { 10824 // Can't block uninstall for an app that is not installed or enabled. 10825 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10826 return false; 10827 } 10828 ps.setBlockUninstall(blockUninstall, userId); 10829 mSettings.writePackageRestrictionsLPr(userId); 10830 } 10831 return true; 10832 } 10833 10834 @Override 10835 public boolean getBlockUninstallForUser(String packageName, int userId) { 10836 synchronized (mPackages) { 10837 PackageSetting ps = mSettings.mPackages.get(packageName); 10838 if (ps == null) { 10839 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10840 return false; 10841 } 10842 return ps.getBlockUninstall(userId); 10843 } 10844 } 10845 10846 /* 10847 * This method handles package deletion in general 10848 */ 10849 private boolean deletePackageLI(String packageName, UserHandle user, 10850 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10851 int flags, PackageRemovedInfo outInfo, 10852 boolean writeSettings) { 10853 if (packageName == null) { 10854 Slog.w(TAG, "Attempt to delete null packageName."); 10855 return false; 10856 } 10857 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10858 PackageSetting ps; 10859 boolean dataOnly = false; 10860 int removeUser = -1; 10861 int appId = -1; 10862 synchronized (mPackages) { 10863 ps = mSettings.mPackages.get(packageName); 10864 if (ps == null) { 10865 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10866 return false; 10867 } 10868 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10869 && user.getIdentifier() != UserHandle.USER_ALL) { 10870 // The caller is asking that the package only be deleted for a single 10871 // user. To do this, we just mark its uninstalled state and delete 10872 // its data. If this is a system app, we only allow this to happen if 10873 // they have set the special DELETE_SYSTEM_APP which requests different 10874 // semantics than normal for uninstalling system apps. 10875 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10876 ps.setUserState(user.getIdentifier(), 10877 COMPONENT_ENABLED_STATE_DEFAULT, 10878 false, //installed 10879 true, //stopped 10880 true, //notLaunched 10881 false, //blocked 10882 null, null, null, 10883 false // blockUninstall 10884 ); 10885 if (!isSystemApp(ps)) { 10886 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10887 // Other user still have this package installed, so all 10888 // we need to do is clear this user's data and save that 10889 // it is uninstalled. 10890 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10891 removeUser = user.getIdentifier(); 10892 appId = ps.appId; 10893 mSettings.writePackageRestrictionsLPr(removeUser); 10894 } else { 10895 // We need to set it back to 'installed' so the uninstall 10896 // broadcasts will be sent correctly. 10897 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10898 ps.setInstalled(true, user.getIdentifier()); 10899 } 10900 } else { 10901 // This is a system app, so we assume that the 10902 // other users still have this package installed, so all 10903 // we need to do is clear this user's data and save that 10904 // it is uninstalled. 10905 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10906 removeUser = user.getIdentifier(); 10907 appId = ps.appId; 10908 mSettings.writePackageRestrictionsLPr(removeUser); 10909 } 10910 } 10911 } 10912 10913 if (removeUser >= 0) { 10914 // From above, we determined that we are deleting this only 10915 // for a single user. Continue the work here. 10916 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10917 if (outInfo != null) { 10918 outInfo.removedPackage = packageName; 10919 outInfo.removedAppId = appId; 10920 outInfo.removedUsers = new int[] {removeUser}; 10921 } 10922 mInstaller.clearUserData(packageName, removeUser); 10923 removeKeystoreDataIfNeeded(removeUser, appId); 10924 schedulePackageCleaning(packageName, removeUser, false); 10925 return true; 10926 } 10927 10928 if (dataOnly) { 10929 // Delete application data first 10930 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10931 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10932 return true; 10933 } 10934 10935 boolean ret = false; 10936 if (isSystemApp(ps)) { 10937 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10938 // When an updated system application is deleted we delete the existing resources as well and 10939 // fall back to existing code in system partition 10940 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10941 flags, outInfo, writeSettings); 10942 } else { 10943 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10944 // Kill application pre-emptively especially for apps on sd. 10945 killApplication(packageName, ps.appId, "uninstall pkg"); 10946 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10947 allUserHandles, perUserInstalled, 10948 outInfo, writeSettings); 10949 } 10950 10951 return ret; 10952 } 10953 10954 private final class ClearStorageConnection implements ServiceConnection { 10955 IMediaContainerService mContainerService; 10956 10957 @Override 10958 public void onServiceConnected(ComponentName name, IBinder service) { 10959 synchronized (this) { 10960 mContainerService = IMediaContainerService.Stub.asInterface(service); 10961 notifyAll(); 10962 } 10963 } 10964 10965 @Override 10966 public void onServiceDisconnected(ComponentName name) { 10967 } 10968 } 10969 10970 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10971 final boolean mounted; 10972 if (Environment.isExternalStorageEmulated()) { 10973 mounted = true; 10974 } else { 10975 final String status = Environment.getExternalStorageState(); 10976 10977 mounted = status.equals(Environment.MEDIA_MOUNTED) 10978 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 10979 } 10980 10981 if (!mounted) { 10982 return; 10983 } 10984 10985 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 10986 int[] users; 10987 if (userId == UserHandle.USER_ALL) { 10988 users = sUserManager.getUserIds(); 10989 } else { 10990 users = new int[] { userId }; 10991 } 10992 final ClearStorageConnection conn = new ClearStorageConnection(); 10993 if (mContext.bindServiceAsUser( 10994 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 10995 try { 10996 for (int curUser : users) { 10997 long timeout = SystemClock.uptimeMillis() + 5000; 10998 synchronized (conn) { 10999 long now = SystemClock.uptimeMillis(); 11000 while (conn.mContainerService == null && now < timeout) { 11001 try { 11002 conn.wait(timeout - now); 11003 } catch (InterruptedException e) { 11004 } 11005 } 11006 } 11007 if (conn.mContainerService == null) { 11008 return; 11009 } 11010 11011 final UserEnvironment userEnv = new UserEnvironment(curUser); 11012 clearDirectory(conn.mContainerService, 11013 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11014 if (allData) { 11015 clearDirectory(conn.mContainerService, 11016 userEnv.buildExternalStorageAppDataDirs(packageName)); 11017 clearDirectory(conn.mContainerService, 11018 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11019 } 11020 } 11021 } finally { 11022 mContext.unbindService(conn); 11023 } 11024 } 11025 } 11026 11027 @Override 11028 public void clearApplicationUserData(final String packageName, 11029 final IPackageDataObserver observer, final int userId) { 11030 mContext.enforceCallingOrSelfPermission( 11031 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11032 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11033 // Queue up an async operation since the package deletion may take a little while. 11034 mHandler.post(new Runnable() { 11035 public void run() { 11036 mHandler.removeCallbacks(this); 11037 final boolean succeeded; 11038 synchronized (mInstallLock) { 11039 succeeded = clearApplicationUserDataLI(packageName, userId); 11040 } 11041 clearExternalStorageDataSync(packageName, userId, true); 11042 if (succeeded) { 11043 // invoke DeviceStorageMonitor's update method to clear any notifications 11044 DeviceStorageMonitorInternal 11045 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11046 if (dsm != null) { 11047 dsm.checkMemory(); 11048 } 11049 } 11050 if(observer != null) { 11051 try { 11052 observer.onRemoveCompleted(packageName, succeeded); 11053 } catch (RemoteException e) { 11054 Log.i(TAG, "Observer no longer exists."); 11055 } 11056 } //end if observer 11057 } //end run 11058 }); 11059 } 11060 11061 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11062 if (packageName == null) { 11063 Slog.w(TAG, "Attempt to delete null packageName."); 11064 return false; 11065 } 11066 PackageParser.Package p; 11067 boolean dataOnly = false; 11068 final int appId; 11069 synchronized (mPackages) { 11070 p = mPackages.get(packageName); 11071 if (p == null) { 11072 dataOnly = true; 11073 PackageSetting ps = mSettings.mPackages.get(packageName); 11074 if ((ps == null) || (ps.pkg == null)) { 11075 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11076 return false; 11077 } 11078 p = ps.pkg; 11079 } 11080 if (!dataOnly) { 11081 // need to check this only for fully installed applications 11082 if (p == null) { 11083 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11084 return false; 11085 } 11086 final ApplicationInfo applicationInfo = p.applicationInfo; 11087 if (applicationInfo == null) { 11088 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11089 return false; 11090 } 11091 } 11092 if (p != null && p.applicationInfo != null) { 11093 appId = p.applicationInfo.uid; 11094 } else { 11095 appId = -1; 11096 } 11097 } 11098 int retCode = mInstaller.clearUserData(packageName, userId); 11099 if (retCode < 0) { 11100 Slog.w(TAG, "Couldn't remove cache files for package: " 11101 + packageName); 11102 return false; 11103 } 11104 removeKeystoreDataIfNeeded(userId, appId); 11105 return true; 11106 } 11107 11108 /** 11109 * Remove entries from the keystore daemon. Will only remove it if the 11110 * {@code appId} is valid. 11111 */ 11112 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11113 if (appId < 0) { 11114 return; 11115 } 11116 11117 final KeyStore keyStore = KeyStore.getInstance(); 11118 if (keyStore != null) { 11119 if (userId == UserHandle.USER_ALL) { 11120 for (final int individual : sUserManager.getUserIds()) { 11121 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11122 } 11123 } else { 11124 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11125 } 11126 } else { 11127 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11128 } 11129 } 11130 11131 @Override 11132 public void deleteApplicationCacheFiles(final String packageName, 11133 final IPackageDataObserver observer) { 11134 mContext.enforceCallingOrSelfPermission( 11135 android.Manifest.permission.DELETE_CACHE_FILES, null); 11136 // Queue up an async operation since the package deletion may take a little while. 11137 final int userId = UserHandle.getCallingUserId(); 11138 mHandler.post(new Runnable() { 11139 public void run() { 11140 mHandler.removeCallbacks(this); 11141 final boolean succeded; 11142 synchronized (mInstallLock) { 11143 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11144 } 11145 clearExternalStorageDataSync(packageName, userId, false); 11146 if(observer != null) { 11147 try { 11148 observer.onRemoveCompleted(packageName, succeded); 11149 } catch (RemoteException e) { 11150 Log.i(TAG, "Observer no longer exists."); 11151 } 11152 } //end if observer 11153 } //end run 11154 }); 11155 } 11156 11157 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11158 if (packageName == null) { 11159 Slog.w(TAG, "Attempt to delete null packageName."); 11160 return false; 11161 } 11162 PackageParser.Package p; 11163 synchronized (mPackages) { 11164 p = mPackages.get(packageName); 11165 } 11166 if (p == null) { 11167 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11168 return false; 11169 } 11170 final ApplicationInfo applicationInfo = p.applicationInfo; 11171 if (applicationInfo == null) { 11172 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11173 return false; 11174 } 11175 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11176 if (retCode < 0) { 11177 Slog.w(TAG, "Couldn't remove cache files for package: " 11178 + packageName + " u" + userId); 11179 return false; 11180 } 11181 return true; 11182 } 11183 11184 @Override 11185 public void getPackageSizeInfo(final String packageName, int userHandle, 11186 final IPackageStatsObserver observer) { 11187 mContext.enforceCallingOrSelfPermission( 11188 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11189 if (packageName == null) { 11190 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11191 } 11192 11193 PackageStats stats = new PackageStats(packageName, userHandle); 11194 11195 /* 11196 * Queue up an async operation since the package measurement may take a 11197 * little while. 11198 */ 11199 Message msg = mHandler.obtainMessage(INIT_COPY); 11200 msg.obj = new MeasureParams(stats, observer); 11201 mHandler.sendMessage(msg); 11202 } 11203 11204 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11205 PackageStats pStats) { 11206 if (packageName == null) { 11207 Slog.w(TAG, "Attempt to get size of null packageName."); 11208 return false; 11209 } 11210 PackageParser.Package p; 11211 boolean dataOnly = false; 11212 String libDirPath = null; 11213 String asecPath = null; 11214 PackageSetting ps = null; 11215 synchronized (mPackages) { 11216 p = mPackages.get(packageName); 11217 ps = mSettings.mPackages.get(packageName); 11218 if(p == null) { 11219 dataOnly = true; 11220 if((ps == null) || (ps.pkg == null)) { 11221 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11222 return false; 11223 } 11224 p = ps.pkg; 11225 } 11226 if (ps != null) { 11227 libDirPath = ps.nativeLibraryPathString; 11228 } 11229 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11230 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11231 if (secureContainerId != null) { 11232 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11233 } 11234 } 11235 } 11236 String publicSrcDir = null; 11237 if(!dataOnly) { 11238 final ApplicationInfo applicationInfo = p.applicationInfo; 11239 if (applicationInfo == null) { 11240 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11241 return false; 11242 } 11243 if (isForwardLocked(p)) { 11244 publicSrcDir = applicationInfo.getBaseResourcePath(); 11245 } 11246 } 11247 // TODO: extend to measure size of split APKs 11248 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirPath, 11249 publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps), 11250 pStats); 11251 if (res < 0) { 11252 return false; 11253 } 11254 11255 // Fix-up for forward-locked applications in ASEC containers. 11256 if (!isExternal(p)) { 11257 pStats.codeSize += pStats.externalCodeSize; 11258 pStats.externalCodeSize = 0L; 11259 } 11260 11261 return true; 11262 } 11263 11264 11265 @Override 11266 public void addPackageToPreferred(String packageName) { 11267 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11268 } 11269 11270 @Override 11271 public void removePackageFromPreferred(String packageName) { 11272 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11273 } 11274 11275 @Override 11276 public List<PackageInfo> getPreferredPackages(int flags) { 11277 return new ArrayList<PackageInfo>(); 11278 } 11279 11280 private int getUidTargetSdkVersionLockedLPr(int uid) { 11281 Object obj = mSettings.getUserIdLPr(uid); 11282 if (obj instanceof SharedUserSetting) { 11283 final SharedUserSetting sus = (SharedUserSetting) obj; 11284 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11285 final Iterator<PackageSetting> it = sus.packages.iterator(); 11286 while (it.hasNext()) { 11287 final PackageSetting ps = it.next(); 11288 if (ps.pkg != null) { 11289 int v = ps.pkg.applicationInfo.targetSdkVersion; 11290 if (v < vers) vers = v; 11291 } 11292 } 11293 return vers; 11294 } else if (obj instanceof PackageSetting) { 11295 final PackageSetting ps = (PackageSetting) obj; 11296 if (ps.pkg != null) { 11297 return ps.pkg.applicationInfo.targetSdkVersion; 11298 } 11299 } 11300 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11301 } 11302 11303 @Override 11304 public void addPreferredActivity(IntentFilter filter, int match, 11305 ComponentName[] set, ComponentName activity, int userId) { 11306 addPreferredActivityInternal(filter, match, set, activity, true, userId); 11307 } 11308 11309 private void addPreferredActivityInternal(IntentFilter filter, int match, 11310 ComponentName[] set, ComponentName activity, boolean always, int userId) { 11311 // writer 11312 int callingUid = Binder.getCallingUid(); 11313 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11314 if (filter.countActions() == 0) { 11315 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11316 return; 11317 } 11318 synchronized (mPackages) { 11319 if (mContext.checkCallingOrSelfPermission( 11320 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11321 != PackageManager.PERMISSION_GRANTED) { 11322 if (getUidTargetSdkVersionLockedLPr(callingUid) 11323 < Build.VERSION_CODES.FROYO) { 11324 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11325 + callingUid); 11326 return; 11327 } 11328 mContext.enforceCallingOrSelfPermission( 11329 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11330 } 11331 11332 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 11333 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11334 mSettings.editPreferredActivitiesLPw(userId).addFilter( 11335 new PreferredActivity(filter, match, set, activity, always)); 11336 mSettings.writePackageRestrictionsLPr(userId); 11337 } 11338 } 11339 11340 @Override 11341 public void replacePreferredActivity(IntentFilter filter, int match, 11342 ComponentName[] set, ComponentName activity) { 11343 if (filter.countActions() != 1) { 11344 throw new IllegalArgumentException( 11345 "replacePreferredActivity expects filter to have only 1 action."); 11346 } 11347 if (filter.countDataAuthorities() != 0 11348 || filter.countDataPaths() != 0 11349 || filter.countDataSchemes() > 1 11350 || filter.countDataTypes() != 0) { 11351 throw new IllegalArgumentException( 11352 "replacePreferredActivity expects filter to have no data authorities, " + 11353 "paths, or types; and at most one scheme."); 11354 } 11355 synchronized (mPackages) { 11356 if (mContext.checkCallingOrSelfPermission( 11357 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11358 != PackageManager.PERMISSION_GRANTED) { 11359 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11360 < Build.VERSION_CODES.FROYO) { 11361 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11362 + Binder.getCallingUid()); 11363 return; 11364 } 11365 mContext.enforceCallingOrSelfPermission( 11366 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11367 } 11368 11369 final int callingUserId = UserHandle.getCallingUserId(); 11370 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 11371 if (pir != null) { 11372 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 11373 if (filter.countDataSchemes() == 1) { 11374 Uri.Builder builder = new Uri.Builder(); 11375 builder.scheme(filter.getDataScheme(0)); 11376 intent.setData(builder.build()); 11377 } 11378 List<PreferredActivity> matches = pir.queryIntent( 11379 intent, null, true, callingUserId); 11380 if (DEBUG_PREFERRED) { 11381 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 11382 } 11383 for (int i = 0; i < matches.size(); i++) { 11384 PreferredActivity pa = matches.get(i); 11385 if (DEBUG_PREFERRED) { 11386 Slog.i(TAG, "Removing preferred activity " 11387 + pa.mPref.mComponent + ":"); 11388 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11389 } 11390 pir.removeFilter(pa); 11391 } 11392 } 11393 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 11394 } 11395 } 11396 11397 @Override 11398 public void clearPackagePreferredActivities(String packageName) { 11399 final int uid = Binder.getCallingUid(); 11400 // writer 11401 synchronized (mPackages) { 11402 PackageParser.Package pkg = mPackages.get(packageName); 11403 if (pkg == null || pkg.applicationInfo.uid != uid) { 11404 if (mContext.checkCallingOrSelfPermission( 11405 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11406 != PackageManager.PERMISSION_GRANTED) { 11407 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11408 < Build.VERSION_CODES.FROYO) { 11409 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11410 + Binder.getCallingUid()); 11411 return; 11412 } 11413 mContext.enforceCallingOrSelfPermission( 11414 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11415 } 11416 } 11417 11418 int user = UserHandle.getCallingUserId(); 11419 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11420 mSettings.writePackageRestrictionsLPr(user); 11421 scheduleWriteSettingsLocked(); 11422 } 11423 } 11424 } 11425 11426 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11427 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11428 ArrayList<PreferredActivity> removed = null; 11429 boolean changed = false; 11430 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11431 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11432 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11433 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11434 continue; 11435 } 11436 Iterator<PreferredActivity> it = pir.filterIterator(); 11437 while (it.hasNext()) { 11438 PreferredActivity pa = it.next(); 11439 // Mark entry for removal only if it matches the package name 11440 // and the entry is of type "always". 11441 if (packageName == null || 11442 (pa.mPref.mComponent.getPackageName().equals(packageName) 11443 && pa.mPref.mAlways)) { 11444 if (removed == null) { 11445 removed = new ArrayList<PreferredActivity>(); 11446 } 11447 removed.add(pa); 11448 } 11449 } 11450 if (removed != null) { 11451 for (int j=0; j<removed.size(); j++) { 11452 PreferredActivity pa = removed.get(j); 11453 pir.removeFilter(pa); 11454 } 11455 changed = true; 11456 } 11457 } 11458 return changed; 11459 } 11460 11461 @Override 11462 public void resetPreferredActivities(int userId) { 11463 mContext.enforceCallingOrSelfPermission( 11464 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11465 // writer 11466 synchronized (mPackages) { 11467 int user = UserHandle.getCallingUserId(); 11468 clearPackagePreferredActivitiesLPw(null, user); 11469 mSettings.readDefaultPreferredAppsLPw(this, user); 11470 mSettings.writePackageRestrictionsLPr(user); 11471 scheduleWriteSettingsLocked(); 11472 } 11473 } 11474 11475 @Override 11476 public int getPreferredActivities(List<IntentFilter> outFilters, 11477 List<ComponentName> outActivities, String packageName) { 11478 11479 int num = 0; 11480 final int userId = UserHandle.getCallingUserId(); 11481 // reader 11482 synchronized (mPackages) { 11483 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11484 if (pir != null) { 11485 final Iterator<PreferredActivity> it = pir.filterIterator(); 11486 while (it.hasNext()) { 11487 final PreferredActivity pa = it.next(); 11488 if (packageName == null 11489 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11490 && pa.mPref.mAlways)) { 11491 if (outFilters != null) { 11492 outFilters.add(new IntentFilter(pa)); 11493 } 11494 if (outActivities != null) { 11495 outActivities.add(pa.mPref.mComponent); 11496 } 11497 } 11498 } 11499 } 11500 } 11501 11502 return num; 11503 } 11504 11505 @Override 11506 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11507 int userId) { 11508 int callingUid = Binder.getCallingUid(); 11509 if (callingUid != Process.SYSTEM_UID) { 11510 throw new SecurityException( 11511 "addPersistentPreferredActivity can only be run by the system"); 11512 } 11513 if (filter.countActions() == 0) { 11514 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11515 return; 11516 } 11517 synchronized (mPackages) { 11518 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11519 " :"); 11520 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11521 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11522 new PersistentPreferredActivity(filter, activity)); 11523 mSettings.writePackageRestrictionsLPr(userId); 11524 } 11525 } 11526 11527 @Override 11528 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11529 int callingUid = Binder.getCallingUid(); 11530 if (callingUid != Process.SYSTEM_UID) { 11531 throw new SecurityException( 11532 "clearPackagePersistentPreferredActivities can only be run by the system"); 11533 } 11534 ArrayList<PersistentPreferredActivity> removed = null; 11535 boolean changed = false; 11536 synchronized (mPackages) { 11537 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11538 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11539 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11540 .valueAt(i); 11541 if (userId != thisUserId) { 11542 continue; 11543 } 11544 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11545 while (it.hasNext()) { 11546 PersistentPreferredActivity ppa = it.next(); 11547 // Mark entry for removal only if it matches the package name. 11548 if (ppa.mComponent.getPackageName().equals(packageName)) { 11549 if (removed == null) { 11550 removed = new ArrayList<PersistentPreferredActivity>(); 11551 } 11552 removed.add(ppa); 11553 } 11554 } 11555 if (removed != null) { 11556 for (int j=0; j<removed.size(); j++) { 11557 PersistentPreferredActivity ppa = removed.get(j); 11558 ppir.removeFilter(ppa); 11559 } 11560 changed = true; 11561 } 11562 } 11563 11564 if (changed) { 11565 mSettings.writePackageRestrictionsLPr(userId); 11566 } 11567 } 11568 } 11569 11570 @Override 11571 public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId, 11572 int targetUserId, int flags) { 11573 mContext.enforceCallingOrSelfPermission( 11574 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11575 if (intentFilter.countActions() == 0) { 11576 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11577 return; 11578 } 11579 synchronized (mPackages) { 11580 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11581 targetUserId, flags); 11582 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11583 mSettings.writePackageRestrictionsLPr(sourceUserId); 11584 } 11585 } 11586 11587 public void addCrossProfileIntentsForPackage(String packageName, 11588 int sourceUserId, int targetUserId) { 11589 mContext.enforceCallingOrSelfPermission( 11590 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11591 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11592 mSettings.writePackageRestrictionsLPr(sourceUserId); 11593 } 11594 11595 public void removeCrossProfileIntentsForPackage(String packageName, 11596 int sourceUserId, int targetUserId) { 11597 mContext.enforceCallingOrSelfPermission( 11598 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11599 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11600 mSettings.writePackageRestrictionsLPr(sourceUserId); 11601 } 11602 11603 @Override 11604 public void clearCrossProfileIntentFilters(int sourceUserId) { 11605 mContext.enforceCallingOrSelfPermission( 11606 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11607 synchronized (mPackages) { 11608 CrossProfileIntentResolver resolver = 11609 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11610 HashSet<CrossProfileIntentFilter> set = 11611 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11612 for (CrossProfileIntentFilter filter : set) { 11613 if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) { 11614 resolver.removeFilter(filter); 11615 } 11616 } 11617 mSettings.writePackageRestrictionsLPr(sourceUserId); 11618 } 11619 } 11620 11621 @Override 11622 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11623 Intent intent = new Intent(Intent.ACTION_MAIN); 11624 intent.addCategory(Intent.CATEGORY_HOME); 11625 11626 final int callingUserId = UserHandle.getCallingUserId(); 11627 List<ResolveInfo> list = queryIntentActivities(intent, null, 11628 PackageManager.GET_META_DATA, callingUserId); 11629 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11630 true, false, false, callingUserId); 11631 11632 allHomeCandidates.clear(); 11633 if (list != null) { 11634 for (ResolveInfo ri : list) { 11635 allHomeCandidates.add(ri); 11636 } 11637 } 11638 return (preferred == null || preferred.activityInfo == null) 11639 ? null 11640 : new ComponentName(preferred.activityInfo.packageName, 11641 preferred.activityInfo.name); 11642 } 11643 11644 @Override 11645 public void setApplicationEnabledSetting(String appPackageName, 11646 int newState, int flags, int userId, String callingPackage) { 11647 if (!sUserManager.exists(userId)) return; 11648 if (callingPackage == null) { 11649 callingPackage = Integer.toString(Binder.getCallingUid()); 11650 } 11651 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11652 } 11653 11654 @Override 11655 public void setComponentEnabledSetting(ComponentName componentName, 11656 int newState, int flags, int userId) { 11657 if (!sUserManager.exists(userId)) return; 11658 setEnabledSetting(componentName.getPackageName(), 11659 componentName.getClassName(), newState, flags, userId, null); 11660 } 11661 11662 private void setEnabledSetting(final String packageName, String className, int newState, 11663 final int flags, int userId, String callingPackage) { 11664 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11665 || newState == COMPONENT_ENABLED_STATE_ENABLED 11666 || newState == COMPONENT_ENABLED_STATE_DISABLED 11667 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11668 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11669 throw new IllegalArgumentException("Invalid new component state: " 11670 + newState); 11671 } 11672 PackageSetting pkgSetting; 11673 final int uid = Binder.getCallingUid(); 11674 final int permission = mContext.checkCallingOrSelfPermission( 11675 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11676 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11677 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11678 boolean sendNow = false; 11679 boolean isApp = (className == null); 11680 String componentName = isApp ? packageName : className; 11681 int packageUid = -1; 11682 ArrayList<String> components; 11683 11684 // writer 11685 synchronized (mPackages) { 11686 pkgSetting = mSettings.mPackages.get(packageName); 11687 if (pkgSetting == null) { 11688 if (className == null) { 11689 throw new IllegalArgumentException( 11690 "Unknown package: " + packageName); 11691 } 11692 throw new IllegalArgumentException( 11693 "Unknown component: " + packageName 11694 + "/" + className); 11695 } 11696 // Allow root and verify that userId is not being specified by a different user 11697 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11698 throw new SecurityException( 11699 "Permission Denial: attempt to change component state from pid=" 11700 + Binder.getCallingPid() 11701 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11702 } 11703 if (className == null) { 11704 // We're dealing with an application/package level state change 11705 if (pkgSetting.getEnabled(userId) == newState) { 11706 // Nothing to do 11707 return; 11708 } 11709 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11710 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11711 // Don't care about who enables an app. 11712 callingPackage = null; 11713 } 11714 pkgSetting.setEnabled(newState, userId, callingPackage); 11715 // pkgSetting.pkg.mSetEnabled = newState; 11716 } else { 11717 // We're dealing with a component level state change 11718 // First, verify that this is a valid class name. 11719 PackageParser.Package pkg = pkgSetting.pkg; 11720 if (pkg == null || !pkg.hasComponentClassName(className)) { 11721 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11722 throw new IllegalArgumentException("Component class " + className 11723 + " does not exist in " + packageName); 11724 } else { 11725 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11726 + className + " does not exist in " + packageName); 11727 } 11728 } 11729 switch (newState) { 11730 case COMPONENT_ENABLED_STATE_ENABLED: 11731 if (!pkgSetting.enableComponentLPw(className, userId)) { 11732 return; 11733 } 11734 break; 11735 case COMPONENT_ENABLED_STATE_DISABLED: 11736 if (!pkgSetting.disableComponentLPw(className, userId)) { 11737 return; 11738 } 11739 break; 11740 case COMPONENT_ENABLED_STATE_DEFAULT: 11741 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11742 return; 11743 } 11744 break; 11745 default: 11746 Slog.e(TAG, "Invalid new component state: " + newState); 11747 return; 11748 } 11749 } 11750 mSettings.writePackageRestrictionsLPr(userId); 11751 components = mPendingBroadcasts.get(userId, packageName); 11752 final boolean newPackage = components == null; 11753 if (newPackage) { 11754 components = new ArrayList<String>(); 11755 } 11756 if (!components.contains(componentName)) { 11757 components.add(componentName); 11758 } 11759 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11760 sendNow = true; 11761 // Purge entry from pending broadcast list if another one exists already 11762 // since we are sending one right away. 11763 mPendingBroadcasts.remove(userId, packageName); 11764 } else { 11765 if (newPackage) { 11766 mPendingBroadcasts.put(userId, packageName, components); 11767 } 11768 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11769 // Schedule a message 11770 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11771 } 11772 } 11773 } 11774 11775 long callingId = Binder.clearCallingIdentity(); 11776 try { 11777 if (sendNow) { 11778 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11779 sendPackageChangedBroadcast(packageName, 11780 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11781 } 11782 } finally { 11783 Binder.restoreCallingIdentity(callingId); 11784 } 11785 } 11786 11787 private void sendPackageChangedBroadcast(String packageName, 11788 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11789 if (DEBUG_INSTALL) 11790 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11791 + componentNames); 11792 Bundle extras = new Bundle(4); 11793 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11794 String nameList[] = new String[componentNames.size()]; 11795 componentNames.toArray(nameList); 11796 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11797 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11798 extras.putInt(Intent.EXTRA_UID, packageUid); 11799 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11800 new int[] {UserHandle.getUserId(packageUid)}); 11801 } 11802 11803 @Override 11804 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11805 if (!sUserManager.exists(userId)) return; 11806 final int uid = Binder.getCallingUid(); 11807 final int permission = mContext.checkCallingOrSelfPermission( 11808 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11809 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11810 enforceCrossUserPermission(uid, userId, true, "stop package"); 11811 // writer 11812 synchronized (mPackages) { 11813 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11814 uid, userId)) { 11815 scheduleWritePackageRestrictionsLocked(userId); 11816 } 11817 } 11818 } 11819 11820 @Override 11821 public String getInstallerPackageName(String packageName) { 11822 // reader 11823 synchronized (mPackages) { 11824 return mSettings.getInstallerPackageNameLPr(packageName); 11825 } 11826 } 11827 11828 @Override 11829 public int getApplicationEnabledSetting(String packageName, int userId) { 11830 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11831 int uid = Binder.getCallingUid(); 11832 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11833 // reader 11834 synchronized (mPackages) { 11835 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11836 } 11837 } 11838 11839 @Override 11840 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11841 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11842 int uid = Binder.getCallingUid(); 11843 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11844 // reader 11845 synchronized (mPackages) { 11846 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11847 } 11848 } 11849 11850 @Override 11851 public void enterSafeMode() { 11852 enforceSystemOrRoot("Only the system can request entering safe mode"); 11853 11854 if (!mSystemReady) { 11855 mSafeMode = true; 11856 } 11857 } 11858 11859 @Override 11860 public void systemReady() { 11861 mSystemReady = true; 11862 11863 // Read the compatibilty setting when the system is ready. 11864 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11865 mContext.getContentResolver(), 11866 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11867 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11868 if (DEBUG_SETTINGS) { 11869 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11870 } 11871 11872 synchronized (mPackages) { 11873 // Verify that all of the preferred activity components actually 11874 // exist. It is possible for applications to be updated and at 11875 // that point remove a previously declared activity component that 11876 // had been set as a preferred activity. We try to clean this up 11877 // the next time we encounter that preferred activity, but it is 11878 // possible for the user flow to never be able to return to that 11879 // situation so here we do a sanity check to make sure we haven't 11880 // left any junk around. 11881 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11882 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11883 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11884 removed.clear(); 11885 for (PreferredActivity pa : pir.filterSet()) { 11886 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11887 removed.add(pa); 11888 } 11889 } 11890 if (removed.size() > 0) { 11891 for (int r=0; r<removed.size(); r++) { 11892 PreferredActivity pa = removed.get(r); 11893 Slog.w(TAG, "Removing dangling preferred activity: " 11894 + pa.mPref.mComponent); 11895 pir.removeFilter(pa); 11896 } 11897 mSettings.writePackageRestrictionsLPr( 11898 mSettings.mPreferredActivities.keyAt(i)); 11899 } 11900 } 11901 } 11902 sUserManager.systemReady(); 11903 } 11904 11905 @Override 11906 public boolean isSafeMode() { 11907 return mSafeMode; 11908 } 11909 11910 @Override 11911 public boolean hasSystemUidErrors() { 11912 return mHasSystemUidErrors; 11913 } 11914 11915 static String arrayToString(int[] array) { 11916 StringBuffer buf = new StringBuffer(128); 11917 buf.append('['); 11918 if (array != null) { 11919 for (int i=0; i<array.length; i++) { 11920 if (i > 0) buf.append(", "); 11921 buf.append(array[i]); 11922 } 11923 } 11924 buf.append(']'); 11925 return buf.toString(); 11926 } 11927 11928 static class DumpState { 11929 public static final int DUMP_LIBS = 1 << 0; 11930 11931 public static final int DUMP_FEATURES = 1 << 1; 11932 11933 public static final int DUMP_RESOLVERS = 1 << 2; 11934 11935 public static final int DUMP_PERMISSIONS = 1 << 3; 11936 11937 public static final int DUMP_PACKAGES = 1 << 4; 11938 11939 public static final int DUMP_SHARED_USERS = 1 << 5; 11940 11941 public static final int DUMP_MESSAGES = 1 << 6; 11942 11943 public static final int DUMP_PROVIDERS = 1 << 7; 11944 11945 public static final int DUMP_VERIFIERS = 1 << 8; 11946 11947 public static final int DUMP_PREFERRED = 1 << 9; 11948 11949 public static final int DUMP_PREFERRED_XML = 1 << 10; 11950 11951 public static final int DUMP_KEYSETS = 1 << 11; 11952 11953 public static final int DUMP_VERSION = 1 << 12; 11954 11955 public static final int OPTION_SHOW_FILTERS = 1 << 0; 11956 11957 private int mTypes; 11958 11959 private int mOptions; 11960 11961 private boolean mTitlePrinted; 11962 11963 private SharedUserSetting mSharedUser; 11964 11965 public boolean isDumping(int type) { 11966 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 11967 return true; 11968 } 11969 11970 return (mTypes & type) != 0; 11971 } 11972 11973 public void setDump(int type) { 11974 mTypes |= type; 11975 } 11976 11977 public boolean isOptionEnabled(int option) { 11978 return (mOptions & option) != 0; 11979 } 11980 11981 public void setOptionEnabled(int option) { 11982 mOptions |= option; 11983 } 11984 11985 public boolean onTitlePrinted() { 11986 final boolean printed = mTitlePrinted; 11987 mTitlePrinted = true; 11988 return printed; 11989 } 11990 11991 public boolean getTitlePrinted() { 11992 return mTitlePrinted; 11993 } 11994 11995 public void setTitlePrinted(boolean enabled) { 11996 mTitlePrinted = enabled; 11997 } 11998 11999 public SharedUserSetting getSharedUser() { 12000 return mSharedUser; 12001 } 12002 12003 public void setSharedUser(SharedUserSetting user) { 12004 mSharedUser = user; 12005 } 12006 } 12007 12008 @Override 12009 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12010 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12011 != PackageManager.PERMISSION_GRANTED) { 12012 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12013 + Binder.getCallingPid() 12014 + ", uid=" + Binder.getCallingUid() 12015 + " without permission " 12016 + android.Manifest.permission.DUMP); 12017 return; 12018 } 12019 12020 DumpState dumpState = new DumpState(); 12021 boolean fullPreferred = false; 12022 boolean checkin = false; 12023 12024 String packageName = null; 12025 12026 int opti = 0; 12027 while (opti < args.length) { 12028 String opt = args[opti]; 12029 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12030 break; 12031 } 12032 opti++; 12033 if ("-a".equals(opt)) { 12034 // Right now we only know how to print all. 12035 } else if ("-h".equals(opt)) { 12036 pw.println("Package manager dump options:"); 12037 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12038 pw.println(" --checkin: dump for a checkin"); 12039 pw.println(" -f: print details of intent filters"); 12040 pw.println(" -h: print this help"); 12041 pw.println(" cmd may be one of:"); 12042 pw.println(" l[ibraries]: list known shared libraries"); 12043 pw.println(" f[ibraries]: list device features"); 12044 pw.println(" k[eysets]: print known keysets"); 12045 pw.println(" r[esolvers]: dump intent resolvers"); 12046 pw.println(" perm[issions]: dump permissions"); 12047 pw.println(" pref[erred]: print preferred package settings"); 12048 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12049 pw.println(" prov[iders]: dump content providers"); 12050 pw.println(" p[ackages]: dump installed packages"); 12051 pw.println(" s[hared-users]: dump shared user IDs"); 12052 pw.println(" m[essages]: print collected runtime messages"); 12053 pw.println(" v[erifiers]: print package verifier info"); 12054 pw.println(" version: print database version info"); 12055 pw.println(" write: write current settings now"); 12056 pw.println(" <package.name>: info about given package"); 12057 return; 12058 } else if ("--checkin".equals(opt)) { 12059 checkin = true; 12060 } else if ("-f".equals(opt)) { 12061 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12062 } else { 12063 pw.println("Unknown argument: " + opt + "; use -h for help"); 12064 } 12065 } 12066 12067 // Is the caller requesting to dump a particular piece of data? 12068 if (opti < args.length) { 12069 String cmd = args[opti]; 12070 opti++; 12071 // Is this a package name? 12072 if ("android".equals(cmd) || cmd.contains(".")) { 12073 packageName = cmd; 12074 // When dumping a single package, we always dump all of its 12075 // filter information since the amount of data will be reasonable. 12076 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12077 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12078 dumpState.setDump(DumpState.DUMP_LIBS); 12079 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12080 dumpState.setDump(DumpState.DUMP_FEATURES); 12081 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12082 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12083 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12084 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12085 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12086 dumpState.setDump(DumpState.DUMP_PREFERRED); 12087 } else if ("preferred-xml".equals(cmd)) { 12088 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12089 if (opti < args.length && "--full".equals(args[opti])) { 12090 fullPreferred = true; 12091 opti++; 12092 } 12093 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12094 dumpState.setDump(DumpState.DUMP_PACKAGES); 12095 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12096 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12097 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12098 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12099 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12100 dumpState.setDump(DumpState.DUMP_MESSAGES); 12101 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12102 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12103 } else if ("version".equals(cmd)) { 12104 dumpState.setDump(DumpState.DUMP_VERSION); 12105 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12106 dumpState.setDump(DumpState.DUMP_KEYSETS); 12107 } else if ("write".equals(cmd)) { 12108 synchronized (mPackages) { 12109 mSettings.writeLPr(); 12110 pw.println("Settings written."); 12111 return; 12112 } 12113 } 12114 } 12115 12116 if (checkin) { 12117 pw.println("vers,1"); 12118 } 12119 12120 // reader 12121 synchronized (mPackages) { 12122 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12123 if (!checkin) { 12124 if (dumpState.onTitlePrinted()) 12125 pw.println(); 12126 pw.println("Database versions:"); 12127 pw.print(" SDK Version:"); 12128 pw.print(" internal="); 12129 pw.print(mSettings.mInternalSdkPlatform); 12130 pw.print(" external="); 12131 pw.println(mSettings.mExternalSdkPlatform); 12132 pw.print(" DB Version:"); 12133 pw.print(" internal="); 12134 pw.print(mSettings.mInternalDatabaseVersion); 12135 pw.print(" external="); 12136 pw.println(mSettings.mExternalDatabaseVersion); 12137 } 12138 } 12139 12140 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12141 if (!checkin) { 12142 if (dumpState.onTitlePrinted()) 12143 pw.println(); 12144 pw.println("Verifiers:"); 12145 pw.print(" Required: "); 12146 pw.print(mRequiredVerifierPackage); 12147 pw.print(" (uid="); 12148 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12149 pw.println(")"); 12150 } else if (mRequiredVerifierPackage != null) { 12151 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12152 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12153 } 12154 } 12155 12156 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12157 boolean printedHeader = false; 12158 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12159 while (it.hasNext()) { 12160 String name = it.next(); 12161 SharedLibraryEntry ent = mSharedLibraries.get(name); 12162 if (!checkin) { 12163 if (!printedHeader) { 12164 if (dumpState.onTitlePrinted()) 12165 pw.println(); 12166 pw.println("Libraries:"); 12167 printedHeader = true; 12168 } 12169 pw.print(" "); 12170 } else { 12171 pw.print("lib,"); 12172 } 12173 pw.print(name); 12174 if (!checkin) { 12175 pw.print(" -> "); 12176 } 12177 if (ent.path != null) { 12178 if (!checkin) { 12179 pw.print("(jar) "); 12180 pw.print(ent.path); 12181 } else { 12182 pw.print(",jar,"); 12183 pw.print(ent.path); 12184 } 12185 } else { 12186 if (!checkin) { 12187 pw.print("(apk) "); 12188 pw.print(ent.apk); 12189 } else { 12190 pw.print(",apk,"); 12191 pw.print(ent.apk); 12192 } 12193 } 12194 pw.println(); 12195 } 12196 } 12197 12198 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12199 if (dumpState.onTitlePrinted()) 12200 pw.println(); 12201 if (!checkin) { 12202 pw.println("Features:"); 12203 } 12204 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12205 while (it.hasNext()) { 12206 String name = it.next(); 12207 if (!checkin) { 12208 pw.print(" "); 12209 } else { 12210 pw.print("feat,"); 12211 } 12212 pw.println(name); 12213 } 12214 } 12215 12216 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12217 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12218 : "Activity Resolver Table:", " ", packageName, 12219 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12220 dumpState.setTitlePrinted(true); 12221 } 12222 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12223 : "Receiver Resolver Table:", " ", packageName, 12224 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12225 dumpState.setTitlePrinted(true); 12226 } 12227 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12228 : "Service Resolver Table:", " ", packageName, 12229 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12230 dumpState.setTitlePrinted(true); 12231 } 12232 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12233 : "Provider Resolver Table:", " ", packageName, 12234 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12235 dumpState.setTitlePrinted(true); 12236 } 12237 } 12238 12239 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12240 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12241 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12242 int user = mSettings.mPreferredActivities.keyAt(i); 12243 if (pir.dump(pw, 12244 dumpState.getTitlePrinted() 12245 ? "\nPreferred Activities User " + user + ":" 12246 : "Preferred Activities User " + user + ":", " ", 12247 packageName, true)) { 12248 dumpState.setTitlePrinted(true); 12249 } 12250 } 12251 } 12252 12253 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12254 pw.flush(); 12255 FileOutputStream fout = new FileOutputStream(fd); 12256 BufferedOutputStream str = new BufferedOutputStream(fout); 12257 XmlSerializer serializer = new FastXmlSerializer(); 12258 try { 12259 serializer.setOutput(str, "utf-8"); 12260 serializer.startDocument(null, true); 12261 serializer.setFeature( 12262 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12263 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12264 serializer.endDocument(); 12265 serializer.flush(); 12266 } catch (IllegalArgumentException e) { 12267 pw.println("Failed writing: " + e); 12268 } catch (IllegalStateException e) { 12269 pw.println("Failed writing: " + e); 12270 } catch (IOException e) { 12271 pw.println("Failed writing: " + e); 12272 } 12273 } 12274 12275 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12276 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12277 } 12278 12279 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12280 boolean printedSomething = false; 12281 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12282 if (packageName != null && !packageName.equals(p.info.packageName)) { 12283 continue; 12284 } 12285 if (!printedSomething) { 12286 if (dumpState.onTitlePrinted()) 12287 pw.println(); 12288 pw.println("Registered ContentProviders:"); 12289 printedSomething = true; 12290 } 12291 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12292 pw.print(" "); pw.println(p.toString()); 12293 } 12294 printedSomething = false; 12295 for (Map.Entry<String, PackageParser.Provider> entry : 12296 mProvidersByAuthority.entrySet()) { 12297 PackageParser.Provider p = entry.getValue(); 12298 if (packageName != null && !packageName.equals(p.info.packageName)) { 12299 continue; 12300 } 12301 if (!printedSomething) { 12302 if (dumpState.onTitlePrinted()) 12303 pw.println(); 12304 pw.println("ContentProvider Authorities:"); 12305 printedSomething = true; 12306 } 12307 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12308 pw.print(" "); pw.println(p.toString()); 12309 if (p.info != null && p.info.applicationInfo != null) { 12310 final String appInfo = p.info.applicationInfo.toString(); 12311 pw.print(" applicationInfo="); pw.println(appInfo); 12312 } 12313 } 12314 } 12315 12316 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12317 mSettings.mKeySetManagerService.dump(pw, packageName, dumpState); 12318 } 12319 12320 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12321 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12322 } 12323 12324 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12325 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12326 } 12327 12328 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12329 if (dumpState.onTitlePrinted()) 12330 pw.println(); 12331 mSettings.dumpReadMessagesLPr(pw, dumpState); 12332 12333 pw.println(); 12334 pw.println("Package warning messages:"); 12335 final File fname = getSettingsProblemFile(); 12336 FileInputStream in = null; 12337 try { 12338 in = new FileInputStream(fname); 12339 final int avail = in.available(); 12340 final byte[] data = new byte[avail]; 12341 in.read(data); 12342 pw.print(new String(data)); 12343 } catch (FileNotFoundException e) { 12344 } catch (IOException e) { 12345 } finally { 12346 if (in != null) { 12347 try { 12348 in.close(); 12349 } catch (IOException e) { 12350 } 12351 } 12352 } 12353 } 12354 } 12355 } 12356 12357 // ------- apps on sdcard specific code ------- 12358 static final boolean DEBUG_SD_INSTALL = false; 12359 12360 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12361 12362 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12363 12364 private boolean mMediaMounted = false; 12365 12366 private String getEncryptKey() { 12367 try { 12368 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12369 SD_ENCRYPTION_KEYSTORE_NAME); 12370 if (sdEncKey == null) { 12371 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12372 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12373 if (sdEncKey == null) { 12374 Slog.e(TAG, "Failed to create encryption keys"); 12375 return null; 12376 } 12377 } 12378 return sdEncKey; 12379 } catch (NoSuchAlgorithmException nsae) { 12380 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12381 return null; 12382 } catch (IOException ioe) { 12383 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12384 return null; 12385 } 12386 12387 } 12388 12389 /* package */static String getTempContainerId() { 12390 int tmpIdx = 1; 12391 String list[] = PackageHelper.getSecureContainerList(); 12392 if (list != null) { 12393 for (final String name : list) { 12394 // Ignore null and non-temporary container entries 12395 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12396 continue; 12397 } 12398 12399 String subStr = name.substring(mTempContainerPrefix.length()); 12400 try { 12401 int cid = Integer.parseInt(subStr); 12402 if (cid >= tmpIdx) { 12403 tmpIdx = cid + 1; 12404 } 12405 } catch (NumberFormatException e) { 12406 } 12407 } 12408 } 12409 return mTempContainerPrefix + tmpIdx; 12410 } 12411 12412 /* 12413 * Update media status on PackageManager. 12414 */ 12415 @Override 12416 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12417 int callingUid = Binder.getCallingUid(); 12418 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12419 throw new SecurityException("Media status can only be updated by the system"); 12420 } 12421 // reader; this apparently protects mMediaMounted, but should probably 12422 // be a different lock in that case. 12423 synchronized (mPackages) { 12424 Log.i(TAG, "Updating external media status from " 12425 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12426 + (mediaStatus ? "mounted" : "unmounted")); 12427 if (DEBUG_SD_INSTALL) 12428 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12429 + ", mMediaMounted=" + mMediaMounted); 12430 if (mediaStatus == mMediaMounted) { 12431 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12432 : 0, -1); 12433 mHandler.sendMessage(msg); 12434 return; 12435 } 12436 mMediaMounted = mediaStatus; 12437 } 12438 // Queue up an async operation since the package installation may take a 12439 // little while. 12440 mHandler.post(new Runnable() { 12441 public void run() { 12442 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12443 } 12444 }); 12445 } 12446 12447 /** 12448 * Called by MountService when the initial ASECs to scan are available. 12449 * Should block until all the ASEC containers are finished being scanned. 12450 */ 12451 public void scanAvailableAsecs() { 12452 updateExternalMediaStatusInner(true, false, false); 12453 if (mShouldRestoreconData) { 12454 SELinuxMMAC.setRestoreconDone(); 12455 mShouldRestoreconData = false; 12456 } 12457 } 12458 12459 /* 12460 * Collect information of applications on external media, map them against 12461 * existing containers and update information based on current mount status. 12462 * Please note that we always have to report status if reportStatus has been 12463 * set to true especially when unloading packages. 12464 */ 12465 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12466 boolean externalStorage) { 12467 // Collection of uids 12468 int uidArr[] = null; 12469 // Collection of stale containers 12470 HashSet<String> removeCids = new HashSet<String>(); 12471 // Collection of packages on external media with valid containers. 12472 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12473 // Get list of secure containers. 12474 final String list[] = PackageHelper.getSecureContainerList(); 12475 if (list == null || list.length == 0) { 12476 Log.i(TAG, "No secure containers on sdcard"); 12477 } else { 12478 // Process list of secure containers and categorize them 12479 // as active or stale based on their package internal state. 12480 int uidList[] = new int[list.length]; 12481 int num = 0; 12482 // reader 12483 synchronized (mPackages) { 12484 for (String cid : list) { 12485 if (DEBUG_SD_INSTALL) 12486 Log.i(TAG, "Processing container " + cid); 12487 String pkgName = getAsecPackageName(cid); 12488 if (pkgName == null) { 12489 if (DEBUG_SD_INSTALL) 12490 Log.i(TAG, "Container : " + cid + " stale"); 12491 removeCids.add(cid); 12492 continue; 12493 } 12494 if (DEBUG_SD_INSTALL) 12495 Log.i(TAG, "Looking for pkg : " + pkgName); 12496 12497 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12498 if (ps == null) { 12499 Log.i(TAG, "Deleting container with no matching settings " + cid); 12500 removeCids.add(cid); 12501 continue; 12502 } 12503 12504 /* 12505 * Skip packages that are not external if we're unmounting 12506 * external storage. 12507 */ 12508 if (externalStorage && !isMounted && !isExternal(ps)) { 12509 continue; 12510 } 12511 12512 final AsecInstallArgs args = new AsecInstallArgs(cid, 12513 getAppInstructionSetFromSettings(ps), 12514 isForwardLocked(ps)); 12515 // The package status is changed only if the code path 12516 // matches between settings and the container id. 12517 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12518 if (DEBUG_SD_INSTALL) { 12519 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12520 + " at code path: " + ps.codePathString); 12521 } 12522 12523 // We do have a valid package installed on sdcard 12524 processCids.put(args, ps.codePathString); 12525 final int uid = ps.appId; 12526 if (uid != -1) { 12527 uidList[num++] = uid; 12528 } 12529 } else { 12530 Log.i(TAG, "Deleting stale container for " + cid); 12531 removeCids.add(cid); 12532 } 12533 } 12534 } 12535 12536 if (num > 0) { 12537 // Sort uid list 12538 Arrays.sort(uidList, 0, num); 12539 // Throw away duplicates 12540 uidArr = new int[num]; 12541 uidArr[0] = uidList[0]; 12542 int di = 0; 12543 for (int i = 1; i < num; i++) { 12544 if (uidList[i - 1] != uidList[i]) { 12545 uidArr[di++] = uidList[i]; 12546 } 12547 } 12548 } 12549 } 12550 // Process packages with valid entries. 12551 if (isMounted) { 12552 if (DEBUG_SD_INSTALL) 12553 Log.i(TAG, "Loading packages"); 12554 loadMediaPackages(processCids, uidArr, removeCids); 12555 startCleaningPackages(); 12556 } else { 12557 if (DEBUG_SD_INSTALL) 12558 Log.i(TAG, "Unloading packages"); 12559 unloadMediaPackages(processCids, uidArr, reportStatus); 12560 } 12561 } 12562 12563 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12564 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12565 int size = pkgList.size(); 12566 if (size > 0) { 12567 // Send broadcasts here 12568 Bundle extras = new Bundle(); 12569 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12570 .toArray(new String[size])); 12571 if (uidArr != null) { 12572 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12573 } 12574 if (replacing) { 12575 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12576 } 12577 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12578 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12579 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12580 } 12581 } 12582 12583 /* 12584 * Look at potentially valid container ids from processCids If package 12585 * information doesn't match the one on record or package scanning fails, 12586 * the cid is added to list of removeCids. We currently don't delete stale 12587 * containers. 12588 */ 12589 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12590 HashSet<String> removeCids) { 12591 ArrayList<String> pkgList = new ArrayList<String>(); 12592 Set<AsecInstallArgs> keys = processCids.keySet(); 12593 boolean doGc = false; 12594 for (AsecInstallArgs args : keys) { 12595 String codePath = processCids.get(args); 12596 if (DEBUG_SD_INSTALL) 12597 Log.i(TAG, "Loading container : " + args.cid); 12598 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12599 try { 12600 // Make sure there are no container errors first. 12601 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12602 Slog.e(TAG, "Failed to mount cid : " + args.cid 12603 + " when installing from sdcard"); 12604 continue; 12605 } 12606 // Check code path here. 12607 if (codePath == null || !codePath.equals(args.getCodePath())) { 12608 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12609 + " does not match one in settings " + codePath); 12610 continue; 12611 } 12612 // Parse package 12613 int parseFlags = mDefParseFlags; 12614 if (args.isExternal()) { 12615 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12616 } 12617 if (args.isFwdLocked()) { 12618 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12619 } 12620 12621 doGc = true; 12622 synchronized (mInstallLock) { 12623 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 12624 0, 0, null, null); 12625 // Scan the package 12626 if (pkg != null) { 12627 /* 12628 * TODO why is the lock being held? doPostInstall is 12629 * called in other places without the lock. This needs 12630 * to be straightened out. 12631 */ 12632 // writer 12633 synchronized (mPackages) { 12634 retCode = PackageManager.INSTALL_SUCCEEDED; 12635 pkgList.add(pkg.packageName); 12636 // Post process args 12637 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12638 pkg.applicationInfo.uid); 12639 } 12640 } else { 12641 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12642 } 12643 } 12644 12645 } finally { 12646 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12647 // Don't destroy container here. Wait till gc clears things 12648 // up. 12649 removeCids.add(args.cid); 12650 } 12651 } 12652 } 12653 // writer 12654 synchronized (mPackages) { 12655 // If the platform SDK has changed since the last time we booted, 12656 // we need to re-grant app permission to catch any new ones that 12657 // appear. This is really a hack, and means that apps can in some 12658 // cases get permissions that the user didn't initially explicitly 12659 // allow... it would be nice to have some better way to handle 12660 // this situation. 12661 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12662 if (regrantPermissions) 12663 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12664 + mSdkVersion + "; regranting permissions for external storage"); 12665 mSettings.mExternalSdkPlatform = mSdkVersion; 12666 12667 // Make sure group IDs have been assigned, and any permission 12668 // changes in other apps are accounted for 12669 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12670 | (regrantPermissions 12671 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12672 : 0)); 12673 12674 mSettings.updateExternalDatabaseVersion(); 12675 12676 // can downgrade to reader 12677 // Persist settings 12678 mSettings.writeLPr(); 12679 } 12680 // Send a broadcast to let everyone know we are done processing 12681 if (pkgList.size() > 0) { 12682 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12683 } 12684 // Force gc to avoid any stale parser references that we might have. 12685 if (doGc) { 12686 Runtime.getRuntime().gc(); 12687 } 12688 // List stale containers and destroy stale temporary containers. 12689 if (removeCids != null) { 12690 for (String cid : removeCids) { 12691 if (cid.startsWith(mTempContainerPrefix)) { 12692 Log.i(TAG, "Destroying stale temporary container " + cid); 12693 PackageHelper.destroySdDir(cid); 12694 } else { 12695 Log.w(TAG, "Container " + cid + " is stale"); 12696 } 12697 } 12698 } 12699 } 12700 12701 /* 12702 * Utility method to unload a list of specified containers 12703 */ 12704 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12705 // Just unmount all valid containers. 12706 for (AsecInstallArgs arg : cidArgs) { 12707 synchronized (mInstallLock) { 12708 arg.doPostDeleteLI(false); 12709 } 12710 } 12711 } 12712 12713 /* 12714 * Unload packages mounted on external media. This involves deleting package 12715 * data from internal structures, sending broadcasts about diabled packages, 12716 * gc'ing to free up references, unmounting all secure containers 12717 * corresponding to packages on external media, and posting a 12718 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12719 * that we always have to post this message if status has been requested no 12720 * matter what. 12721 */ 12722 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12723 final boolean reportStatus) { 12724 if (DEBUG_SD_INSTALL) 12725 Log.i(TAG, "unloading media packages"); 12726 ArrayList<String> pkgList = new ArrayList<String>(); 12727 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12728 final Set<AsecInstallArgs> keys = processCids.keySet(); 12729 for (AsecInstallArgs args : keys) { 12730 String pkgName = args.getPackageName(); 12731 if (DEBUG_SD_INSTALL) 12732 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12733 // Delete package internally 12734 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12735 synchronized (mInstallLock) { 12736 boolean res = deletePackageLI(pkgName, null, false, null, null, 12737 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12738 if (res) { 12739 pkgList.add(pkgName); 12740 } else { 12741 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12742 failedList.add(args); 12743 } 12744 } 12745 } 12746 12747 // reader 12748 synchronized (mPackages) { 12749 // We didn't update the settings after removing each package; 12750 // write them now for all packages. 12751 mSettings.writeLPr(); 12752 } 12753 12754 // We have to absolutely send UPDATED_MEDIA_STATUS only 12755 // after confirming that all the receivers processed the ordered 12756 // broadcast when packages get disabled, force a gc to clean things up. 12757 // and unload all the containers. 12758 if (pkgList.size() > 0) { 12759 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12760 new IIntentReceiver.Stub() { 12761 public void performReceive(Intent intent, int resultCode, String data, 12762 Bundle extras, boolean ordered, boolean sticky, 12763 int sendingUser) throws RemoteException { 12764 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12765 reportStatus ? 1 : 0, 1, keys); 12766 mHandler.sendMessage(msg); 12767 } 12768 }); 12769 } else { 12770 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12771 keys); 12772 mHandler.sendMessage(msg); 12773 } 12774 } 12775 12776 /** Binder call */ 12777 @Override 12778 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12779 final int flags) { 12780 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12781 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12782 int returnCode = PackageManager.MOVE_SUCCEEDED; 12783 int currFlags = 0; 12784 int newFlags = 0; 12785 // reader 12786 synchronized (mPackages) { 12787 PackageParser.Package pkg = mPackages.get(packageName); 12788 if (pkg == null) { 12789 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12790 } else { 12791 // Disable moving fwd locked apps and system packages 12792 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12793 Slog.w(TAG, "Cannot move system application"); 12794 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12795 } else if (pkg.mOperationPending) { 12796 Slog.w(TAG, "Attempt to move package which has pending operations"); 12797 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12798 } else { 12799 // Find install location first 12800 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12801 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12802 Slog.w(TAG, "Ambigous flags specified for move location."); 12803 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12804 } else { 12805 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12806 : PackageManager.INSTALL_INTERNAL; 12807 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12808 : PackageManager.INSTALL_INTERNAL; 12809 12810 if (newFlags == currFlags) { 12811 Slog.w(TAG, "No move required. Trying to move to same location"); 12812 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12813 } else { 12814 if (isForwardLocked(pkg)) { 12815 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12816 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12817 } 12818 } 12819 } 12820 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12821 pkg.mOperationPending = true; 12822 } 12823 } 12824 } 12825 12826 /* 12827 * TODO this next block probably shouldn't be inside the lock. We 12828 * can't guarantee these won't change after this is fired off 12829 * anyway. 12830 */ 12831 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12832 processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user), 12833 returnCode); 12834 } else { 12835 Message msg = mHandler.obtainMessage(INIT_COPY); 12836 final String instructionSet = getAppInstructionSet(pkg.applicationInfo); 12837 InstallArgs srcArgs = createInstallArgsForExisting(currFlags, 12838 pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(), 12839 pkg.applicationInfo.nativeLibraryDir, instructionSet); 12840 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 12841 instructionSet, pkg.applicationInfo.uid, user); 12842 msg.obj = mp; 12843 mHandler.sendMessage(msg); 12844 } 12845 } 12846 } 12847 12848 private void processPendingMove(final MoveParams mp, final int currentStatus) { 12849 // Queue up an async operation since the package deletion may take a 12850 // little while. 12851 mHandler.post(new Runnable() { 12852 public void run() { 12853 // TODO fix this; this does nothing. 12854 mHandler.removeCallbacks(this); 12855 int returnCode = currentStatus; 12856 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 12857 int uidArr[] = null; 12858 ArrayList<String> pkgList = null; 12859 synchronized (mPackages) { 12860 PackageParser.Package pkg = mPackages.get(mp.packageName); 12861 if (pkg == null) { 12862 Slog.w(TAG, " Package " + mp.packageName 12863 + " doesn't exist. Aborting move"); 12864 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12865 } else if (!mp.srcArgs.getCodePath().equals( 12866 pkg.applicationInfo.getCodePath())) { 12867 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 12868 + mp.srcArgs.getCodePath() + " to " 12869 + pkg.applicationInfo.getCodePath() 12870 + " Aborting move and returning error"); 12871 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12872 } else { 12873 uidArr = new int[] { 12874 pkg.applicationInfo.uid 12875 }; 12876 pkgList = new ArrayList<String>(); 12877 pkgList.add(mp.packageName); 12878 } 12879 } 12880 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12881 // Send resources unavailable broadcast 12882 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 12883 // Update package code and resource paths 12884 synchronized (mInstallLock) { 12885 synchronized (mPackages) { 12886 PackageParser.Package pkg = mPackages.get(mp.packageName); 12887 // Recheck for package again. 12888 if (pkg == null) { 12889 Slog.w(TAG, " Package " + mp.packageName 12890 + " doesn't exist. Aborting move"); 12891 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12892 } else if (!mp.srcArgs.getCodePath().equals( 12893 pkg.applicationInfo.getCodePath())) { 12894 Slog.w(TAG, "Package " + mp.packageName 12895 + " code path changed from " + mp.srcArgs.getCodePath() 12896 + " to " + pkg.applicationInfo.getCodePath() 12897 + " Aborting move and returning error"); 12898 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12899 } else { 12900 final String oldCodePath = pkg.codePath; 12901 final String newCodePath = mp.targetArgs.getCodePath(); 12902 final String newResPath = mp.targetArgs.getResourcePath(); 12903 final String newNativePath = mp.targetArgs 12904 .getNativeLibraryPath(); 12905 12906 final File newNativeDir = new File(newNativePath); 12907 12908 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 12909 NativeLibraryHelper.Handle handle = null; 12910 try { 12911 handle = NativeLibraryHelper.Handle.create( 12912 new File(newCodePath)); 12913 final int abi = NativeLibraryHelper.findSupportedAbi( 12914 handle, Build.SUPPORTED_ABIS); 12915 if (abi >= 0) { 12916 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 12917 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 12918 } 12919 } catch (IOException ioe) { 12920 Slog.w(TAG, "Unable to extract native libs for package :" 12921 + mp.packageName, ioe); 12922 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12923 } finally { 12924 IoUtils.closeQuietly(handle); 12925 } 12926 } 12927 final int[] users = sUserManager.getUserIds(); 12928 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12929 for (int user : users) { 12930 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 12931 newNativePath, user) < 0) { 12932 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12933 } 12934 } 12935 } 12936 12937 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12938 pkg.codePath = newCodePath; 12939 pkg.baseCodePath = newCodePath; 12940 // Move dex files around 12941 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 12942 // Moving of dex files failed. Set 12943 // error code and abort move. 12944 pkg.codePath = oldCodePath; 12945 pkg.baseCodePath = oldCodePath; 12946 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12947 } 12948 } 12949 12950 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12951 pkg.applicationInfo.setCodePath(newCodePath); 12952 pkg.applicationInfo.setBaseCodePath(newCodePath); 12953 pkg.applicationInfo.setSplitCodePaths(null); 12954 pkg.applicationInfo.setResourcePath(newResPath); 12955 pkg.applicationInfo.setBaseResourcePath(newResPath); 12956 pkg.applicationInfo.setSplitResourcePaths(null); 12957 pkg.applicationInfo.nativeLibraryDir = newNativePath; 12958 12959 PackageSetting ps = (PackageSetting) pkg.mExtras; 12960 ps.codePath = new File(pkg.applicationInfo.getCodePath()); 12961 ps.codePathString = ps.codePath.getPath(); 12962 ps.resourcePath = new File( 12963 pkg.applicationInfo.getResourcePath()); 12964 ps.resourcePathString = ps.resourcePath.getPath(); 12965 ps.nativeLibraryPathString = newNativePath; 12966 // Set the application info flag 12967 // correctly. 12968 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 12969 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12970 } else { 12971 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12972 } 12973 ps.setFlags(pkg.applicationInfo.flags); 12974 mAppDirs.remove(oldCodePath); 12975 mAppDirs.put(newCodePath, pkg); 12976 // Persist settings 12977 mSettings.writeLPr(); 12978 } 12979 } 12980 } 12981 } 12982 // Send resources available broadcast 12983 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12984 } 12985 } 12986 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12987 // Clean up failed installation 12988 if (mp.targetArgs != null) { 12989 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 12990 -1); 12991 } 12992 } else { 12993 // Force a gc to clear things up. 12994 Runtime.getRuntime().gc(); 12995 // Delete older code 12996 synchronized (mInstallLock) { 12997 mp.srcArgs.doPostDeleteLI(true); 12998 } 12999 } 13000 13001 // Allow more operations on this file if we didn't fail because 13002 // an operation was already pending for this package. 13003 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 13004 synchronized (mPackages) { 13005 PackageParser.Package pkg = mPackages.get(mp.packageName); 13006 if (pkg != null) { 13007 pkg.mOperationPending = false; 13008 } 13009 } 13010 } 13011 13012 IPackageMoveObserver observer = mp.observer; 13013 if (observer != null) { 13014 try { 13015 observer.packageMoved(mp.packageName, returnCode); 13016 } catch (RemoteException e) { 13017 Log.i(TAG, "Observer no longer exists."); 13018 } 13019 } 13020 } 13021 }); 13022 } 13023 13024 @Override 13025 public boolean setInstallLocation(int loc) { 13026 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13027 null); 13028 if (getInstallLocation() == loc) { 13029 return true; 13030 } 13031 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13032 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13033 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13034 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13035 return true; 13036 } 13037 return false; 13038 } 13039 13040 @Override 13041 public int getInstallLocation() { 13042 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13043 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13044 PackageHelper.APP_INSTALL_AUTO); 13045 } 13046 13047 /** Called by UserManagerService */ 13048 void cleanUpUserLILPw(int userHandle) { 13049 mDirtyUsers.remove(userHandle); 13050 mSettings.removeUserLPr(userHandle); 13051 mPendingBroadcasts.remove(userHandle); 13052 if (mInstaller != null) { 13053 // Technically, we shouldn't be doing this with the package lock 13054 // held. However, this is very rare, and there is already so much 13055 // other disk I/O going on, that we'll let it slide for now. 13056 mInstaller.removeUserDataDirs(userHandle); 13057 } 13058 mUserNeedsBadging.delete(userHandle); 13059 } 13060 13061 /** Called by UserManagerService */ 13062 void createNewUserLILPw(int userHandle, File path) { 13063 if (mInstaller != null) { 13064 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13065 } 13066 } 13067 13068 @Override 13069 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13070 mContext.enforceCallingOrSelfPermission( 13071 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13072 "Only package verification agents can read the verifier device identity"); 13073 13074 synchronized (mPackages) { 13075 return mSettings.getVerifierDeviceIdentityLPw(); 13076 } 13077 } 13078 13079 @Override 13080 public void setPermissionEnforced(String permission, boolean enforced) { 13081 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13082 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13083 synchronized (mPackages) { 13084 if (mSettings.mReadExternalStorageEnforced == null 13085 || mSettings.mReadExternalStorageEnforced != enforced) { 13086 mSettings.mReadExternalStorageEnforced = enforced; 13087 mSettings.writeLPr(); 13088 } 13089 } 13090 // kill any non-foreground processes so we restart them and 13091 // grant/revoke the GID. 13092 final IActivityManager am = ActivityManagerNative.getDefault(); 13093 if (am != null) { 13094 final long token = Binder.clearCallingIdentity(); 13095 try { 13096 am.killProcessesBelowForeground("setPermissionEnforcement"); 13097 } catch (RemoteException e) { 13098 } finally { 13099 Binder.restoreCallingIdentity(token); 13100 } 13101 } 13102 } else { 13103 throw new IllegalArgumentException("No selective enforcement for " + permission); 13104 } 13105 } 13106 13107 @Override 13108 @Deprecated 13109 public boolean isPermissionEnforced(String permission) { 13110 return true; 13111 } 13112 13113 @Override 13114 public boolean isStorageLow() { 13115 final long token = Binder.clearCallingIdentity(); 13116 try { 13117 final DeviceStorageMonitorInternal 13118 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13119 if (dsm != null) { 13120 return dsm.isMemoryLow(); 13121 } else { 13122 return false; 13123 } 13124 } finally { 13125 Binder.restoreCallingIdentity(token); 13126 } 13127 } 13128 13129 @Override 13130 public IPackageInstaller getPackageInstaller() { 13131 return mInstallerService; 13132 } 13133 13134 private boolean userNeedsBadging(int userId) { 13135 int index = mUserNeedsBadging.indexOfKey(userId); 13136 if (index < 0) { 13137 final UserInfo userInfo; 13138 final long token = Binder.clearCallingIdentity(); 13139 try { 13140 userInfo = sUserManager.getUserInfo(userId); 13141 } finally { 13142 Binder.restoreCallingIdentity(token); 13143 } 13144 final boolean b; 13145 if (userInfo != null && userInfo.isManagedProfile()) { 13146 b = true; 13147 } else { 13148 b = false; 13149 } 13150 mUserNeedsBadging.put(userId, b); 13151 return b; 13152 } 13153 return mUserNeedsBadging.valueAt(index); 13154 } 13155} 13156