PackageManagerService.java revision 65b1a7c0ba4213d625b1cb36d1405cf8767310d4
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 final String nativeLibraryPath; 6152 if (bundledApk) { 6153 // If "/system/lib64/apkname" exists, assume that is the per-package 6154 // native library directory to use; otherwise use "/system/lib/apkname". 6155 String apkRoot = calculateApkRoot(pkg.applicationInfo.getCodePath()); 6156 File lib64 = new File(apkRoot, LIB64_DIR_NAME); 6157 File packLib64 = new File(lib64, apkName); 6158 File libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME); 6159 nativeLibraryPath = (new File(libDir, apkName)).getAbsolutePath(); 6160 } else { 6161 // We're installing an upgrade; use directory found during scan 6162 // TODO: consider deriving this based on instructionSet 6163 nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir; 6164 } 6165 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath; 6166 // pkgSetting might be null during rescan following uninstall of updates 6167 // to a bundled app, so accommodate that possibility. The settings in 6168 // that case will be established later from the parsed package. 6169 if (pkgSetting != null) { 6170 pkgSetting.nativeLibraryPathString = nativeLibraryPath; 6171 } 6172 } 6173 6174 // Deduces the required ABI of an upgraded system app. 6175 private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) { 6176 final String apkRoot = calculateApkRoot(pkg.applicationInfo.getCodePath()); 6177 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6178 6179 // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>" 6180 // or similar. 6181 final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath()); 6182 final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath()); 6183 6184 // Assume that the bundled native libraries always correspond to the 6185 // most preferred 32 or 64 bit ABI. 6186 if (lib64.exists()) { 6187 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6188 pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0]; 6189 } else if (lib.exists()) { 6190 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6191 pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0]; 6192 } else { 6193 // This is the case where the app has no native code. 6194 pkg.applicationInfo.cpuAbi = null; 6195 pkgSetting.cpuAbiString = null; 6196 } 6197 } 6198 6199 private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle, 6200 final File nativeLibraryDir, String[] abiList) throws IOException { 6201 if (!nativeLibraryDir.isDirectory()) { 6202 nativeLibraryDir.delete(); 6203 6204 if (!nativeLibraryDir.mkdir()) { 6205 throw new IOException("Cannot create " + nativeLibraryDir.getPath()); 6206 } 6207 6208 try { 6209 Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6210 } catch (ErrnoException e) { 6211 throw new IOException("Cannot chmod native library directory " 6212 + nativeLibraryDir.getPath(), e); 6213 } 6214 } else if (!SELinux.restorecon(nativeLibraryDir)) { 6215 throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath()); 6216 } 6217 6218 /* 6219 * If this is an internal application or our nativeLibraryPath points to 6220 * the app-lib directory, unpack the libraries if necessary. 6221 */ 6222 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6223 if (abi >= 0) { 6224 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, 6225 nativeLibraryDir, Build.SUPPORTED_ABIS[abi]); 6226 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6227 return copyRet; 6228 } 6229 } 6230 6231 return abi; 6232 } 6233 6234 private void killApplication(String pkgName, int appId, String reason) { 6235 // Request the ActivityManager to kill the process(only for existing packages) 6236 // so that we do not end up in a confused state while the user is still using the older 6237 // version of the application while the new one gets installed. 6238 IActivityManager am = ActivityManagerNative.getDefault(); 6239 if (am != null) { 6240 try { 6241 am.killApplicationWithAppId(pkgName, appId, reason); 6242 } catch (RemoteException e) { 6243 } 6244 } 6245 } 6246 6247 void removePackageLI(PackageSetting ps, boolean chatty) { 6248 if (DEBUG_INSTALL) { 6249 if (chatty) 6250 Log.d(TAG, "Removing package " + ps.name); 6251 } 6252 6253 // writer 6254 synchronized (mPackages) { 6255 mPackages.remove(ps.name); 6256 if (ps.codePathString != null) { 6257 mAppDirs.remove(ps.codePathString); 6258 } 6259 6260 final PackageParser.Package pkg = ps.pkg; 6261 if (pkg != null) { 6262 cleanPackageDataStructuresLILPw(pkg, chatty); 6263 } 6264 } 6265 } 6266 6267 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6268 if (DEBUG_INSTALL) { 6269 if (chatty) 6270 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6271 } 6272 6273 // writer 6274 synchronized (mPackages) { 6275 mPackages.remove(pkg.applicationInfo.packageName); 6276 if (pkg.codePath != null) { 6277 mAppDirs.remove(pkg.codePath); 6278 } 6279 cleanPackageDataStructuresLILPw(pkg, chatty); 6280 } 6281 } 6282 6283 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6284 int N = pkg.providers.size(); 6285 StringBuilder r = null; 6286 int i; 6287 for (i=0; i<N; i++) { 6288 PackageParser.Provider p = pkg.providers.get(i); 6289 mProviders.removeProvider(p); 6290 if (p.info.authority == null) { 6291 6292 /* There was another ContentProvider with this authority when 6293 * this app was installed so this authority is null, 6294 * Ignore it as we don't have to unregister the provider. 6295 */ 6296 continue; 6297 } 6298 String names[] = p.info.authority.split(";"); 6299 for (int j = 0; j < names.length; j++) { 6300 if (mProvidersByAuthority.get(names[j]) == p) { 6301 mProvidersByAuthority.remove(names[j]); 6302 if (DEBUG_REMOVE) { 6303 if (chatty) 6304 Log.d(TAG, "Unregistered content provider: " + names[j] 6305 + ", className = " + p.info.name + ", isSyncable = " 6306 + p.info.isSyncable); 6307 } 6308 } 6309 } 6310 if (DEBUG_REMOVE && chatty) { 6311 if (r == null) { 6312 r = new StringBuilder(256); 6313 } else { 6314 r.append(' '); 6315 } 6316 r.append(p.info.name); 6317 } 6318 } 6319 if (r != null) { 6320 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6321 } 6322 6323 N = pkg.services.size(); 6324 r = null; 6325 for (i=0; i<N; i++) { 6326 PackageParser.Service s = pkg.services.get(i); 6327 mServices.removeService(s); 6328 if (chatty) { 6329 if (r == null) { 6330 r = new StringBuilder(256); 6331 } else { 6332 r.append(' '); 6333 } 6334 r.append(s.info.name); 6335 } 6336 } 6337 if (r != null) { 6338 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6339 } 6340 6341 N = pkg.receivers.size(); 6342 r = null; 6343 for (i=0; i<N; i++) { 6344 PackageParser.Activity a = pkg.receivers.get(i); 6345 mReceivers.removeActivity(a, "receiver"); 6346 if (DEBUG_REMOVE && chatty) { 6347 if (r == null) { 6348 r = new StringBuilder(256); 6349 } else { 6350 r.append(' '); 6351 } 6352 r.append(a.info.name); 6353 } 6354 } 6355 if (r != null) { 6356 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6357 } 6358 6359 N = pkg.activities.size(); 6360 r = null; 6361 for (i=0; i<N; i++) { 6362 PackageParser.Activity a = pkg.activities.get(i); 6363 mActivities.removeActivity(a, "activity"); 6364 if (DEBUG_REMOVE && chatty) { 6365 if (r == null) { 6366 r = new StringBuilder(256); 6367 } else { 6368 r.append(' '); 6369 } 6370 r.append(a.info.name); 6371 } 6372 } 6373 if (r != null) { 6374 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6375 } 6376 6377 N = pkg.permissions.size(); 6378 r = null; 6379 for (i=0; i<N; i++) { 6380 PackageParser.Permission p = pkg.permissions.get(i); 6381 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6382 if (bp == null) { 6383 bp = mSettings.mPermissionTrees.get(p.info.name); 6384 } 6385 if (bp != null && bp.perm == p) { 6386 bp.perm = null; 6387 if (DEBUG_REMOVE && chatty) { 6388 if (r == null) { 6389 r = new StringBuilder(256); 6390 } else { 6391 r.append(' '); 6392 } 6393 r.append(p.info.name); 6394 } 6395 } 6396 } 6397 if (r != null) { 6398 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6399 } 6400 6401 N = pkg.instrumentation.size(); 6402 r = null; 6403 for (i=0; i<N; i++) { 6404 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6405 mInstrumentation.remove(a.getComponentName()); 6406 if (DEBUG_REMOVE && chatty) { 6407 if (r == null) { 6408 r = new StringBuilder(256); 6409 } else { 6410 r.append(' '); 6411 } 6412 r.append(a.info.name); 6413 } 6414 } 6415 if (r != null) { 6416 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6417 } 6418 6419 r = null; 6420 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6421 // Only system apps can hold shared libraries. 6422 if (pkg.libraryNames != null) { 6423 for (i=0; i<pkg.libraryNames.size(); i++) { 6424 String name = pkg.libraryNames.get(i); 6425 SharedLibraryEntry cur = mSharedLibraries.get(name); 6426 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6427 mSharedLibraries.remove(name); 6428 if (DEBUG_REMOVE && chatty) { 6429 if (r == null) { 6430 r = new StringBuilder(256); 6431 } else { 6432 r.append(' '); 6433 } 6434 r.append(name); 6435 } 6436 } 6437 } 6438 } 6439 } 6440 if (r != null) { 6441 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6442 } 6443 } 6444 6445 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6446 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6447 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6448 return true; 6449 } 6450 } 6451 return false; 6452 } 6453 6454 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6455 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6456 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6457 6458 private void updatePermissionsLPw(String changingPkg, 6459 PackageParser.Package pkgInfo, int flags) { 6460 // Make sure there are no dangling permission trees. 6461 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6462 while (it.hasNext()) { 6463 final BasePermission bp = it.next(); 6464 if (bp.packageSetting == null) { 6465 // We may not yet have parsed the package, so just see if 6466 // we still know about its settings. 6467 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6468 } 6469 if (bp.packageSetting == null) { 6470 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6471 + " from package " + bp.sourcePackage); 6472 it.remove(); 6473 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6474 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6475 Slog.i(TAG, "Removing old permission tree: " + bp.name 6476 + " from package " + bp.sourcePackage); 6477 flags |= UPDATE_PERMISSIONS_ALL; 6478 it.remove(); 6479 } 6480 } 6481 } 6482 6483 // Make sure all dynamic permissions have been assigned to a package, 6484 // and make sure there are no dangling permissions. 6485 it = mSettings.mPermissions.values().iterator(); 6486 while (it.hasNext()) { 6487 final BasePermission bp = it.next(); 6488 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6489 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6490 + bp.name + " pkg=" + bp.sourcePackage 6491 + " info=" + bp.pendingInfo); 6492 if (bp.packageSetting == null && bp.pendingInfo != null) { 6493 final BasePermission tree = findPermissionTreeLP(bp.name); 6494 if (tree != null && tree.perm != null) { 6495 bp.packageSetting = tree.packageSetting; 6496 bp.perm = new PackageParser.Permission(tree.perm.owner, 6497 new PermissionInfo(bp.pendingInfo)); 6498 bp.perm.info.packageName = tree.perm.info.packageName; 6499 bp.perm.info.name = bp.name; 6500 bp.uid = tree.uid; 6501 } 6502 } 6503 } 6504 if (bp.packageSetting == null) { 6505 // We may not yet have parsed the package, so just see if 6506 // we still know about its settings. 6507 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6508 } 6509 if (bp.packageSetting == null) { 6510 Slog.w(TAG, "Removing dangling permission: " + bp.name 6511 + " from package " + bp.sourcePackage); 6512 it.remove(); 6513 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6514 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6515 Slog.i(TAG, "Removing old permission: " + bp.name 6516 + " from package " + bp.sourcePackage); 6517 flags |= UPDATE_PERMISSIONS_ALL; 6518 it.remove(); 6519 } 6520 } 6521 } 6522 6523 // Now update the permissions for all packages, in particular 6524 // replace the granted permissions of the system packages. 6525 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6526 for (PackageParser.Package pkg : mPackages.values()) { 6527 if (pkg != pkgInfo) { 6528 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6529 } 6530 } 6531 } 6532 6533 if (pkgInfo != null) { 6534 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6535 } 6536 } 6537 6538 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6539 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6540 if (ps == null) { 6541 return; 6542 } 6543 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6544 HashSet<String> origPermissions = gp.grantedPermissions; 6545 boolean changedPermission = false; 6546 6547 if (replace) { 6548 ps.permissionsFixed = false; 6549 if (gp == ps) { 6550 origPermissions = new HashSet<String>(gp.grantedPermissions); 6551 gp.grantedPermissions.clear(); 6552 gp.gids = mGlobalGids; 6553 } 6554 } 6555 6556 if (gp.gids == null) { 6557 gp.gids = mGlobalGids; 6558 } 6559 6560 final int N = pkg.requestedPermissions.size(); 6561 for (int i=0; i<N; i++) { 6562 final String name = pkg.requestedPermissions.get(i); 6563 final boolean required = pkg.requestedPermissionsRequired.get(i); 6564 final BasePermission bp = mSettings.mPermissions.get(name); 6565 if (DEBUG_INSTALL) { 6566 if (gp != ps) { 6567 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6568 } 6569 } 6570 6571 if (bp == null || bp.packageSetting == null) { 6572 Slog.w(TAG, "Unknown permission " + name 6573 + " in package " + pkg.packageName); 6574 continue; 6575 } 6576 6577 final String perm = bp.name; 6578 boolean allowed; 6579 boolean allowedSig = false; 6580 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6581 if (level == PermissionInfo.PROTECTION_NORMAL 6582 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6583 // We grant a normal or dangerous permission if any of the following 6584 // are true: 6585 // 1) The permission is required 6586 // 2) The permission is optional, but was granted in the past 6587 // 3) The permission is optional, but was requested by an 6588 // app in /system (not /data) 6589 // 6590 // Otherwise, reject the permission. 6591 allowed = (required || origPermissions.contains(perm) 6592 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6593 } else if (bp.packageSetting == null) { 6594 // This permission is invalid; skip it. 6595 allowed = false; 6596 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6597 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6598 if (allowed) { 6599 allowedSig = true; 6600 } 6601 } else { 6602 allowed = false; 6603 } 6604 if (DEBUG_INSTALL) { 6605 if (gp != ps) { 6606 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6607 } 6608 } 6609 if (allowed) { 6610 if (!isSystemApp(ps) && ps.permissionsFixed) { 6611 // If this is an existing, non-system package, then 6612 // we can't add any new permissions to it. 6613 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6614 // Except... if this is a permission that was added 6615 // to the platform (note: need to only do this when 6616 // updating the platform). 6617 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6618 } 6619 } 6620 if (allowed) { 6621 if (!gp.grantedPermissions.contains(perm)) { 6622 changedPermission = true; 6623 gp.grantedPermissions.add(perm); 6624 gp.gids = appendInts(gp.gids, bp.gids); 6625 } else if (!ps.haveGids) { 6626 gp.gids = appendInts(gp.gids, bp.gids); 6627 } 6628 } else { 6629 Slog.w(TAG, "Not granting permission " + perm 6630 + " to package " + pkg.packageName 6631 + " because it was previously installed without"); 6632 } 6633 } else { 6634 if (gp.grantedPermissions.remove(perm)) { 6635 changedPermission = true; 6636 gp.gids = removeInts(gp.gids, bp.gids); 6637 Slog.i(TAG, "Un-granting permission " + perm 6638 + " from package " + pkg.packageName 6639 + " (protectionLevel=" + bp.protectionLevel 6640 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6641 + ")"); 6642 } else { 6643 Slog.w(TAG, "Not granting permission " + perm 6644 + " to package " + pkg.packageName 6645 + " (protectionLevel=" + bp.protectionLevel 6646 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6647 + ")"); 6648 } 6649 } 6650 } 6651 6652 if ((changedPermission || replace) && !ps.permissionsFixed && 6653 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6654 // This is the first that we have heard about this package, so the 6655 // permissions we have now selected are fixed until explicitly 6656 // changed. 6657 ps.permissionsFixed = true; 6658 } 6659 ps.haveGids = true; 6660 } 6661 6662 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6663 boolean allowed = false; 6664 final int NP = PackageParser.NEW_PERMISSIONS.length; 6665 for (int ip=0; ip<NP; ip++) { 6666 final PackageParser.NewPermissionInfo npi 6667 = PackageParser.NEW_PERMISSIONS[ip]; 6668 if (npi.name.equals(perm) 6669 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6670 allowed = true; 6671 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6672 + pkg.packageName); 6673 break; 6674 } 6675 } 6676 return allowed; 6677 } 6678 6679 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6680 BasePermission bp, HashSet<String> origPermissions) { 6681 boolean allowed; 6682 allowed = (compareSignatures( 6683 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6684 == PackageManager.SIGNATURE_MATCH) 6685 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6686 == PackageManager.SIGNATURE_MATCH); 6687 if (!allowed && (bp.protectionLevel 6688 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6689 if (isSystemApp(pkg)) { 6690 // For updated system applications, a system permission 6691 // is granted only if it had been defined by the original application. 6692 if (isUpdatedSystemApp(pkg)) { 6693 final PackageSetting sysPs = mSettings 6694 .getDisabledSystemPkgLPr(pkg.packageName); 6695 final GrantedPermissions origGp = sysPs.sharedUser != null 6696 ? sysPs.sharedUser : sysPs; 6697 6698 if (origGp.grantedPermissions.contains(perm)) { 6699 // If the original was granted this permission, we take 6700 // that grant decision as read and propagate it to the 6701 // update. 6702 allowed = true; 6703 } else { 6704 // The system apk may have been updated with an older 6705 // version of the one on the data partition, but which 6706 // granted a new system permission that it didn't have 6707 // before. In this case we do want to allow the app to 6708 // now get the new permission if the ancestral apk is 6709 // privileged to get it. 6710 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6711 for (int j=0; 6712 j<sysPs.pkg.requestedPermissions.size(); j++) { 6713 if (perm.equals( 6714 sysPs.pkg.requestedPermissions.get(j))) { 6715 allowed = true; 6716 break; 6717 } 6718 } 6719 } 6720 } 6721 } else { 6722 allowed = isPrivilegedApp(pkg); 6723 } 6724 } 6725 } 6726 if (!allowed && (bp.protectionLevel 6727 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6728 // For development permissions, a development permission 6729 // is granted only if it was already granted. 6730 allowed = origPermissions.contains(perm); 6731 } 6732 return allowed; 6733 } 6734 6735 final class ActivityIntentResolver 6736 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6737 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6738 boolean defaultOnly, int userId) { 6739 if (!sUserManager.exists(userId)) return null; 6740 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6741 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6742 } 6743 6744 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6745 int userId) { 6746 if (!sUserManager.exists(userId)) return null; 6747 mFlags = flags; 6748 return super.queryIntent(intent, resolvedType, 6749 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6750 } 6751 6752 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6753 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6754 if (!sUserManager.exists(userId)) return null; 6755 if (packageActivities == null) { 6756 return null; 6757 } 6758 mFlags = flags; 6759 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6760 final int N = packageActivities.size(); 6761 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6762 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6763 6764 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6765 for (int i = 0; i < N; ++i) { 6766 intentFilters = packageActivities.get(i).intents; 6767 if (intentFilters != null && intentFilters.size() > 0) { 6768 PackageParser.ActivityIntentInfo[] array = 6769 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6770 intentFilters.toArray(array); 6771 listCut.add(array); 6772 } 6773 } 6774 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6775 } 6776 6777 public final void addActivity(PackageParser.Activity a, String type) { 6778 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6779 mActivities.put(a.getComponentName(), a); 6780 if (DEBUG_SHOW_INFO) 6781 Log.v( 6782 TAG, " " + type + " " + 6783 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6784 if (DEBUG_SHOW_INFO) 6785 Log.v(TAG, " Class=" + a.info.name); 6786 final int NI = a.intents.size(); 6787 for (int j=0; j<NI; j++) { 6788 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6789 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6790 intent.setPriority(0); 6791 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6792 + a.className + " with priority > 0, forcing to 0"); 6793 } 6794 if (DEBUG_SHOW_INFO) { 6795 Log.v(TAG, " IntentFilter:"); 6796 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6797 } 6798 if (!intent.debugCheck()) { 6799 Log.w(TAG, "==> For Activity " + a.info.name); 6800 } 6801 addFilter(intent); 6802 } 6803 } 6804 6805 public final void removeActivity(PackageParser.Activity a, String type) { 6806 mActivities.remove(a.getComponentName()); 6807 if (DEBUG_SHOW_INFO) { 6808 Log.v(TAG, " " + type + " " 6809 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6810 : a.info.name) + ":"); 6811 Log.v(TAG, " Class=" + a.info.name); 6812 } 6813 final int NI = a.intents.size(); 6814 for (int j=0; j<NI; j++) { 6815 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6816 if (DEBUG_SHOW_INFO) { 6817 Log.v(TAG, " IntentFilter:"); 6818 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6819 } 6820 removeFilter(intent); 6821 } 6822 } 6823 6824 @Override 6825 protected boolean allowFilterResult( 6826 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 6827 ActivityInfo filterAi = filter.activity.info; 6828 for (int i=dest.size()-1; i>=0; i--) { 6829 ActivityInfo destAi = dest.get(i).activityInfo; 6830 if (destAi.name == filterAi.name 6831 && destAi.packageName == filterAi.packageName) { 6832 return false; 6833 } 6834 } 6835 return true; 6836 } 6837 6838 @Override 6839 protected ActivityIntentInfo[] newArray(int size) { 6840 return new ActivityIntentInfo[size]; 6841 } 6842 6843 @Override 6844 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 6845 if (!sUserManager.exists(userId)) return true; 6846 PackageParser.Package p = filter.activity.owner; 6847 if (p != null) { 6848 PackageSetting ps = (PackageSetting)p.mExtras; 6849 if (ps != null) { 6850 // System apps are never considered stopped for purposes of 6851 // filtering, because there may be no way for the user to 6852 // actually re-launch them. 6853 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 6854 && ps.getStopped(userId); 6855 } 6856 } 6857 return false; 6858 } 6859 6860 @Override 6861 protected boolean isPackageForFilter(String packageName, 6862 PackageParser.ActivityIntentInfo info) { 6863 return packageName.equals(info.activity.owner.packageName); 6864 } 6865 6866 @Override 6867 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 6868 int match, int userId) { 6869 if (!sUserManager.exists(userId)) return null; 6870 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 6871 return null; 6872 } 6873 final PackageParser.Activity activity = info.activity; 6874 if (mSafeMode && (activity.info.applicationInfo.flags 6875 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6876 return null; 6877 } 6878 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 6879 if (ps == null) { 6880 return null; 6881 } 6882 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 6883 ps.readUserState(userId), userId); 6884 if (ai == null) { 6885 return null; 6886 } 6887 final ResolveInfo res = new ResolveInfo(); 6888 res.activityInfo = ai; 6889 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 6890 res.filter = info; 6891 } 6892 res.priority = info.getPriority(); 6893 res.preferredOrder = activity.owner.mPreferredOrder; 6894 //System.out.println("Result: " + res.activityInfo.className + 6895 // " = " + res.priority); 6896 res.match = match; 6897 res.isDefault = info.hasDefault; 6898 res.labelRes = info.labelRes; 6899 res.nonLocalizedLabel = info.nonLocalizedLabel; 6900 if (userNeedsBadging(userId)) { 6901 res.noResourceId = true; 6902 } else { 6903 res.icon = info.icon; 6904 } 6905 res.system = isSystemApp(res.activityInfo.applicationInfo); 6906 return res; 6907 } 6908 6909 @Override 6910 protected void sortResults(List<ResolveInfo> results) { 6911 Collections.sort(results, mResolvePrioritySorter); 6912 } 6913 6914 @Override 6915 protected void dumpFilter(PrintWriter out, String prefix, 6916 PackageParser.ActivityIntentInfo filter) { 6917 out.print(prefix); out.print( 6918 Integer.toHexString(System.identityHashCode(filter.activity))); 6919 out.print(' '); 6920 filter.activity.printComponentShortName(out); 6921 out.print(" filter "); 6922 out.println(Integer.toHexString(System.identityHashCode(filter))); 6923 } 6924 6925// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 6926// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 6927// final List<ResolveInfo> retList = Lists.newArrayList(); 6928// while (i.hasNext()) { 6929// final ResolveInfo resolveInfo = i.next(); 6930// if (isEnabledLP(resolveInfo.activityInfo)) { 6931// retList.add(resolveInfo); 6932// } 6933// } 6934// return retList; 6935// } 6936 6937 // Keys are String (activity class name), values are Activity. 6938 private final HashMap<ComponentName, PackageParser.Activity> mActivities 6939 = new HashMap<ComponentName, PackageParser.Activity>(); 6940 private int mFlags; 6941 } 6942 6943 private final class ServiceIntentResolver 6944 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 6945 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6946 boolean defaultOnly, int userId) { 6947 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6948 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6949 } 6950 6951 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6952 int userId) { 6953 if (!sUserManager.exists(userId)) return null; 6954 mFlags = flags; 6955 return super.queryIntent(intent, resolvedType, 6956 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6957 } 6958 6959 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6960 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 6961 if (!sUserManager.exists(userId)) return null; 6962 if (packageServices == null) { 6963 return null; 6964 } 6965 mFlags = flags; 6966 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6967 final int N = packageServices.size(); 6968 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 6969 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 6970 6971 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 6972 for (int i = 0; i < N; ++i) { 6973 intentFilters = packageServices.get(i).intents; 6974 if (intentFilters != null && intentFilters.size() > 0) { 6975 PackageParser.ServiceIntentInfo[] array = 6976 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 6977 intentFilters.toArray(array); 6978 listCut.add(array); 6979 } 6980 } 6981 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6982 } 6983 6984 public final void addService(PackageParser.Service s) { 6985 mServices.put(s.getComponentName(), s); 6986 if (DEBUG_SHOW_INFO) { 6987 Log.v(TAG, " " 6988 + (s.info.nonLocalizedLabel != null 6989 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6990 Log.v(TAG, " Class=" + s.info.name); 6991 } 6992 final int NI = s.intents.size(); 6993 int j; 6994 for (j=0; j<NI; j++) { 6995 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6996 if (DEBUG_SHOW_INFO) { 6997 Log.v(TAG, " IntentFilter:"); 6998 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6999 } 7000 if (!intent.debugCheck()) { 7001 Log.w(TAG, "==> For Service " + s.info.name); 7002 } 7003 addFilter(intent); 7004 } 7005 } 7006 7007 public final void removeService(PackageParser.Service s) { 7008 mServices.remove(s.getComponentName()); 7009 if (DEBUG_SHOW_INFO) { 7010 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7011 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7012 Log.v(TAG, " Class=" + s.info.name); 7013 } 7014 final int NI = s.intents.size(); 7015 int j; 7016 for (j=0; j<NI; j++) { 7017 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7018 if (DEBUG_SHOW_INFO) { 7019 Log.v(TAG, " IntentFilter:"); 7020 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7021 } 7022 removeFilter(intent); 7023 } 7024 } 7025 7026 @Override 7027 protected boolean allowFilterResult( 7028 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7029 ServiceInfo filterSi = filter.service.info; 7030 for (int i=dest.size()-1; i>=0; i--) { 7031 ServiceInfo destAi = dest.get(i).serviceInfo; 7032 if (destAi.name == filterSi.name 7033 && destAi.packageName == filterSi.packageName) { 7034 return false; 7035 } 7036 } 7037 return true; 7038 } 7039 7040 @Override 7041 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7042 return new PackageParser.ServiceIntentInfo[size]; 7043 } 7044 7045 @Override 7046 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7047 if (!sUserManager.exists(userId)) return true; 7048 PackageParser.Package p = filter.service.owner; 7049 if (p != null) { 7050 PackageSetting ps = (PackageSetting)p.mExtras; 7051 if (ps != null) { 7052 // System apps are never considered stopped for purposes of 7053 // filtering, because there may be no way for the user to 7054 // actually re-launch them. 7055 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7056 && ps.getStopped(userId); 7057 } 7058 } 7059 return false; 7060 } 7061 7062 @Override 7063 protected boolean isPackageForFilter(String packageName, 7064 PackageParser.ServiceIntentInfo info) { 7065 return packageName.equals(info.service.owner.packageName); 7066 } 7067 7068 @Override 7069 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7070 int match, int userId) { 7071 if (!sUserManager.exists(userId)) return null; 7072 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7073 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7074 return null; 7075 } 7076 final PackageParser.Service service = info.service; 7077 if (mSafeMode && (service.info.applicationInfo.flags 7078 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7079 return null; 7080 } 7081 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7082 if (ps == null) { 7083 return null; 7084 } 7085 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7086 ps.readUserState(userId), userId); 7087 if (si == null) { 7088 return null; 7089 } 7090 final ResolveInfo res = new ResolveInfo(); 7091 res.serviceInfo = si; 7092 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7093 res.filter = filter; 7094 } 7095 res.priority = info.getPriority(); 7096 res.preferredOrder = service.owner.mPreferredOrder; 7097 //System.out.println("Result: " + res.activityInfo.className + 7098 // " = " + res.priority); 7099 res.match = match; 7100 res.isDefault = info.hasDefault; 7101 res.labelRes = info.labelRes; 7102 res.nonLocalizedLabel = info.nonLocalizedLabel; 7103 res.icon = info.icon; 7104 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7105 return res; 7106 } 7107 7108 @Override 7109 protected void sortResults(List<ResolveInfo> results) { 7110 Collections.sort(results, mResolvePrioritySorter); 7111 } 7112 7113 @Override 7114 protected void dumpFilter(PrintWriter out, String prefix, 7115 PackageParser.ServiceIntentInfo filter) { 7116 out.print(prefix); out.print( 7117 Integer.toHexString(System.identityHashCode(filter.service))); 7118 out.print(' '); 7119 filter.service.printComponentShortName(out); 7120 out.print(" filter "); 7121 out.println(Integer.toHexString(System.identityHashCode(filter))); 7122 } 7123 7124// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7125// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7126// final List<ResolveInfo> retList = Lists.newArrayList(); 7127// while (i.hasNext()) { 7128// final ResolveInfo resolveInfo = (ResolveInfo) i; 7129// if (isEnabledLP(resolveInfo.serviceInfo)) { 7130// retList.add(resolveInfo); 7131// } 7132// } 7133// return retList; 7134// } 7135 7136 // Keys are String (activity class name), values are Activity. 7137 private final HashMap<ComponentName, PackageParser.Service> mServices 7138 = new HashMap<ComponentName, PackageParser.Service>(); 7139 private int mFlags; 7140 }; 7141 7142 private final class ProviderIntentResolver 7143 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7144 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7145 boolean defaultOnly, int userId) { 7146 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7147 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7148 } 7149 7150 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7151 int userId) { 7152 if (!sUserManager.exists(userId)) 7153 return null; 7154 mFlags = flags; 7155 return super.queryIntent(intent, resolvedType, 7156 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7157 } 7158 7159 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7160 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7161 if (!sUserManager.exists(userId)) 7162 return null; 7163 if (packageProviders == null) { 7164 return null; 7165 } 7166 mFlags = flags; 7167 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7168 final int N = packageProviders.size(); 7169 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7170 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7171 7172 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7173 for (int i = 0; i < N; ++i) { 7174 intentFilters = packageProviders.get(i).intents; 7175 if (intentFilters != null && intentFilters.size() > 0) { 7176 PackageParser.ProviderIntentInfo[] array = 7177 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7178 intentFilters.toArray(array); 7179 listCut.add(array); 7180 } 7181 } 7182 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7183 } 7184 7185 public final void addProvider(PackageParser.Provider p) { 7186 if (mProviders.containsKey(p.getComponentName())) { 7187 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7188 return; 7189 } 7190 7191 mProviders.put(p.getComponentName(), p); 7192 if (DEBUG_SHOW_INFO) { 7193 Log.v(TAG, " " 7194 + (p.info.nonLocalizedLabel != null 7195 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7196 Log.v(TAG, " Class=" + p.info.name); 7197 } 7198 final int NI = p.intents.size(); 7199 int j; 7200 for (j = 0; j < NI; j++) { 7201 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7202 if (DEBUG_SHOW_INFO) { 7203 Log.v(TAG, " IntentFilter:"); 7204 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7205 } 7206 if (!intent.debugCheck()) { 7207 Log.w(TAG, "==> For Provider " + p.info.name); 7208 } 7209 addFilter(intent); 7210 } 7211 } 7212 7213 public final void removeProvider(PackageParser.Provider p) { 7214 mProviders.remove(p.getComponentName()); 7215 if (DEBUG_SHOW_INFO) { 7216 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7217 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7218 Log.v(TAG, " Class=" + p.info.name); 7219 } 7220 final int NI = p.intents.size(); 7221 int j; 7222 for (j = 0; j < NI; j++) { 7223 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7224 if (DEBUG_SHOW_INFO) { 7225 Log.v(TAG, " IntentFilter:"); 7226 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7227 } 7228 removeFilter(intent); 7229 } 7230 } 7231 7232 @Override 7233 protected boolean allowFilterResult( 7234 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7235 ProviderInfo filterPi = filter.provider.info; 7236 for (int i = dest.size() - 1; i >= 0; i--) { 7237 ProviderInfo destPi = dest.get(i).providerInfo; 7238 if (destPi.name == filterPi.name 7239 && destPi.packageName == filterPi.packageName) { 7240 return false; 7241 } 7242 } 7243 return true; 7244 } 7245 7246 @Override 7247 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7248 return new PackageParser.ProviderIntentInfo[size]; 7249 } 7250 7251 @Override 7252 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7253 if (!sUserManager.exists(userId)) 7254 return true; 7255 PackageParser.Package p = filter.provider.owner; 7256 if (p != null) { 7257 PackageSetting ps = (PackageSetting) p.mExtras; 7258 if (ps != null) { 7259 // System apps are never considered stopped for purposes of 7260 // filtering, because there may be no way for the user to 7261 // actually re-launch them. 7262 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7263 && ps.getStopped(userId); 7264 } 7265 } 7266 return false; 7267 } 7268 7269 @Override 7270 protected boolean isPackageForFilter(String packageName, 7271 PackageParser.ProviderIntentInfo info) { 7272 return packageName.equals(info.provider.owner.packageName); 7273 } 7274 7275 @Override 7276 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7277 int match, int userId) { 7278 if (!sUserManager.exists(userId)) 7279 return null; 7280 final PackageParser.ProviderIntentInfo info = filter; 7281 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7282 return null; 7283 } 7284 final PackageParser.Provider provider = info.provider; 7285 if (mSafeMode && (provider.info.applicationInfo.flags 7286 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7287 return null; 7288 } 7289 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7290 if (ps == null) { 7291 return null; 7292 } 7293 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7294 ps.readUserState(userId), userId); 7295 if (pi == null) { 7296 return null; 7297 } 7298 final ResolveInfo res = new ResolveInfo(); 7299 res.providerInfo = pi; 7300 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7301 res.filter = filter; 7302 } 7303 res.priority = info.getPriority(); 7304 res.preferredOrder = provider.owner.mPreferredOrder; 7305 res.match = match; 7306 res.isDefault = info.hasDefault; 7307 res.labelRes = info.labelRes; 7308 res.nonLocalizedLabel = info.nonLocalizedLabel; 7309 res.icon = info.icon; 7310 res.system = isSystemApp(res.providerInfo.applicationInfo); 7311 return res; 7312 } 7313 7314 @Override 7315 protected void sortResults(List<ResolveInfo> results) { 7316 Collections.sort(results, mResolvePrioritySorter); 7317 } 7318 7319 @Override 7320 protected void dumpFilter(PrintWriter out, String prefix, 7321 PackageParser.ProviderIntentInfo filter) { 7322 out.print(prefix); 7323 out.print( 7324 Integer.toHexString(System.identityHashCode(filter.provider))); 7325 out.print(' '); 7326 filter.provider.printComponentShortName(out); 7327 out.print(" filter "); 7328 out.println(Integer.toHexString(System.identityHashCode(filter))); 7329 } 7330 7331 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7332 = new HashMap<ComponentName, PackageParser.Provider>(); 7333 private int mFlags; 7334 }; 7335 7336 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7337 new Comparator<ResolveInfo>() { 7338 public int compare(ResolveInfo r1, ResolveInfo r2) { 7339 int v1 = r1.priority; 7340 int v2 = r2.priority; 7341 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7342 if (v1 != v2) { 7343 return (v1 > v2) ? -1 : 1; 7344 } 7345 v1 = r1.preferredOrder; 7346 v2 = r2.preferredOrder; 7347 if (v1 != v2) { 7348 return (v1 > v2) ? -1 : 1; 7349 } 7350 if (r1.isDefault != r2.isDefault) { 7351 return r1.isDefault ? -1 : 1; 7352 } 7353 v1 = r1.match; 7354 v2 = r2.match; 7355 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7356 if (v1 != v2) { 7357 return (v1 > v2) ? -1 : 1; 7358 } 7359 if (r1.system != r2.system) { 7360 return r1.system ? -1 : 1; 7361 } 7362 return 0; 7363 } 7364 }; 7365 7366 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7367 new Comparator<ProviderInfo>() { 7368 public int compare(ProviderInfo p1, ProviderInfo p2) { 7369 final int v1 = p1.initOrder; 7370 final int v2 = p2.initOrder; 7371 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7372 } 7373 }; 7374 7375 static final void sendPackageBroadcast(String action, String pkg, 7376 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7377 int[] userIds) { 7378 IActivityManager am = ActivityManagerNative.getDefault(); 7379 if (am != null) { 7380 try { 7381 if (userIds == null) { 7382 userIds = am.getRunningUserIds(); 7383 } 7384 for (int id : userIds) { 7385 final Intent intent = new Intent(action, 7386 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7387 if (extras != null) { 7388 intent.putExtras(extras); 7389 } 7390 if (targetPkg != null) { 7391 intent.setPackage(targetPkg); 7392 } 7393 // Modify the UID when posting to other users 7394 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7395 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7396 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7397 intent.putExtra(Intent.EXTRA_UID, uid); 7398 } 7399 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7400 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7401 if (DEBUG_BROADCASTS) { 7402 RuntimeException here = new RuntimeException("here"); 7403 here.fillInStackTrace(); 7404 Slog.d(TAG, "Sending to user " + id + ": " 7405 + intent.toShortString(false, true, false, false) 7406 + " " + intent.getExtras(), here); 7407 } 7408 am.broadcastIntent(null, intent, null, finishedReceiver, 7409 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7410 finishedReceiver != null, false, id); 7411 } 7412 } catch (RemoteException ex) { 7413 } 7414 } 7415 } 7416 7417 /** 7418 * Check if the external storage media is available. This is true if there 7419 * is a mounted external storage medium or if the external storage is 7420 * emulated. 7421 */ 7422 private boolean isExternalMediaAvailable() { 7423 return mMediaMounted || Environment.isExternalStorageEmulated(); 7424 } 7425 7426 @Override 7427 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7428 // writer 7429 synchronized (mPackages) { 7430 if (!isExternalMediaAvailable()) { 7431 // If the external storage is no longer mounted at this point, 7432 // the caller may not have been able to delete all of this 7433 // packages files and can not delete any more. Bail. 7434 return null; 7435 } 7436 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7437 if (lastPackage != null) { 7438 pkgs.remove(lastPackage); 7439 } 7440 if (pkgs.size() > 0) { 7441 return pkgs.get(0); 7442 } 7443 } 7444 return null; 7445 } 7446 7447 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7448 if (false) { 7449 RuntimeException here = new RuntimeException("here"); 7450 here.fillInStackTrace(); 7451 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7452 + " andCode=" + andCode, here); 7453 } 7454 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7455 userId, andCode ? 1 : 0, packageName)); 7456 } 7457 7458 void startCleaningPackages() { 7459 // reader 7460 synchronized (mPackages) { 7461 if (!isExternalMediaAvailable()) { 7462 return; 7463 } 7464 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7465 return; 7466 } 7467 } 7468 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7469 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7470 IActivityManager am = ActivityManagerNative.getDefault(); 7471 if (am != null) { 7472 try { 7473 am.startService(null, intent, null, UserHandle.USER_OWNER); 7474 } catch (RemoteException e) { 7475 } 7476 } 7477 } 7478 7479 private final class AppDirObserver extends FileObserver { 7480 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 7481 super(path, mask); 7482 mRootDir = path; 7483 mIsRom = isrom; 7484 mIsPrivileged = isPrivileged; 7485 } 7486 7487 public void onEvent(int event, String path) { 7488 String removedPackage = null; 7489 int removedAppId = -1; 7490 int[] removedUsers = null; 7491 String addedPackage = null; 7492 int addedAppId = -1; 7493 int[] addedUsers = null; 7494 7495 // TODO post a message to the handler to obtain serial ordering 7496 synchronized (mInstallLock) { 7497 String fullPathStr = null; 7498 File fullPath = null; 7499 if (path != null) { 7500 fullPath = new File(mRootDir, path); 7501 fullPathStr = fullPath.getPath(); 7502 } 7503 7504 if (DEBUG_APP_DIR_OBSERVER) 7505 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 7506 7507 if (!isApkFile(fullPath)) { 7508 if (DEBUG_APP_DIR_OBSERVER) 7509 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 7510 return; 7511 } 7512 7513 // Ignore packages that are being installed or 7514 // have just been installed. 7515 if (ignoreCodePath(fullPathStr)) { 7516 return; 7517 } 7518 PackageParser.Package p = null; 7519 PackageSetting ps = null; 7520 // reader 7521 synchronized (mPackages) { 7522 p = mAppDirs.get(fullPathStr); 7523 if (p != null) { 7524 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 7525 if (ps != null) { 7526 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7527 } else { 7528 removedUsers = sUserManager.getUserIds(); 7529 } 7530 } 7531 addedUsers = sUserManager.getUserIds(); 7532 } 7533 if ((event&REMOVE_EVENTS) != 0) { 7534 if (ps != null) { 7535 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 7536 removePackageLI(ps, true); 7537 removedPackage = ps.name; 7538 removedAppId = ps.appId; 7539 } 7540 } 7541 7542 if ((event&ADD_EVENTS) != 0) { 7543 if (p == null) { 7544 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 7545 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 7546 if (mIsRom) { 7547 flags |= PackageParser.PARSE_IS_SYSTEM 7548 | PackageParser.PARSE_IS_SYSTEM_DIR; 7549 if (mIsPrivileged) { 7550 flags |= PackageParser.PARSE_IS_PRIVILEGED; 7551 } 7552 } 7553 p = scanPackageLI(fullPath, flags, 7554 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 7555 System.currentTimeMillis(), UserHandle.ALL, null); 7556 if (p != null) { 7557 /* 7558 * TODO this seems dangerous as the package may have 7559 * changed since we last acquired the mPackages 7560 * lock. 7561 */ 7562 // writer 7563 synchronized (mPackages) { 7564 updatePermissionsLPw(p.packageName, p, 7565 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 7566 } 7567 addedPackage = p.applicationInfo.packageName; 7568 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 7569 } 7570 } 7571 } 7572 7573 // reader 7574 synchronized (mPackages) { 7575 mSettings.writeLPr(); 7576 } 7577 } 7578 7579 if (removedPackage != null) { 7580 Bundle extras = new Bundle(1); 7581 extras.putInt(Intent.EXTRA_UID, removedAppId); 7582 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 7583 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7584 extras, null, null, removedUsers); 7585 } 7586 if (addedPackage != null) { 7587 Bundle extras = new Bundle(1); 7588 extras.putInt(Intent.EXTRA_UID, addedAppId); 7589 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 7590 extras, null, null, addedUsers); 7591 } 7592 } 7593 7594 private final String mRootDir; 7595 private final boolean mIsRom; 7596 private final boolean mIsPrivileged; 7597 } 7598 7599 /* 7600 * The old-style observer methods all just trampoline to the newer signature with 7601 * expanded install observer API. The older API continues to work but does not 7602 * supply the additional details of the Observer2 API. 7603 */ 7604 7605 /* Called when a downloaded package installation has been confirmed by the user */ 7606 public void installPackage( 7607 final Uri packageURI, final IPackageInstallObserver observer, final int flags) { 7608 installPackageEtc(packageURI, observer, null, flags, null); 7609 } 7610 7611 /* Called when a downloaded package installation has been confirmed by the user */ 7612 @Override 7613 public void installPackage( 7614 final Uri packageURI, final IPackageInstallObserver observer, final int flags, 7615 final String installerPackageName) { 7616 installPackageWithVerificationEtc(packageURI, observer, null, flags, 7617 installerPackageName, null, null, null); 7618 } 7619 7620 @Override 7621 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer, 7622 int flags, String installerPackageName, Uri verificationURI, 7623 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7624 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7625 VerificationParams.NO_UID, manifestDigest); 7626 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7627 installerPackageName, verificationParams, encryptionParams); 7628 } 7629 7630 @Override 7631 public void installPackageWithVerificationAndEncryption(Uri packageURI, 7632 IPackageInstallObserver observer, int flags, String installerPackageName, 7633 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7634 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7635 installerPackageName, verificationParams, encryptionParams); 7636 } 7637 7638 /* 7639 * And here are the "live" versions that take both observer arguments 7640 */ 7641 public void installPackageEtc( 7642 final Uri packageURI, final IPackageInstallObserver observer, 7643 IPackageInstallObserver2 observer2, final int flags) { 7644 installPackageEtc(packageURI, observer, observer2, flags, null); 7645 } 7646 7647 public void installPackageEtc( 7648 final Uri packageURI, final IPackageInstallObserver observer, 7649 final IPackageInstallObserver2 observer2, final int flags, 7650 final String installerPackageName) { 7651 installPackageWithVerificationEtc(packageURI, observer, observer2, flags, 7652 installerPackageName, null, null, null); 7653 } 7654 7655 @Override 7656 public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer, 7657 IPackageInstallObserver2 observer2, 7658 int flags, String installerPackageName, Uri verificationURI, 7659 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7660 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7661 VerificationParams.NO_UID, manifestDigest); 7662 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags, 7663 installerPackageName, verificationParams, encryptionParams); 7664 } 7665 7666 /* 7667 * All of the installPackage...*() methods redirect to this one for the master implementation 7668 */ 7669 public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI, 7670 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7671 int flags, String installerPackageName, 7672 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7673 if (observer == null && observer2 == null) { 7674 throw new IllegalArgumentException("No install observer supplied"); 7675 } 7676 installPackageWithVerificationEncryptionAndAbiOverrideEtc(packageURI, observer, observer2, 7677 flags, installerPackageName, verificationParams, encryptionParams, null); 7678 } 7679 7680 @Override 7681 public void installPackageWithVerificationEncryptionAndAbiOverrideEtc(Uri packageURI, 7682 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7683 int flags, String installerPackageName, 7684 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams, 7685 String packageAbiOverride) { 7686 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7687 null); 7688 7689 final int uid = Binder.getCallingUid(); 7690 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7691 try { 7692 if (observer != null) { 7693 observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7694 } 7695 if (observer2 != null) { 7696 observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7697 } 7698 } catch (RemoteException re) { 7699 } 7700 return; 7701 } 7702 7703 UserHandle user; 7704 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7705 user = UserHandle.ALL; 7706 } else { 7707 user = new UserHandle(UserHandle.getUserId(uid)); 7708 } 7709 7710 final int filteredFlags; 7711 7712 if (uid == Process.SHELL_UID || uid == 0) { 7713 if (DEBUG_INSTALL) { 7714 Slog.v(TAG, "Install from ADB"); 7715 } 7716 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7717 } else { 7718 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7719 } 7720 7721 verificationParams.setInstallerUid(uid); 7722 7723 if (!"file".equals(packageURI.getScheme())) { 7724 throw new UnsupportedOperationException("Only file:// URIs are supported"); 7725 } 7726 final File fromFile = new File(packageURI.getPath()); 7727 7728 if (encryptionParams != null) { 7729 throw new UnsupportedOperationException("ContainerEncryptionParams not supported"); 7730 } 7731 7732 final Message msg = mHandler.obtainMessage(INIT_COPY); 7733 msg.obj = new InstallParams(fromFile, observer, observer2, filteredFlags, 7734 installerPackageName, verificationParams, user, packageAbiOverride); 7735 mHandler.sendMessage(msg); 7736 } 7737 7738 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7739 Bundle extras = new Bundle(1); 7740 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7741 7742 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7743 packageName, extras, null, null, new int[] {userId}); 7744 try { 7745 IActivityManager am = ActivityManagerNative.getDefault(); 7746 final boolean isSystem = 7747 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7748 if (isSystem && am.isUserRunning(userId, false)) { 7749 // The just-installed/enabled app is bundled on the system, so presumed 7750 // to be able to run automatically without needing an explicit launch. 7751 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7752 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7753 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7754 .setPackage(packageName); 7755 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7756 android.app.AppOpsManager.OP_NONE, false, false, userId); 7757 } 7758 } catch (RemoteException e) { 7759 // shouldn't happen 7760 Slog.w(TAG, "Unable to bootstrap installed package", e); 7761 } 7762 } 7763 7764 @Override 7765 public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked, 7766 int userId) { 7767 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7768 PackageSetting pkgSetting; 7769 final int uid = Binder.getCallingUid(); 7770 if (UserHandle.getUserId(uid) != userId) { 7771 mContext.enforceCallingOrSelfPermission( 7772 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7773 "setApplicationBlockedSetting for user " + userId); 7774 } 7775 7776 if (blocked && isPackageDeviceAdmin(packageName, userId)) { 7777 Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin"); 7778 return false; 7779 } 7780 7781 long callingId = Binder.clearCallingIdentity(); 7782 try { 7783 boolean sendAdded = false; 7784 boolean sendRemoved = false; 7785 // writer 7786 synchronized (mPackages) { 7787 pkgSetting = mSettings.mPackages.get(packageName); 7788 if (pkgSetting == null) { 7789 return false; 7790 } 7791 if (pkgSetting.getBlocked(userId) != blocked) { 7792 pkgSetting.setBlocked(blocked, userId); 7793 mSettings.writePackageRestrictionsLPr(userId); 7794 if (blocked) { 7795 sendRemoved = true; 7796 } else { 7797 sendAdded = true; 7798 } 7799 } 7800 } 7801 if (sendAdded) { 7802 sendPackageAddedForUser(packageName, pkgSetting, userId); 7803 return true; 7804 } 7805 if (sendRemoved) { 7806 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7807 "blocking pkg"); 7808 sendPackageBlockedForUser(packageName, pkgSetting, userId); 7809 } 7810 } finally { 7811 Binder.restoreCallingIdentity(callingId); 7812 } 7813 return false; 7814 } 7815 7816 private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting, 7817 int userId) { 7818 final PackageRemovedInfo info = new PackageRemovedInfo(); 7819 info.removedPackage = packageName; 7820 info.removedUsers = new int[] {userId}; 7821 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7822 info.sendBroadcast(false, false, false); 7823 } 7824 7825 /** 7826 * Returns true if application is not found or there was an error. Otherwise it returns 7827 * the blocked state of the package for the given user. 7828 */ 7829 @Override 7830 public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) { 7831 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7832 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7833 "getApplicationBlocked for user " + userId); 7834 PackageSetting pkgSetting; 7835 long callingId = Binder.clearCallingIdentity(); 7836 try { 7837 // writer 7838 synchronized (mPackages) { 7839 pkgSetting = mSettings.mPackages.get(packageName); 7840 if (pkgSetting == null) { 7841 return true; 7842 } 7843 return pkgSetting.getBlocked(userId); 7844 } 7845 } finally { 7846 Binder.restoreCallingIdentity(callingId); 7847 } 7848 } 7849 7850 void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer2, 7851 PackageInstallerParams params, String installerPackageName, int installerUid, 7852 UserHandle user) { 7853 Slog.e(TAG, "TODO: install stage!"); 7854 try { 7855 observer2.packageInstalled(packageName, null, 7856 PackageManager.INSTALL_FAILED_INTERNAL_ERROR); 7857 } catch (RemoteException ignored) { 7858 } 7859 } 7860 7861 /** 7862 * @hide 7863 */ 7864 @Override 7865 public int installExistingPackageAsUser(String packageName, int userId) { 7866 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7867 null); 7868 PackageSetting pkgSetting; 7869 final int uid = Binder.getCallingUid(); 7870 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7871 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7872 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7873 } 7874 7875 long callingId = Binder.clearCallingIdentity(); 7876 try { 7877 boolean sendAdded = false; 7878 Bundle extras = new Bundle(1); 7879 7880 // writer 7881 synchronized (mPackages) { 7882 pkgSetting = mSettings.mPackages.get(packageName); 7883 if (pkgSetting == null) { 7884 return PackageManager.INSTALL_FAILED_INVALID_URI; 7885 } 7886 if (!pkgSetting.getInstalled(userId)) { 7887 pkgSetting.setInstalled(true, userId); 7888 pkgSetting.setBlocked(false, userId); 7889 mSettings.writePackageRestrictionsLPr(userId); 7890 sendAdded = true; 7891 } 7892 } 7893 7894 if (sendAdded) { 7895 sendPackageAddedForUser(packageName, pkgSetting, userId); 7896 } 7897 } finally { 7898 Binder.restoreCallingIdentity(callingId); 7899 } 7900 7901 return PackageManager.INSTALL_SUCCEEDED; 7902 } 7903 7904 boolean isUserRestricted(int userId, String restrictionKey) { 7905 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7906 if (restrictions.getBoolean(restrictionKey, false)) { 7907 Log.w(TAG, "User is restricted: " + restrictionKey); 7908 return true; 7909 } 7910 return false; 7911 } 7912 7913 @Override 7914 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7915 mContext.enforceCallingOrSelfPermission( 7916 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7917 "Only package verification agents can verify applications"); 7918 7919 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7920 final PackageVerificationResponse response = new PackageVerificationResponse( 7921 verificationCode, Binder.getCallingUid()); 7922 msg.arg1 = id; 7923 msg.obj = response; 7924 mHandler.sendMessage(msg); 7925 } 7926 7927 @Override 7928 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7929 long millisecondsToDelay) { 7930 mContext.enforceCallingOrSelfPermission( 7931 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7932 "Only package verification agents can extend verification timeouts"); 7933 7934 final PackageVerificationState state = mPendingVerification.get(id); 7935 final PackageVerificationResponse response = new PackageVerificationResponse( 7936 verificationCodeAtTimeout, Binder.getCallingUid()); 7937 7938 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7939 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7940 } 7941 if (millisecondsToDelay < 0) { 7942 millisecondsToDelay = 0; 7943 } 7944 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7945 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7946 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7947 } 7948 7949 if ((state != null) && !state.timeoutExtended()) { 7950 state.extendTimeout(); 7951 7952 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7953 msg.arg1 = id; 7954 msg.obj = response; 7955 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7956 } 7957 } 7958 7959 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7960 int verificationCode, UserHandle user) { 7961 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7962 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7963 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7964 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7965 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 7966 7967 mContext.sendBroadcastAsUser(intent, user, 7968 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 7969 } 7970 7971 private ComponentName matchComponentForVerifier(String packageName, 7972 List<ResolveInfo> receivers) { 7973 ActivityInfo targetReceiver = null; 7974 7975 final int NR = receivers.size(); 7976 for (int i = 0; i < NR; i++) { 7977 final ResolveInfo info = receivers.get(i); 7978 if (info.activityInfo == null) { 7979 continue; 7980 } 7981 7982 if (packageName.equals(info.activityInfo.packageName)) { 7983 targetReceiver = info.activityInfo; 7984 break; 7985 } 7986 } 7987 7988 if (targetReceiver == null) { 7989 return null; 7990 } 7991 7992 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 7993 } 7994 7995 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 7996 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 7997 if (pkgInfo.verifiers.length == 0) { 7998 return null; 7999 } 8000 8001 final int N = pkgInfo.verifiers.length; 8002 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8003 for (int i = 0; i < N; i++) { 8004 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8005 8006 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8007 receivers); 8008 if (comp == null) { 8009 continue; 8010 } 8011 8012 final int verifierUid = getUidForVerifier(verifierInfo); 8013 if (verifierUid == -1) { 8014 continue; 8015 } 8016 8017 if (DEBUG_VERIFY) { 8018 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8019 + " with the correct signature"); 8020 } 8021 sufficientVerifiers.add(comp); 8022 verificationState.addSufficientVerifier(verifierUid); 8023 } 8024 8025 return sufficientVerifiers; 8026 } 8027 8028 private int getUidForVerifier(VerifierInfo verifierInfo) { 8029 synchronized (mPackages) { 8030 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8031 if (pkg == null) { 8032 return -1; 8033 } else if (pkg.mSignatures.length != 1) { 8034 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8035 + " has more than one signature; ignoring"); 8036 return -1; 8037 } 8038 8039 /* 8040 * If the public key of the package's signature does not match 8041 * our expected public key, then this is a different package and 8042 * we should skip. 8043 */ 8044 8045 final byte[] expectedPublicKey; 8046 try { 8047 final Signature verifierSig = pkg.mSignatures[0]; 8048 final PublicKey publicKey = verifierSig.getPublicKey(); 8049 expectedPublicKey = publicKey.getEncoded(); 8050 } catch (CertificateException e) { 8051 return -1; 8052 } 8053 8054 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8055 8056 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8057 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8058 + " does not have the expected public key; ignoring"); 8059 return -1; 8060 } 8061 8062 return pkg.applicationInfo.uid; 8063 } 8064 } 8065 8066 @Override 8067 public void finishPackageInstall(int token) { 8068 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8069 8070 if (DEBUG_INSTALL) { 8071 Slog.v(TAG, "BM finishing package install for " + token); 8072 } 8073 8074 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8075 mHandler.sendMessage(msg); 8076 } 8077 8078 /** 8079 * Get the verification agent timeout. 8080 * 8081 * @return verification timeout in milliseconds 8082 */ 8083 private long getVerificationTimeout() { 8084 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8085 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8086 DEFAULT_VERIFICATION_TIMEOUT); 8087 } 8088 8089 /** 8090 * Get the default verification agent response code. 8091 * 8092 * @return default verification response code 8093 */ 8094 private int getDefaultVerificationResponse() { 8095 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8096 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8097 DEFAULT_VERIFICATION_RESPONSE); 8098 } 8099 8100 /** 8101 * Check whether or not package verification has been enabled. 8102 * 8103 * @return true if verification should be performed 8104 */ 8105 private boolean isVerificationEnabled(int userId, int flags) { 8106 if (!DEFAULT_VERIFY_ENABLE) { 8107 return false; 8108 } 8109 8110 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8111 8112 // Check if installing from ADB 8113 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8114 // Do not run verification in a test harness environment 8115 if (ActivityManager.isRunningInTestHarness()) { 8116 return false; 8117 } 8118 if (ensureVerifyAppsEnabled) { 8119 return true; 8120 } 8121 // Check if the developer does not want package verification for ADB installs 8122 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8123 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8124 return false; 8125 } 8126 } 8127 8128 if (ensureVerifyAppsEnabled) { 8129 return true; 8130 } 8131 8132 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8133 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8134 } 8135 8136 /** 8137 * Get the "allow unknown sources" setting. 8138 * 8139 * @return the current "allow unknown sources" setting 8140 */ 8141 private int getUnknownSourcesSettings() { 8142 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8143 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8144 -1); 8145 } 8146 8147 @Override 8148 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8149 final int uid = Binder.getCallingUid(); 8150 // writer 8151 synchronized (mPackages) { 8152 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8153 if (targetPackageSetting == null) { 8154 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8155 } 8156 8157 PackageSetting installerPackageSetting; 8158 if (installerPackageName != null) { 8159 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8160 if (installerPackageSetting == null) { 8161 throw new IllegalArgumentException("Unknown installer package: " 8162 + installerPackageName); 8163 } 8164 } else { 8165 installerPackageSetting = null; 8166 } 8167 8168 Signature[] callerSignature; 8169 Object obj = mSettings.getUserIdLPr(uid); 8170 if (obj != null) { 8171 if (obj instanceof SharedUserSetting) { 8172 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8173 } else if (obj instanceof PackageSetting) { 8174 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8175 } else { 8176 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8177 } 8178 } else { 8179 throw new SecurityException("Unknown calling uid " + uid); 8180 } 8181 8182 // Verify: can't set installerPackageName to a package that is 8183 // not signed with the same cert as the caller. 8184 if (installerPackageSetting != null) { 8185 if (compareSignatures(callerSignature, 8186 installerPackageSetting.signatures.mSignatures) 8187 != PackageManager.SIGNATURE_MATCH) { 8188 throw new SecurityException( 8189 "Caller does not have same cert as new installer package " 8190 + installerPackageName); 8191 } 8192 } 8193 8194 // Verify: if target already has an installer package, it must 8195 // be signed with the same cert as the caller. 8196 if (targetPackageSetting.installerPackageName != null) { 8197 PackageSetting setting = mSettings.mPackages.get( 8198 targetPackageSetting.installerPackageName); 8199 // If the currently set package isn't valid, then it's always 8200 // okay to change it. 8201 if (setting != null) { 8202 if (compareSignatures(callerSignature, 8203 setting.signatures.mSignatures) 8204 != PackageManager.SIGNATURE_MATCH) { 8205 throw new SecurityException( 8206 "Caller does not have same cert as old installer package " 8207 + targetPackageSetting.installerPackageName); 8208 } 8209 } 8210 } 8211 8212 // Okay! 8213 targetPackageSetting.installerPackageName = installerPackageName; 8214 scheduleWriteSettingsLocked(); 8215 } 8216 } 8217 8218 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8219 // Queue up an async operation since the package installation may take a little while. 8220 mHandler.post(new Runnable() { 8221 public void run() { 8222 mHandler.removeCallbacks(this); 8223 // Result object to be returned 8224 PackageInstalledInfo res = new PackageInstalledInfo(); 8225 res.returnCode = currentStatus; 8226 res.uid = -1; 8227 res.pkg = null; 8228 res.removedInfo = new PackageRemovedInfo(); 8229 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8230 args.doPreInstall(res.returnCode); 8231 synchronized (mInstallLock) { 8232 installPackageLI(args, true, res); 8233 } 8234 args.doPostInstall(res.returnCode, res.uid); 8235 } 8236 8237 // A restore should be performed at this point if (a) the install 8238 // succeeded, (b) the operation is not an update, and (c) the new 8239 // package has a backupAgent defined. 8240 final boolean update = res.removedInfo.removedPackage != null; 8241 boolean doRestore = (!update 8242 && res.pkg != null 8243 && res.pkg.applicationInfo.backupAgentName != null); 8244 8245 // Set up the post-install work request bookkeeping. This will be used 8246 // and cleaned up by the post-install event handling regardless of whether 8247 // there's a restore pass performed. Token values are >= 1. 8248 int token; 8249 if (mNextInstallToken < 0) mNextInstallToken = 1; 8250 token = mNextInstallToken++; 8251 8252 PostInstallData data = new PostInstallData(args, res); 8253 mRunningInstalls.put(token, data); 8254 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8255 8256 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8257 // Pass responsibility to the Backup Manager. It will perform a 8258 // restore if appropriate, then pass responsibility back to the 8259 // Package Manager to run the post-install observer callbacks 8260 // and broadcasts. 8261 IBackupManager bm = IBackupManager.Stub.asInterface( 8262 ServiceManager.getService(Context.BACKUP_SERVICE)); 8263 if (bm != null) { 8264 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8265 + " to BM for possible restore"); 8266 try { 8267 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8268 } catch (RemoteException e) { 8269 // can't happen; the backup manager is local 8270 } catch (Exception e) { 8271 Slog.e(TAG, "Exception trying to enqueue restore", e); 8272 doRestore = false; 8273 } 8274 } else { 8275 Slog.e(TAG, "Backup Manager not found!"); 8276 doRestore = false; 8277 } 8278 } 8279 8280 if (!doRestore) { 8281 // No restore possible, or the Backup Manager was mysteriously not 8282 // available -- just fire the post-install work request directly. 8283 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8284 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8285 mHandler.sendMessage(msg); 8286 } 8287 } 8288 }); 8289 } 8290 8291 private abstract class HandlerParams { 8292 private static final int MAX_RETRIES = 4; 8293 8294 /** 8295 * Number of times startCopy() has been attempted and had a non-fatal 8296 * error. 8297 */ 8298 private int mRetries = 0; 8299 8300 /** User handle for the user requesting the information or installation. */ 8301 private final UserHandle mUser; 8302 8303 HandlerParams(UserHandle user) { 8304 mUser = user; 8305 } 8306 8307 UserHandle getUser() { 8308 return mUser; 8309 } 8310 8311 final boolean startCopy() { 8312 boolean res; 8313 try { 8314 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8315 8316 if (++mRetries > MAX_RETRIES) { 8317 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8318 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8319 handleServiceError(); 8320 return false; 8321 } else { 8322 handleStartCopy(); 8323 res = true; 8324 } 8325 } catch (RemoteException e) { 8326 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8327 mHandler.sendEmptyMessage(MCS_RECONNECT); 8328 res = false; 8329 } 8330 handleReturnCode(); 8331 return res; 8332 } 8333 8334 final void serviceError() { 8335 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8336 handleServiceError(); 8337 handleReturnCode(); 8338 } 8339 8340 abstract void handleStartCopy() throws RemoteException; 8341 abstract void handleServiceError(); 8342 abstract void handleReturnCode(); 8343 } 8344 8345 class MeasureParams extends HandlerParams { 8346 private final PackageStats mStats; 8347 private boolean mSuccess; 8348 8349 private final IPackageStatsObserver mObserver; 8350 8351 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8352 super(new UserHandle(stats.userHandle)); 8353 mObserver = observer; 8354 mStats = stats; 8355 } 8356 8357 @Override 8358 public String toString() { 8359 return "MeasureParams{" 8360 + Integer.toHexString(System.identityHashCode(this)) 8361 + " " + mStats.packageName + "}"; 8362 } 8363 8364 @Override 8365 void handleStartCopy() throws RemoteException { 8366 synchronized (mInstallLock) { 8367 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8368 } 8369 8370 if (mSuccess) { 8371 final boolean mounted; 8372 if (Environment.isExternalStorageEmulated()) { 8373 mounted = true; 8374 } else { 8375 final String status = Environment.getExternalStorageState(); 8376 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8377 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8378 } 8379 8380 if (mounted) { 8381 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8382 8383 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8384 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8385 8386 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8387 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8388 8389 // Always subtract cache size, since it's a subdirectory 8390 mStats.externalDataSize -= mStats.externalCacheSize; 8391 8392 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8393 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8394 8395 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8396 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8397 } 8398 } 8399 } 8400 8401 @Override 8402 void handleReturnCode() { 8403 if (mObserver != null) { 8404 try { 8405 mObserver.onGetStatsCompleted(mStats, mSuccess); 8406 } catch (RemoteException e) { 8407 Slog.i(TAG, "Observer no longer exists."); 8408 } 8409 } 8410 } 8411 8412 @Override 8413 void handleServiceError() { 8414 Slog.e(TAG, "Could not measure application " + mStats.packageName 8415 + " external storage"); 8416 } 8417 } 8418 8419 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8420 throws RemoteException { 8421 long result = 0; 8422 for (File path : paths) { 8423 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8424 } 8425 return result; 8426 } 8427 8428 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8429 for (File path : paths) { 8430 try { 8431 mcs.clearDirectory(path.getAbsolutePath()); 8432 } catch (RemoteException e) { 8433 } 8434 } 8435 } 8436 8437 class InstallParams extends HandlerParams { 8438 /** 8439 * Location where install is coming from, before it has been 8440 * copied/renamed into place. This could be a single monolithic APK 8441 * file, or a cluster directory. This location may be untrusted. 8442 */ 8443 final File originFile; 8444 8445 /** 8446 * Flag indicating that {@link #originFile} lives in a trusted location, 8447 * meaning downstream users don't need to defensively copy the contents. 8448 */ 8449 boolean originTrusted; 8450 8451 final IPackageInstallObserver observer; 8452 final IPackageInstallObserver2 observer2; 8453 int flags; 8454 final String installerPackageName; 8455 final VerificationParams verificationParams; 8456 private InstallArgs mArgs; 8457 private int mRet; 8458 final String packageAbiOverride; 8459 final String packageInstructionSetOverride; 8460 8461 InstallParams(File originFile, IPackageInstallObserver observer, 8462 IPackageInstallObserver2 observer2, int flags, String installerPackageName, 8463 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 8464 super(user); 8465 this.originFile = Preconditions.checkNotNull(originFile); 8466 this.originTrusted = false; 8467 this.observer = observer; 8468 this.observer2 = observer2; 8469 this.flags = flags; 8470 this.installerPackageName = installerPackageName; 8471 this.verificationParams = verificationParams; 8472 this.packageAbiOverride = packageAbiOverride; 8473 this.packageInstructionSetOverride = (packageAbiOverride == null) ? 8474 packageAbiOverride : VMRuntime.getInstructionSet(packageAbiOverride); 8475 } 8476 8477 @Override 8478 public String toString() { 8479 return "InstallParams{" 8480 + Integer.toHexString(System.identityHashCode(this)) 8481 + " " + originFile + "}"; 8482 } 8483 8484 public ManifestDigest getManifestDigest() { 8485 if (verificationParams == null) { 8486 return null; 8487 } 8488 return verificationParams.getManifestDigest(); 8489 } 8490 8491 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8492 String packageName = pkgLite.packageName; 8493 int installLocation = pkgLite.installLocation; 8494 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8495 // reader 8496 synchronized (mPackages) { 8497 PackageParser.Package pkg = mPackages.get(packageName); 8498 if (pkg != null) { 8499 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8500 // Check for downgrading. 8501 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8502 if (pkgLite.versionCode < pkg.mVersionCode) { 8503 Slog.w(TAG, "Can't install update of " + packageName 8504 + " update version " + pkgLite.versionCode 8505 + " is older than installed version " 8506 + pkg.mVersionCode); 8507 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8508 } 8509 } 8510 // Check for updated system application. 8511 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8512 if (onSd) { 8513 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8514 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8515 } 8516 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8517 } else { 8518 if (onSd) { 8519 // Install flag overrides everything. 8520 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8521 } 8522 // If current upgrade specifies particular preference 8523 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8524 // Application explicitly specified internal. 8525 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8526 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8527 // App explictly prefers external. Let policy decide 8528 } else { 8529 // Prefer previous location 8530 if (isExternal(pkg)) { 8531 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8532 } 8533 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8534 } 8535 } 8536 } else { 8537 // Invalid install. Return error code 8538 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8539 } 8540 } 8541 } 8542 // All the special cases have been taken care of. 8543 // Return result based on recommended install location. 8544 if (onSd) { 8545 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8546 } 8547 return pkgLite.recommendedInstallLocation; 8548 } 8549 8550 private long getMemoryLowThreshold() { 8551 final DeviceStorageMonitorInternal 8552 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8553 if (dsm == null) { 8554 return 0L; 8555 } 8556 return dsm.getMemoryLowThreshold(); 8557 } 8558 8559 /* 8560 * Invoke remote method to get package information and install 8561 * location values. Override install location based on default 8562 * policy if needed and then create install arguments based 8563 * on the install location. 8564 */ 8565 public void handleStartCopy() throws RemoteException { 8566 int ret = PackageManager.INSTALL_SUCCEEDED; 8567 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8568 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8569 PackageInfoLite pkgLite = null; 8570 8571 if (onInt && onSd) { 8572 // Check if both bits are set. 8573 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8574 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8575 } else { 8576 final long lowThreshold = getMemoryLowThreshold(); 8577 if (lowThreshold == 0L) { 8578 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8579 } 8580 8581 // Remote call to find out default install location 8582 final String originPath = originFile.getAbsolutePath(); 8583 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold, 8584 packageAbiOverride); 8585 8586 /* 8587 * If we have too little free space, try to free cache 8588 * before giving up. 8589 */ 8590 if (pkgLite.recommendedInstallLocation 8591 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8592 final long size = mContainerService.calculateInstalledSize( 8593 originPath, isForwardLocked(), packageAbiOverride); 8594 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8595 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, 8596 lowThreshold, packageAbiOverride); 8597 } 8598 /* 8599 * The cache free must have deleted the file we 8600 * downloaded to install. 8601 * 8602 * TODO: fix the "freeCache" call to not delete 8603 * the file we care about. 8604 */ 8605 if (pkgLite.recommendedInstallLocation 8606 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8607 pkgLite.recommendedInstallLocation 8608 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8609 } 8610 } 8611 } 8612 8613 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8614 int loc = pkgLite.recommendedInstallLocation; 8615 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8616 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8617 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8618 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8619 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8620 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8621 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8622 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8623 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8624 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8625 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8626 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8627 } else { 8628 // Override with defaults if needed. 8629 loc = installLocationPolicy(pkgLite, flags); 8630 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8631 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8632 } else if (!onSd && !onInt) { 8633 // Override install location with flags 8634 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8635 // Set the flag to install on external media. 8636 flags |= PackageManager.INSTALL_EXTERNAL; 8637 flags &= ~PackageManager.INSTALL_INTERNAL; 8638 } else { 8639 // Make sure the flag for installing on external 8640 // media is unset 8641 flags |= PackageManager.INSTALL_INTERNAL; 8642 flags &= ~PackageManager.INSTALL_EXTERNAL; 8643 } 8644 } 8645 } 8646 } 8647 8648 final InstallArgs args = createInstallArgs(this); 8649 mArgs = args; 8650 8651 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8652 /* 8653 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8654 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8655 */ 8656 int userIdentifier = getUser().getIdentifier(); 8657 if (userIdentifier == UserHandle.USER_ALL 8658 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8659 userIdentifier = UserHandle.USER_OWNER; 8660 } 8661 8662 /* 8663 * Determine if we have any installed package verifiers. If we 8664 * do, then we'll defer to them to verify the packages. 8665 */ 8666 final int requiredUid = mRequiredVerifierPackage == null ? -1 8667 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8668 if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) { 8669 // TODO: send verifier the install session instead of uri 8670 final Intent verification = new Intent( 8671 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8672 verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE); 8673 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8674 8675 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8676 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8677 0 /* TODO: Which userId? */); 8678 8679 if (DEBUG_VERIFY) { 8680 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8681 + verification.toString() + " with " + pkgLite.verifiers.length 8682 + " optional verifiers"); 8683 } 8684 8685 final int verificationId = mPendingVerificationToken++; 8686 8687 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8688 8689 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8690 installerPackageName); 8691 8692 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8693 8694 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8695 pkgLite.packageName); 8696 8697 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8698 pkgLite.versionCode); 8699 8700 if (verificationParams != null) { 8701 if (verificationParams.getVerificationURI() != null) { 8702 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8703 verificationParams.getVerificationURI()); 8704 } 8705 if (verificationParams.getOriginatingURI() != null) { 8706 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8707 verificationParams.getOriginatingURI()); 8708 } 8709 if (verificationParams.getReferrer() != null) { 8710 verification.putExtra(Intent.EXTRA_REFERRER, 8711 verificationParams.getReferrer()); 8712 } 8713 if (verificationParams.getOriginatingUid() >= 0) { 8714 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8715 verificationParams.getOriginatingUid()); 8716 } 8717 if (verificationParams.getInstallerUid() >= 0) { 8718 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8719 verificationParams.getInstallerUid()); 8720 } 8721 } 8722 8723 final PackageVerificationState verificationState = new PackageVerificationState( 8724 requiredUid, args); 8725 8726 mPendingVerification.append(verificationId, verificationState); 8727 8728 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8729 receivers, verificationState); 8730 8731 /* 8732 * If any sufficient verifiers were listed in the package 8733 * manifest, attempt to ask them. 8734 */ 8735 if (sufficientVerifiers != null) { 8736 final int N = sufficientVerifiers.size(); 8737 if (N == 0) { 8738 Slog.i(TAG, "Additional verifiers required, but none installed."); 8739 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8740 } else { 8741 for (int i = 0; i < N; i++) { 8742 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8743 8744 final Intent sufficientIntent = new Intent(verification); 8745 sufficientIntent.setComponent(verifierComponent); 8746 8747 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8748 } 8749 } 8750 } 8751 8752 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8753 mRequiredVerifierPackage, receivers); 8754 if (ret == PackageManager.INSTALL_SUCCEEDED 8755 && mRequiredVerifierPackage != null) { 8756 /* 8757 * Send the intent to the required verification agent, 8758 * but only start the verification timeout after the 8759 * target BroadcastReceivers have run. 8760 */ 8761 verification.setComponent(requiredVerifierComponent); 8762 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8763 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8764 new BroadcastReceiver() { 8765 @Override 8766 public void onReceive(Context context, Intent intent) { 8767 final Message msg = mHandler 8768 .obtainMessage(CHECK_PENDING_VERIFICATION); 8769 msg.arg1 = verificationId; 8770 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8771 } 8772 }, null, 0, null, null); 8773 8774 /* 8775 * We don't want the copy to proceed until verification 8776 * succeeds, so null out this field. 8777 */ 8778 mArgs = null; 8779 } 8780 } else { 8781 /* 8782 * No package verification is enabled, so immediately start 8783 * the remote call to initiate copy using temporary file. 8784 */ 8785 ret = args.copyApk(mContainerService, true); 8786 } 8787 } 8788 8789 mRet = ret; 8790 } 8791 8792 @Override 8793 void handleReturnCode() { 8794 // If mArgs is null, then MCS couldn't be reached. When it 8795 // reconnects, it will try again to install. At that point, this 8796 // will succeed. 8797 if (mArgs != null) { 8798 processPendingInstall(mArgs, mRet); 8799 } 8800 } 8801 8802 @Override 8803 void handleServiceError() { 8804 mArgs = createInstallArgs(this); 8805 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8806 } 8807 8808 public boolean isForwardLocked() { 8809 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8810 } 8811 } 8812 8813 /* 8814 * Utility class used in movePackage api. 8815 * srcArgs and targetArgs are not set for invalid flags and make 8816 * sure to do null checks when invoking methods on them. 8817 * We probably want to return ErrorPrams for both failed installs 8818 * and moves. 8819 */ 8820 class MoveParams extends HandlerParams { 8821 final IPackageMoveObserver observer; 8822 final int flags; 8823 final String packageName; 8824 final InstallArgs srcArgs; 8825 final InstallArgs targetArgs; 8826 int uid; 8827 int mRet; 8828 8829 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8830 String packageName, String instructionSet, int uid, UserHandle user) { 8831 super(user); 8832 this.srcArgs = srcArgs; 8833 this.observer = observer; 8834 this.flags = flags; 8835 this.packageName = packageName; 8836 this.uid = uid; 8837 if (srcArgs != null) { 8838 final String codePath = srcArgs.getCodePath(); 8839 targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, 8840 instructionSet); 8841 } else { 8842 targetArgs = null; 8843 } 8844 } 8845 8846 @Override 8847 public String toString() { 8848 return "MoveParams{" 8849 + Integer.toHexString(System.identityHashCode(this)) 8850 + " " + packageName + "}"; 8851 } 8852 8853 public void handleStartCopy() throws RemoteException { 8854 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8855 // Check for storage space on target medium 8856 if (!targetArgs.checkFreeStorage(mContainerService)) { 8857 Log.w(TAG, "Insufficient storage to install"); 8858 return; 8859 } 8860 8861 mRet = srcArgs.doPreCopy(); 8862 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8863 return; 8864 } 8865 8866 mRet = targetArgs.copyApk(mContainerService, false); 8867 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8868 srcArgs.doPostCopy(uid); 8869 return; 8870 } 8871 8872 mRet = srcArgs.doPostCopy(uid); 8873 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8874 return; 8875 } 8876 8877 mRet = targetArgs.doPreInstall(mRet); 8878 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8879 return; 8880 } 8881 8882 if (DEBUG_SD_INSTALL) { 8883 StringBuilder builder = new StringBuilder(); 8884 if (srcArgs != null) { 8885 builder.append("src: "); 8886 builder.append(srcArgs.getCodePath()); 8887 } 8888 if (targetArgs != null) { 8889 builder.append(" target : "); 8890 builder.append(targetArgs.getCodePath()); 8891 } 8892 Log.i(TAG, builder.toString()); 8893 } 8894 } 8895 8896 @Override 8897 void handleReturnCode() { 8898 targetArgs.doPostInstall(mRet, uid); 8899 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8900 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8901 currentStatus = PackageManager.MOVE_SUCCEEDED; 8902 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8903 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8904 } 8905 processPendingMove(this, currentStatus); 8906 } 8907 8908 @Override 8909 void handleServiceError() { 8910 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8911 } 8912 } 8913 8914 /** 8915 * Used during creation of InstallArgs 8916 * 8917 * @param flags package installation flags 8918 * @return true if should be installed on external storage 8919 */ 8920 private static boolean installOnSd(int flags) { 8921 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8922 return false; 8923 } 8924 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8925 return true; 8926 } 8927 return false; 8928 } 8929 8930 /** 8931 * Used during creation of InstallArgs 8932 * 8933 * @param flags package installation flags 8934 * @return true if should be installed as forward locked 8935 */ 8936 private static boolean installForwardLocked(int flags) { 8937 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8938 } 8939 8940 private InstallArgs createInstallArgs(InstallParams params) { 8941 // TODO: extend to support incoming zero-copy locations 8942 8943 if (installOnSd(params.flags) || params.isForwardLocked()) { 8944 return new AsecInstallArgs(params); 8945 } else { 8946 return new FileInstallArgs(params); 8947 } 8948 } 8949 8950 /** 8951 * Create args that describe an existing installed package. Typically used 8952 * when cleaning up old installs, or used as a move source. 8953 */ 8954 private InstallArgs createInstallArgsForExisting(int flags, String codePath, 8955 String resourcePath, String nativeLibraryPath, String instructionSet) { 8956 final boolean isInAsec; 8957 if (installOnSd(flags)) { 8958 /* Apps on SD card are always in ASEC containers. */ 8959 isInAsec = true; 8960 } else if (installForwardLocked(flags) 8961 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8962 /* 8963 * Forward-locked apps are only in ASEC containers if they're the 8964 * new style 8965 */ 8966 isInAsec = true; 8967 } else { 8968 isInAsec = false; 8969 } 8970 8971 if (isInAsec) { 8972 return new AsecInstallArgs(codePath, resourcePath, nativeLibraryPath, 8973 instructionSet, installOnSd(flags), installForwardLocked(flags)); 8974 } else { 8975 return new FileInstallArgs(codePath, resourcePath, nativeLibraryPath, instructionSet); 8976 } 8977 } 8978 8979 private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName, 8980 String instructionSet) { 8981 final File codeFile = new File(codePath); 8982 if (installOnSd(flags) || installForwardLocked(flags)) { 8983 String cid = getNextCodePath(codePath, pkgName, "/" 8984 + AsecInstallArgs.RES_FILE_NAME); 8985 return new AsecInstallArgs(codeFile, cid, instructionSet, installOnSd(flags), 8986 installForwardLocked(flags)); 8987 } else { 8988 return new FileInstallArgs(codeFile, instructionSet); 8989 } 8990 } 8991 8992 static abstract class InstallArgs { 8993 /** @see InstallParams#originFile */ 8994 final File originFile; 8995 /** @see InstallParams#originTrusted */ 8996 final boolean originTrusted; 8997 8998 // TODO: define inherit location 8999 9000 final IPackageInstallObserver observer; 9001 final IPackageInstallObserver2 observer2; 9002 // Always refers to PackageManager flags only 9003 final int flags; 9004 final String installerPackageName; 9005 final ManifestDigest manifestDigest; 9006 final UserHandle user; 9007 final String instructionSet; 9008 final String abiOverride; 9009 9010 InstallArgs(File originFile, boolean originTrusted, IPackageInstallObserver observer, 9011 IPackageInstallObserver2 observer2, int flags, String installerPackageName, 9012 ManifestDigest manifestDigest, UserHandle user, String instructionSet, 9013 String abiOverride) { 9014 this.originFile = originFile; 9015 this.originTrusted = originTrusted; 9016 this.flags = flags; 9017 this.observer = observer; 9018 this.observer2 = observer2; 9019 this.installerPackageName = installerPackageName; 9020 this.manifestDigest = manifestDigest; 9021 this.user = user; 9022 this.instructionSet = instructionSet; 9023 this.abiOverride = abiOverride; 9024 } 9025 9026 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9027 abstract int doPreInstall(int status); 9028 9029 /** 9030 * Rename package into final resting place. All paths on the given 9031 * scanned package should be updated to reflect the rename. 9032 */ 9033 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9034 abstract int doPostInstall(int status, int uid); 9035 9036 /** @see PackageSettingBase#codePathString */ 9037 abstract String getCodePath(); 9038 /** @see PackageSettingBase#resourcePathString */ 9039 abstract String getResourcePath(); 9040 /** @see PackageSettingBase#nativeLibraryPathString */ 9041 abstract String getNativeLibraryPath(); 9042 9043 // Need installer lock especially for dex file removal. 9044 abstract void cleanUpResourcesLI(); 9045 abstract boolean doPostDeleteLI(boolean delete); 9046 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9047 9048 /** 9049 * Called before the source arguments are copied. This is used mostly 9050 * for MoveParams when it needs to read the source file to put it in the 9051 * destination. 9052 */ 9053 int doPreCopy() { 9054 return PackageManager.INSTALL_SUCCEEDED; 9055 } 9056 9057 /** 9058 * Called after the source arguments are copied. This is used mostly for 9059 * MoveParams when it needs to read the source file to put it in the 9060 * destination. 9061 * 9062 * @return 9063 */ 9064 int doPostCopy(int uid) { 9065 return PackageManager.INSTALL_SUCCEEDED; 9066 } 9067 9068 protected boolean isFwdLocked() { 9069 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9070 } 9071 9072 UserHandle getUser() { 9073 return user; 9074 } 9075 } 9076 9077 /** 9078 * Logic to handle installation of non-ASEC applications, including copying 9079 * and renaming logic. 9080 */ 9081 class FileInstallArgs extends InstallArgs { 9082 private File codeFile; 9083 private File resourceFile; 9084 private File nativeLibraryFile; 9085 9086 // Example topology: 9087 // /data/app/com.example/base.apk 9088 // /data/app/com.example/split_foo.apk 9089 // /data/app/com.example/native/arm/libfoo.so 9090 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9091 9092 /** New install */ 9093 FileInstallArgs(InstallParams params) { 9094 super(params.originFile, params.originTrusted, params.observer, params.observer2, 9095 params.flags, params.installerPackageName, params.getManifestDigest(), 9096 params.getUser(), params.packageInstructionSetOverride, 9097 params.packageAbiOverride); 9098 if (isFwdLocked()) { 9099 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9100 } 9101 } 9102 9103 /** Existing install */ 9104 FileInstallArgs(String codePath, String resourcePath, String nativeLibraryPath, 9105 String instructionSet) { 9106 super(null, false, null, null, 0, null, null, null, instructionSet, null); 9107 this.codeFile = (codePath != null) ? new File(codePath) : null; 9108 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9109 this.nativeLibraryFile = (nativeLibraryPath != null) ? new File(nativeLibraryPath) : null; 9110 } 9111 9112 /** New install from existing */ 9113 FileInstallArgs(File originFile, String instructionSet) { 9114 super(originFile, true, null, null, 0, null, null, null, instructionSet, null); 9115 } 9116 9117 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9118 final long lowThreshold; 9119 9120 final DeviceStorageMonitorInternal 9121 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9122 if (dsm == null) { 9123 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9124 lowThreshold = 0L; 9125 } else { 9126 if (dsm.isMemoryLow()) { 9127 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9128 return false; 9129 } 9130 9131 lowThreshold = dsm.getMemoryLowThreshold(); 9132 } 9133 9134 return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9135 lowThreshold); 9136 } 9137 9138 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9139 try { 9140 final File tempDir = createTempPackageDir(mAppInstallDir); 9141 codeFile = tempDir; 9142 resourceFile = tempDir; 9143 } catch (IOException e) { 9144 Slog.w(TAG, "Failed to create copy file: " + e); 9145 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9146 } 9147 9148 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9149 @Override 9150 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9151 if (!FileUtils.isValidExtFilename(name)) { 9152 throw new IllegalArgumentException("Invalid filename: " + name); 9153 } 9154 try { 9155 final File file = new File(codeFile, name); 9156 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9157 O_RDWR | O_CREAT, 0644); 9158 Os.chmod(file.getAbsolutePath(), 0644); 9159 return new ParcelFileDescriptor(fd); 9160 } catch (ErrnoException e) { 9161 throw new RemoteException("Failed to open: " + e.getMessage()); 9162 } 9163 } 9164 }; 9165 9166 int ret = imcs.copyPackage(originFile.getAbsolutePath(), target); 9167 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9168 Slog.e(TAG, "Failed to copy package"); 9169 return ret; 9170 } 9171 9172 String[] abiList = (abiOverride != null) ? 9173 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 9174 NativeLibraryHelper.Handle handle = null; 9175 try { 9176 handle = NativeLibraryHelper.Handle.create(codeFile); 9177 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && 9178 abiOverride == null && 9179 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9180 abiList = Build.SUPPORTED_32_BIT_ABIS; 9181 } 9182 9183 // TODO: refactor to avoid double findSupportedAbi() 9184 final int abiIndex = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9185 if (abiIndex < 0 && abiIndex != PackageManager.NO_NATIVE_LIBRARIES) { 9186 return abiIndex; 9187 } else if (abiIndex >= 0) { 9188 final File baseLibFile = new File(codeFile, LIB_DIR_NAME); 9189 baseLibFile.mkdir(); 9190 Os.chmod(baseLibFile.getAbsolutePath(), 0755); 9191 9192 final String abi = Build.SUPPORTED_ABIS[abiIndex]; 9193 final String instructionSet = VMRuntime.getInstructionSet(abi); 9194 nativeLibraryFile = new File(baseLibFile, instructionSet); 9195 nativeLibraryFile.mkdir(); 9196 Os.chmod(nativeLibraryFile.getAbsolutePath(), 0755); 9197 9198 copyNativeLibrariesForInternalApp(handle, nativeLibraryFile, abiList); 9199 } 9200 } catch (IOException | ErrnoException e) { 9201 Slog.e(TAG, "Copying native libraries failed", e); 9202 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9203 } finally { 9204 IoUtils.closeQuietly(handle); 9205 } 9206 9207 return ret; 9208 } 9209 9210 int doPreInstall(int status) { 9211 if (status != PackageManager.INSTALL_SUCCEEDED) { 9212 cleanUp(); 9213 } 9214 return status; 9215 } 9216 9217 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9218 if (status != PackageManager.INSTALL_SUCCEEDED) { 9219 cleanUp(); 9220 return false; 9221 } else { 9222 final File beforeCodeFile = codeFile; 9223 final File afterCodeFile = new File(mAppInstallDir, 9224 getNextCodePath(oldCodePath, pkg.packageName, null)); 9225 9226 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9227 if (!beforeCodeFile.renameTo(afterCodeFile)) { 9228 return false; 9229 } 9230 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9231 return false; 9232 } 9233 9234 // Reflect the rename internally 9235 codeFile = afterCodeFile; 9236 resourceFile = afterCodeFile; 9237 nativeLibraryFile = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9238 nativeLibraryFile); 9239 9240 // Reflect the rename in scanned details 9241 pkg.codePath = afterCodeFile.getAbsolutePath(); 9242 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9243 pkg.baseCodePath); 9244 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9245 pkg.splitCodePaths); 9246 9247 // Reflect the rename in app info 9248 pkg.applicationInfo.setCodePath(pkg.codePath); 9249 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9250 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9251 pkg.applicationInfo.setResourcePath(pkg.codePath); 9252 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9253 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9254 pkg.applicationInfo.nativeLibraryDir = getNativeLibraryPath(); 9255 9256 return true; 9257 } 9258 } 9259 9260 int doPostInstall(int status, int uid) { 9261 if (status != PackageManager.INSTALL_SUCCEEDED) { 9262 cleanUp(); 9263 } 9264 return status; 9265 } 9266 9267 @Override 9268 String getCodePath() { 9269 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9270 } 9271 9272 @Override 9273 String getResourcePath() { 9274 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9275 } 9276 9277 @Override 9278 String getNativeLibraryPath() { 9279 return (nativeLibraryFile != null) ? nativeLibraryFile.getAbsolutePath() : null; 9280 } 9281 9282 private boolean cleanUp() { 9283 if (codeFile == null || !codeFile.exists()) { 9284 return false; 9285 } 9286 9287 if (codeFile.isDirectory()) { 9288 FileUtils.deleteContents(codeFile); 9289 } 9290 codeFile.delete(); 9291 9292 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9293 resourceFile.delete(); 9294 } 9295 9296 if (nativeLibraryFile != null && !FileUtils.contains(codeFile, nativeLibraryFile)) { 9297 FileUtils.deleteContents(nativeLibraryFile); 9298 nativeLibraryFile.delete(); 9299 } 9300 9301 return true; 9302 } 9303 9304 void cleanUpResourcesLI() { 9305 // Try enumerating all code paths before deleting 9306 List<String> allCodePaths = Collections.EMPTY_LIST; 9307 if (codeFile != null && codeFile.exists()) { 9308 try { 9309 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9310 allCodePaths = pkg.getAllCodePaths(); 9311 } catch (PackageParserException e) { 9312 // Ignored; we tried our best 9313 } 9314 } 9315 9316 cleanUp(); 9317 9318 if (!allCodePaths.isEmpty()) { 9319 if (instructionSet == null) { 9320 throw new IllegalStateException("instructionSet == null"); 9321 } 9322 9323 for (String codePath : allCodePaths) { 9324 int retCode = mInstaller.rmdex(codePath, instructionSet); 9325 if (retCode < 0) { 9326 Slog.w(TAG, "Couldn't remove dex file for package: " 9327 + " at location " + codePath + ", retcode=" + retCode); 9328 // we don't consider this to be a failure of the core package deletion 9329 } 9330 } 9331 } 9332 } 9333 9334 boolean doPostDeleteLI(boolean delete) { 9335 // XXX err, shouldn't we respect the delete flag? 9336 cleanUpResourcesLI(); 9337 return true; 9338 } 9339 } 9340 9341 private boolean isAsecExternal(String cid) { 9342 final String asecPath = PackageHelper.getSdFilesystem(cid); 9343 return !asecPath.startsWith(mAsecInternalPath); 9344 } 9345 9346 /** 9347 * Extract the MountService "container ID" from the full code path of an 9348 * .apk. 9349 */ 9350 static String cidFromCodePath(String fullCodePath) { 9351 int eidx = fullCodePath.lastIndexOf("/"); 9352 String subStr1 = fullCodePath.substring(0, eidx); 9353 int sidx = subStr1.lastIndexOf("/"); 9354 return subStr1.substring(sidx+1, eidx); 9355 } 9356 9357 /** 9358 * Logic to handle installation of ASEC applications, including copying and 9359 * renaming logic. 9360 */ 9361 class AsecInstallArgs extends InstallArgs { 9362 // TODO: teach about handling cluster directories 9363 9364 static final String RES_FILE_NAME = "pkg.apk"; 9365 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9366 9367 String cid; 9368 String packagePath; 9369 String resourcePath; 9370 String libraryPath; 9371 9372 /** New install */ 9373 AsecInstallArgs(InstallParams params) { 9374 super(params.originFile, params.originTrusted, params.observer, params.observer2, 9375 params.flags, params.installerPackageName, params.getManifestDigest(), 9376 params.getUser(), params.packageInstructionSetOverride, 9377 params.packageAbiOverride); 9378 } 9379 9380 /** Existing install */ 9381 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 9382 String instructionSet, boolean isExternal, boolean isForwardLocked) { 9383 super(null, false, null, null, (isExternal ? INSTALL_EXTERNAL : 0) 9384 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9385 instructionSet, null); 9386 // Extract cid from fullCodePath 9387 int eidx = fullCodePath.lastIndexOf("/"); 9388 String subStr1 = fullCodePath.substring(0, eidx); 9389 int sidx = subStr1.lastIndexOf("/"); 9390 cid = subStr1.substring(sidx+1, eidx); 9391 setCachePath(subStr1); 9392 } 9393 9394 AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) { 9395 super(null, false, null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9396 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9397 instructionSet, null); 9398 this.cid = cid; 9399 setCachePath(PackageHelper.getSdDir(cid)); 9400 } 9401 9402 /** New install from existing */ 9403 AsecInstallArgs(File originPackageFile, String cid, String instructionSet, 9404 boolean isExternal, boolean isForwardLocked) { 9405 super(originPackageFile, true, null, null, (isExternal ? INSTALL_EXTERNAL : 0) 9406 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9407 instructionSet, null); 9408 this.cid = cid; 9409 } 9410 9411 void createCopyFile() { 9412 cid = getTempContainerId(); 9413 } 9414 9415 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9416 return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9417 abiOverride); 9418 } 9419 9420 private final boolean isExternal() { 9421 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9422 } 9423 9424 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9425 if (temp) { 9426 createCopyFile(); 9427 } else { 9428 /* 9429 * Pre-emptively destroy the container since it's destroyed if 9430 * copying fails due to it existing anyway. 9431 */ 9432 PackageHelper.destroySdDir(cid); 9433 } 9434 9435 final String newCachePath = imcs.copyPackageToContainer( 9436 originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9437 isFwdLocked(), abiOverride); 9438 9439 if (newCachePath != null) { 9440 setCachePath(newCachePath); 9441 return PackageManager.INSTALL_SUCCEEDED; 9442 } else { 9443 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9444 } 9445 } 9446 9447 @Override 9448 String getCodePath() { 9449 return packagePath; 9450 } 9451 9452 @Override 9453 String getResourcePath() { 9454 return resourcePath; 9455 } 9456 9457 @Override 9458 String getNativeLibraryPath() { 9459 return libraryPath; 9460 } 9461 9462 int doPreInstall(int status) { 9463 if (status != PackageManager.INSTALL_SUCCEEDED) { 9464 // Destroy container 9465 PackageHelper.destroySdDir(cid); 9466 } else { 9467 boolean mounted = PackageHelper.isContainerMounted(cid); 9468 if (!mounted) { 9469 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9470 Process.SYSTEM_UID); 9471 if (newCachePath != null) { 9472 setCachePath(newCachePath); 9473 } else { 9474 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9475 } 9476 } 9477 } 9478 return status; 9479 } 9480 9481 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9482 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9483 String newCachePath = null; 9484 if (PackageHelper.isContainerMounted(cid)) { 9485 // Unmount the container 9486 if (!PackageHelper.unMountSdDir(cid)) { 9487 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9488 return false; 9489 } 9490 } 9491 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9492 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9493 " which might be stale. Will try to clean up."); 9494 // Clean up the stale container and proceed to recreate. 9495 if (!PackageHelper.destroySdDir(newCacheId)) { 9496 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9497 return false; 9498 } 9499 // Successfully cleaned up stale container. Try to rename again. 9500 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9501 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9502 + " inspite of cleaning it up."); 9503 return false; 9504 } 9505 } 9506 if (!PackageHelper.isContainerMounted(newCacheId)) { 9507 Slog.w(TAG, "Mounting container " + newCacheId); 9508 newCachePath = PackageHelper.mountSdDir(newCacheId, 9509 getEncryptKey(), Process.SYSTEM_UID); 9510 } else { 9511 newCachePath = PackageHelper.getSdDir(newCacheId); 9512 } 9513 if (newCachePath == null) { 9514 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9515 return false; 9516 } 9517 Log.i(TAG, "Succesfully renamed " + cid + 9518 " to " + newCacheId + 9519 " at new path: " + newCachePath); 9520 cid = newCacheId; 9521 setCachePath(newCachePath); 9522 9523 // TODO: extend to support split APKs 9524 pkg.codePath = getCodePath(); 9525 pkg.baseCodePath = getCodePath(); 9526 pkg.splitCodePaths = null; 9527 9528 pkg.applicationInfo.setCodePath(getCodePath()); 9529 pkg.applicationInfo.setBaseCodePath(getCodePath()); 9530 pkg.applicationInfo.setSplitCodePaths(null); 9531 pkg.applicationInfo.setResourcePath(getResourcePath()); 9532 pkg.applicationInfo.setBaseResourcePath(getResourcePath()); 9533 pkg.applicationInfo.setSplitResourcePaths(null); 9534 pkg.applicationInfo.nativeLibraryDir = getNativeLibraryPath(); 9535 9536 return true; 9537 } 9538 9539 private void setCachePath(String newCachePath) { 9540 File cachePath = new File(newCachePath); 9541 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath(); 9542 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9543 9544 if (isFwdLocked()) { 9545 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9546 } else { 9547 resourcePath = packagePath; 9548 } 9549 } 9550 9551 int doPostInstall(int status, int uid) { 9552 if (status != PackageManager.INSTALL_SUCCEEDED) { 9553 cleanUp(); 9554 } else { 9555 final int groupOwner; 9556 final String protectedFile; 9557 if (isFwdLocked()) { 9558 groupOwner = UserHandle.getSharedAppGid(uid); 9559 protectedFile = RES_FILE_NAME; 9560 } else { 9561 groupOwner = -1; 9562 protectedFile = null; 9563 } 9564 9565 if (uid < Process.FIRST_APPLICATION_UID 9566 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9567 Slog.e(TAG, "Failed to finalize " + cid); 9568 PackageHelper.destroySdDir(cid); 9569 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9570 } 9571 9572 boolean mounted = PackageHelper.isContainerMounted(cid); 9573 if (!mounted) { 9574 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9575 } 9576 } 9577 return status; 9578 } 9579 9580 private void cleanUp() { 9581 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9582 9583 // Destroy secure container 9584 PackageHelper.destroySdDir(cid); 9585 } 9586 9587 void cleanUpResourcesLI() { 9588 String sourceFile = getCodePath(); 9589 // Remove dex file 9590 if (instructionSet == null) { 9591 throw new IllegalStateException("instructionSet == null"); 9592 } 9593 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9594 if (retCode < 0) { 9595 Slog.w(TAG, "Couldn't remove dex file for package: " 9596 + " at location " 9597 + sourceFile.toString() + ", retcode=" + retCode); 9598 // we don't consider this to be a failure of the core package deletion 9599 } 9600 cleanUp(); 9601 } 9602 9603 boolean matchContainer(String app) { 9604 if (cid.startsWith(app)) { 9605 return true; 9606 } 9607 return false; 9608 } 9609 9610 String getPackageName() { 9611 return getAsecPackageName(cid); 9612 } 9613 9614 boolean doPostDeleteLI(boolean delete) { 9615 boolean ret = false; 9616 boolean mounted = PackageHelper.isContainerMounted(cid); 9617 if (mounted) { 9618 // Unmount first 9619 ret = PackageHelper.unMountSdDir(cid); 9620 } 9621 if (ret && delete) { 9622 cleanUpResourcesLI(); 9623 } 9624 return ret; 9625 } 9626 9627 @Override 9628 int doPreCopy() { 9629 if (isFwdLocked()) { 9630 if (!PackageHelper.fixSdPermissions(cid, 9631 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9632 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9633 } 9634 } 9635 9636 return PackageManager.INSTALL_SUCCEEDED; 9637 } 9638 9639 @Override 9640 int doPostCopy(int uid) { 9641 if (isFwdLocked()) { 9642 if (uid < Process.FIRST_APPLICATION_UID 9643 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9644 RES_FILE_NAME)) { 9645 Slog.e(TAG, "Failed to finalize " + cid); 9646 PackageHelper.destroySdDir(cid); 9647 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9648 } 9649 } 9650 9651 return PackageManager.INSTALL_SUCCEEDED; 9652 } 9653 } 9654 9655 static String getAsecPackageName(String packageCid) { 9656 int idx = packageCid.lastIndexOf("-"); 9657 if (idx == -1) { 9658 return packageCid; 9659 } 9660 return packageCid.substring(0, idx); 9661 } 9662 9663 // Utility method used to create code paths based on package name and available index. 9664 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9665 String idxStr = ""; 9666 int idx = 1; 9667 // Fall back to default value of idx=1 if prefix is not 9668 // part of oldCodePath 9669 if (oldCodePath != null) { 9670 String subStr = oldCodePath; 9671 // Drop the suffix right away 9672 if (suffix != null && subStr.endsWith(suffix)) { 9673 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9674 } 9675 // If oldCodePath already contains prefix find out the 9676 // ending index to either increment or decrement. 9677 int sidx = subStr.lastIndexOf(prefix); 9678 if (sidx != -1) { 9679 subStr = subStr.substring(sidx + prefix.length()); 9680 if (subStr != null) { 9681 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9682 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9683 } 9684 try { 9685 idx = Integer.parseInt(subStr); 9686 if (idx <= 1) { 9687 idx++; 9688 } else { 9689 idx--; 9690 } 9691 } catch(NumberFormatException e) { 9692 } 9693 } 9694 } 9695 } 9696 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9697 return prefix + idxStr; 9698 } 9699 9700 // Utility method used to ignore ADD/REMOVE events 9701 // by directory observer. 9702 private static boolean ignoreCodePath(String fullPathStr) { 9703 String apkName = deriveCodePathName(fullPathStr); 9704 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9705 if (idx != -1 && ((idx+1) < apkName.length())) { 9706 // Make sure the package ends with a numeral 9707 String version = apkName.substring(idx+1); 9708 try { 9709 Integer.parseInt(version); 9710 return true; 9711 } catch (NumberFormatException e) {} 9712 } 9713 return false; 9714 } 9715 9716 // Utility method that returns the relative package path with respect 9717 // to the installation directory. Like say for /data/data/com.test-1.apk 9718 // string com.test-1 is returned. 9719 static String deriveCodePathName(String codePath) { 9720 if (codePath == null) { 9721 return null; 9722 } 9723 final File codeFile = new File(codePath); 9724 final String name = codeFile.getName(); 9725 if (codeFile.isDirectory()) { 9726 return name; 9727 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9728 final int lastDot = name.lastIndexOf('.'); 9729 return name.substring(0, lastDot); 9730 } else { 9731 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9732 return null; 9733 } 9734 } 9735 9736 class PackageInstalledInfo { 9737 String name; 9738 int uid; 9739 // The set of users that originally had this package installed. 9740 int[] origUsers; 9741 // The set of users that now have this package installed. 9742 int[] newUsers; 9743 PackageParser.Package pkg; 9744 int returnCode; 9745 PackageRemovedInfo removedInfo; 9746 9747 // In some error cases we want to convey more info back to the observer 9748 String origPackage; 9749 String origPermission; 9750 } 9751 9752 /* 9753 * Install a non-existing package. 9754 */ 9755 private void installNewPackageLI(PackageParser.Package pkg, 9756 int parseFlags, int scanMode, UserHandle user, 9757 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9758 // Remember this for later, in case we need to rollback this install 9759 String pkgName = pkg.packageName; 9760 9761 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9762 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9763 synchronized(mPackages) { 9764 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9765 // A package with the same name is already installed, though 9766 // it has been renamed to an older name. The package we 9767 // are trying to install should be installed as an update to 9768 // the existing one, but that has not been requested, so bail. 9769 Slog.w(TAG, "Attempt to re-install " + pkgName 9770 + " without first uninstalling package running as " 9771 + mSettings.mRenamedPackages.get(pkgName)); 9772 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9773 return; 9774 } 9775 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9776 // Don't allow installation over an existing package with the same name. 9777 Slog.w(TAG, "Attempt to re-install " + pkgName 9778 + " without first uninstalling."); 9779 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9780 return; 9781 } 9782 } 9783 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9784 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9785 System.currentTimeMillis(), user, abiOverride); 9786 if (newPackage == null) { 9787 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 9788 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9789 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9790 } 9791 } else { 9792 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9793 // delete the partially installed application. the data directory will have to be 9794 // restored if it was already existing 9795 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9796 // remove package from internal structures. Note that we want deletePackageX to 9797 // delete the package data and cache directories that it created in 9798 // scanPackageLocked, unless those directories existed before we even tried to 9799 // install. 9800 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9801 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9802 res.removedInfo, true); 9803 } 9804 } 9805 } 9806 9807 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9808 // Upgrade keysets are being used. Determine if new package has a superset of the 9809 // required keys. 9810 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9811 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9812 Set<Long> newSigningKeyIds = new ArraySet<Long>(); 9813 for (PublicKey pk : newPkg.mSigningKeys) { 9814 newSigningKeyIds.add(ksms.getIdForPublicKey(pk)); 9815 } 9816 //remove PUBLIC_KEY_NOT_FOUND, although not necessary 9817 newSigningKeyIds.remove(ksms.PUBLIC_KEY_NOT_FOUND); 9818 for (int i = 0; i < upgradeKeySets.length; i++) { 9819 if (newSigningKeyIds.containsAll(ksms.mKeySetMapping.get(upgradeKeySets[i]))) { 9820 return true; 9821 } 9822 } 9823 return false; 9824 } 9825 9826 private void replacePackageLI(PackageParser.Package pkg, 9827 int parseFlags, int scanMode, UserHandle user, 9828 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9829 PackageParser.Package oldPackage; 9830 String pkgName = pkg.packageName; 9831 int[] allUsers; 9832 boolean[] perUserInstalled; 9833 9834 // First find the old package info and check signatures 9835 synchronized(mPackages) { 9836 oldPackage = mPackages.get(pkgName); 9837 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9838 PackageSetting ps = mSettings.mPackages.get(pkgName); 9839 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9840 // default to original signature matching 9841 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9842 != PackageManager.SIGNATURE_MATCH) { 9843 Slog.w(TAG, "New package has a different signature: " + pkgName); 9844 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9845 return; 9846 } 9847 } else { 9848 if(!checkUpgradeKeySetLP(ps, pkg)) { 9849 Slog.w(TAG, "New package not signed by keys specified by upgrade-keysets: " 9850 + pkgName); 9851 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9852 return; 9853 } 9854 } 9855 9856 // In case of rollback, remember per-user/profile install state 9857 allUsers = sUserManager.getUserIds(); 9858 perUserInstalled = new boolean[allUsers.length]; 9859 for (int i = 0; i < allUsers.length; i++) { 9860 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9861 } 9862 } 9863 boolean sysPkg = (isSystemApp(oldPackage)); 9864 if (sysPkg) { 9865 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9866 user, allUsers, perUserInstalled, installerPackageName, res, 9867 abiOverride); 9868 } else { 9869 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9870 user, allUsers, perUserInstalled, installerPackageName, res, 9871 abiOverride); 9872 } 9873 } 9874 9875 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9876 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9877 int[] allUsers, boolean[] perUserInstalled, 9878 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9879 PackageParser.Package newPackage = null; 9880 String pkgName = deletedPackage.packageName; 9881 boolean deletedPkg = true; 9882 boolean updatedSettings = false; 9883 9884 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9885 + deletedPackage); 9886 long origUpdateTime; 9887 if (pkg.mExtras != null) { 9888 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9889 } else { 9890 origUpdateTime = 0; 9891 } 9892 9893 // First delete the existing package while retaining the data directory 9894 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9895 res.removedInfo, true)) { 9896 // If the existing package wasn't successfully deleted 9897 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9898 deletedPkg = false; 9899 } else { 9900 // Successfully deleted the old package. Now proceed with re-installation 9901 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9902 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 9903 System.currentTimeMillis(), user, abiOverride); 9904 if (newPackage == null) { 9905 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 9906 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9907 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9908 } 9909 } else { 9910 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9911 updatedSettings = true; 9912 } 9913 } 9914 9915 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9916 // remove package from internal structures. Note that we want deletePackageX to 9917 // delete the package data and cache directories that it created in 9918 // scanPackageLocked, unless those directories existed before we even tried to 9919 // install. 9920 if(updatedSettings) { 9921 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9922 deletePackageLI( 9923 pkgName, null, true, allUsers, perUserInstalled, 9924 PackageManager.DELETE_KEEP_DATA, 9925 res.removedInfo, true); 9926 } 9927 // Since we failed to install the new package we need to restore the old 9928 // package that we deleted. 9929 if (deletedPkg) { 9930 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 9931 File restoreFile = new File(deletedPackage.codePath); 9932 // Parse old package 9933 boolean oldOnSd = isExternal(deletedPackage); 9934 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 9935 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 9936 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 9937 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 9938 | SCAN_UPDATE_TIME; 9939 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 9940 origUpdateTime, null, null) == null) { 9941 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 9942 return; 9943 } 9944 // Restore of old package succeeded. Update permissions. 9945 // writer 9946 synchronized (mPackages) { 9947 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 9948 UPDATE_PERMISSIONS_ALL); 9949 // can downgrade to reader 9950 mSettings.writeLPr(); 9951 } 9952 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 9953 } 9954 } 9955 } 9956 9957 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 9958 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9959 int[] allUsers, boolean[] perUserInstalled, 9960 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9961 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 9962 + ", old=" + deletedPackage); 9963 PackageParser.Package newPackage = null; 9964 boolean updatedSettings = false; 9965 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 9966 PackageParser.PARSE_IS_SYSTEM; 9967 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 9968 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9969 } 9970 String packageName = deletedPackage.packageName; 9971 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9972 if (packageName == null) { 9973 Slog.w(TAG, "Attempt to delete null packageName."); 9974 return; 9975 } 9976 PackageParser.Package oldPkg; 9977 PackageSetting oldPkgSetting; 9978 // reader 9979 synchronized (mPackages) { 9980 oldPkg = mPackages.get(packageName); 9981 oldPkgSetting = mSettings.mPackages.get(packageName); 9982 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 9983 (oldPkgSetting == null)) { 9984 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 9985 return; 9986 } 9987 } 9988 9989 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 9990 9991 res.removedInfo.uid = oldPkg.applicationInfo.uid; 9992 res.removedInfo.removedPackage = packageName; 9993 // Remove existing system package 9994 removePackageLI(oldPkgSetting, true); 9995 // writer 9996 synchronized (mPackages) { 9997 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 9998 // We didn't need to disable the .apk as a current system package, 9999 // which means we are replacing another update that is already 10000 // installed. We need to make sure to delete the older one's .apk. 10001 res.removedInfo.args = createInstallArgsForExisting(0, 10002 deletedPackage.applicationInfo.getCodePath(), 10003 deletedPackage.applicationInfo.getResourcePath(), 10004 deletedPackage.applicationInfo.nativeLibraryDir, 10005 getAppInstructionSet(deletedPackage.applicationInfo)); 10006 } else { 10007 res.removedInfo.args = null; 10008 } 10009 } 10010 10011 // Successfully disabled the old package. Now proceed with re-installation 10012 res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED; 10013 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10014 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride); 10015 if (newPackage == null) { 10016 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 10017 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 10018 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 10019 } 10020 } else { 10021 if (newPackage.mExtras != null) { 10022 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 10023 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10024 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10025 10026 // is the update attempting to change shared user? that isn't going to work... 10027 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10028 Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser 10029 + " to " + newPkgSetting.sharedUser); 10030 res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 10031 updatedSettings = true; 10032 } 10033 } 10034 10035 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10036 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10037 updatedSettings = true; 10038 } 10039 } 10040 10041 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10042 // Re installation failed. Restore old information 10043 // Remove new pkg information 10044 if (newPackage != null) { 10045 removeInstalledPackageLI(newPackage, true); 10046 } 10047 // Add back the old system package 10048 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null); 10049 // Restore the old system information in Settings 10050 synchronized(mPackages) { 10051 if (updatedSettings) { 10052 mSettings.enableSystemPackageLPw(packageName); 10053 mSettings.setInstallerPackageName(packageName, 10054 oldPkgSetting.installerPackageName); 10055 } 10056 mSettings.writeLPr(); 10057 } 10058 } 10059 } 10060 10061 // Utility method used to move dex files during install. 10062 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10063 // TODO: extend to move split APK dex files 10064 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10065 final String instructionSet = getAppInstructionSet(newPackage.applicationInfo); 10066 int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath, 10067 instructionSet); 10068 if (retCode != 0) { 10069 /* 10070 * Programs may be lazily run through dexopt, so the 10071 * source may not exist. However, something seems to 10072 * have gone wrong, so note that dexopt needs to be 10073 * run again and remove the source file. In addition, 10074 * remove the target to make sure there isn't a stale 10075 * file from a previous version of the package. 10076 */ 10077 newPackage.mDexOptNeeded = true; 10078 mInstaller.rmdex(oldCodePath, instructionSet); 10079 mInstaller.rmdex(newPackage.baseCodePath, instructionSet); 10080 } 10081 } 10082 return PackageManager.INSTALL_SUCCEEDED; 10083 } 10084 10085 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10086 int[] allUsers, boolean[] perUserInstalled, 10087 PackageInstalledInfo res) { 10088 String pkgName = newPackage.packageName; 10089 synchronized (mPackages) { 10090 //write settings. the installStatus will be incomplete at this stage. 10091 //note that the new package setting would have already been 10092 //added to mPackages. It hasn't been persisted yet. 10093 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10094 mSettings.writeLPr(); 10095 } 10096 10097 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10098 10099 synchronized (mPackages) { 10100 updatePermissionsLPw(newPackage.packageName, newPackage, 10101 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10102 ? UPDATE_PERMISSIONS_ALL : 0)); 10103 // For system-bundled packages, we assume that installing an upgraded version 10104 // of the package implies that the user actually wants to run that new code, 10105 // so we enable the package. 10106 if (isSystemApp(newPackage)) { 10107 // NB: implicit assumption that system package upgrades apply to all users 10108 if (DEBUG_INSTALL) { 10109 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10110 } 10111 PackageSetting ps = mSettings.mPackages.get(pkgName); 10112 if (ps != null) { 10113 if (res.origUsers != null) { 10114 for (int userHandle : res.origUsers) { 10115 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10116 userHandle, installerPackageName); 10117 } 10118 } 10119 // Also convey the prior install/uninstall state 10120 if (allUsers != null && perUserInstalled != null) { 10121 for (int i = 0; i < allUsers.length; i++) { 10122 if (DEBUG_INSTALL) { 10123 Slog.d(TAG, " user " + allUsers[i] 10124 + " => " + perUserInstalled[i]); 10125 } 10126 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10127 } 10128 // these install state changes will be persisted in the 10129 // upcoming call to mSettings.writeLPr(). 10130 } 10131 } 10132 } 10133 res.name = pkgName; 10134 res.uid = newPackage.applicationInfo.uid; 10135 res.pkg = newPackage; 10136 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10137 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10138 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10139 //to update install status 10140 mSettings.writeLPr(); 10141 } 10142 } 10143 10144 private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) { 10145 int pFlags = args.flags; 10146 String installerPackageName = args.installerPackageName; 10147 File tmpPackageFile = new File(args.getCodePath()); 10148 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10149 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10150 boolean replace = false; 10151 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10152 | (newInstall ? SCAN_NEW_INSTALL : 0); 10153 // Result object to be returned 10154 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10155 10156 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10157 // Retrieve PackageSettings and parse package 10158 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10159 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10160 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10161 PackageParser pp = new PackageParser(); 10162 pp.setSeparateProcesses(mSeparateProcesses); 10163 pp.setDisplayMetrics(mMetrics); 10164 10165 final PackageParser.Package pkg; 10166 try { 10167 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10168 } catch (PackageParserException e) { 10169 res.returnCode = e.error; 10170 return; 10171 } 10172 10173 String pkgName = res.name = pkg.packageName; 10174 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10175 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10176 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 10177 return; 10178 } 10179 } 10180 10181 try { 10182 pp.collectCertificates(pkg, parseFlags); 10183 pp.collectManifestDigest(pkg); 10184 } catch (PackageParserException e) { 10185 res.returnCode = e.error; 10186 return; 10187 } 10188 10189 /* If the installer passed in a manifest digest, compare it now. */ 10190 if (args.manifestDigest != null) { 10191 if (DEBUG_INSTALL) { 10192 final String parsedManifest = pkg.manifestDigest == null ? "null" 10193 : pkg.manifestDigest.toString(); 10194 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10195 + parsedManifest); 10196 } 10197 10198 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10199 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 10200 return; 10201 } 10202 } else if (DEBUG_INSTALL) { 10203 final String parsedManifest = pkg.manifestDigest == null 10204 ? "null" : pkg.manifestDigest.toString(); 10205 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10206 } 10207 10208 // Get rid of all references to package scan path via parser. 10209 pp = null; 10210 String oldCodePath = null; 10211 boolean systemApp = false; 10212 synchronized (mPackages) { 10213 // Check whether the newly-scanned package wants to define an already-defined perm 10214 int N = pkg.permissions.size(); 10215 for (int i = N-1; i >= 0; i--) { 10216 PackageParser.Permission perm = pkg.permissions.get(i); 10217 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10218 if (bp != null) { 10219 // If the defining package is signed with our cert, it's okay. This 10220 // also includes the "updating the same package" case, of course. 10221 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10222 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10223 // If the owning package is the system itself, we log but allow 10224 // install to proceed; we fail the install on all other permission 10225 // redefinitions. 10226 if (!bp.sourcePackage.equals("android")) { 10227 Slog.w(TAG, "Package " + pkg.packageName 10228 + " attempting to redeclare permission " + perm.info.name 10229 + " already owned by " + bp.sourcePackage); 10230 res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 10231 res.origPermission = perm.info.name; 10232 res.origPackage = bp.sourcePackage; 10233 return; 10234 } else { 10235 Slog.w(TAG, "Package " + pkg.packageName 10236 + " attempting to redeclare system permission " 10237 + perm.info.name + "; ignoring new declaration"); 10238 pkg.permissions.remove(i); 10239 } 10240 } 10241 } 10242 } 10243 10244 // Check if installing already existing package 10245 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10246 String oldName = mSettings.mRenamedPackages.get(pkgName); 10247 if (pkg.mOriginalPackages != null 10248 && pkg.mOriginalPackages.contains(oldName) 10249 && mPackages.containsKey(oldName)) { 10250 // This package is derived from an original package, 10251 // and this device has been updating from that original 10252 // name. We must continue using the original name, so 10253 // rename the new package here. 10254 pkg.setPackageName(oldName); 10255 pkgName = pkg.packageName; 10256 replace = true; 10257 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10258 + oldName + " pkgName=" + pkgName); 10259 } else if (mPackages.containsKey(pkgName)) { 10260 // This package, under its official name, already exists 10261 // on the device; we should replace it. 10262 replace = true; 10263 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10264 } 10265 } 10266 PackageSetting ps = mSettings.mPackages.get(pkgName); 10267 if (ps != null) { 10268 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10269 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10270 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10271 systemApp = (ps.pkg.applicationInfo.flags & 10272 ApplicationInfo.FLAG_SYSTEM) != 0; 10273 } 10274 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10275 } 10276 } 10277 10278 if (systemApp && onSd) { 10279 // Disable updates to system apps on sdcard 10280 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 10281 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10282 return; 10283 } 10284 10285 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10286 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10287 return; 10288 } 10289 10290 if (replace) { 10291 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10292 installerPackageName, res, args.abiOverride); 10293 } else { 10294 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10295 installerPackageName, res, args.abiOverride); 10296 } 10297 synchronized (mPackages) { 10298 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10299 if (ps != null) { 10300 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10301 } 10302 } 10303 } 10304 10305 private static boolean isForwardLocked(PackageParser.Package pkg) { 10306 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10307 } 10308 10309 10310 private boolean isForwardLocked(PackageSetting ps) { 10311 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10312 } 10313 10314 private static boolean isExternal(PackageParser.Package pkg) { 10315 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10316 } 10317 10318 private static boolean isExternal(PackageSetting ps) { 10319 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10320 } 10321 10322 private static boolean isSystemApp(PackageParser.Package pkg) { 10323 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10324 } 10325 10326 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10327 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10328 } 10329 10330 private static boolean isSystemApp(ApplicationInfo info) { 10331 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10332 } 10333 10334 private static boolean isSystemApp(PackageSetting ps) { 10335 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10336 } 10337 10338 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10339 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10340 } 10341 10342 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10343 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10344 } 10345 10346 private int packageFlagsToInstallFlags(PackageSetting ps) { 10347 int installFlags = 0; 10348 if (isExternal(ps)) { 10349 installFlags |= PackageManager.INSTALL_EXTERNAL; 10350 } 10351 if (isForwardLocked(ps)) { 10352 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10353 } 10354 return installFlags; 10355 } 10356 10357 private void deleteTempPackageFiles() { 10358 final FilenameFilter filter = new FilenameFilter() { 10359 public boolean accept(File dir, String name) { 10360 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10361 } 10362 }; 10363 deleteTempPackageFilesInDirectory(mAppInstallDir, filter); 10364 deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter); 10365 } 10366 10367 private static final void deleteTempPackageFilesInDirectory(File directory, 10368 FilenameFilter filter) { 10369 final File[] files = directory.listFiles(filter); 10370 if (!ArrayUtils.isEmpty(files)) { 10371 for (File file : files) { 10372 if (file.isDirectory()) { 10373 FileUtils.deleteContents(file); 10374 file.delete(); 10375 } else if (file.isFile()) { 10376 file.delete(); 10377 } 10378 } 10379 } 10380 } 10381 10382 private File createTempPackageDir(File installDir) throws IOException { 10383 int n = 0; 10384 while (n++ < 32) { 10385 final File file = new File(installDir, "vmdl" + mTempFileRandom.nextInt() + ".tmp"); 10386 try { 10387 Os.mkdir(file.getAbsolutePath(), 0755); 10388 Os.chmod(file.getAbsolutePath(), 0755); 10389 if (!SELinux.restorecon(file)) { 10390 throw new IOException("Failed to restorecon"); 10391 } 10392 return file; 10393 } catch (ErrnoException e) { 10394 if (e.errno == EEXIST) continue; 10395 throw e.rethrowAsIOException(); 10396 } 10397 } 10398 throw new IOException("Failed to create temp directory"); 10399 } 10400 10401 private File createTempPackageFile(File installDir) throws IOException { 10402 int n = 0; 10403 while (n++ < 32) { 10404 final File file = new File(installDir, "vmdl" + mTempFileRandom.nextInt() + ".tmp"); 10405 try { 10406 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10407 O_RDWR | O_CREAT | O_EXCL, 0644); 10408 IoUtils.closeQuietly(fd); 10409 Os.chmod(file.getAbsolutePath(), 0644); 10410 if (!SELinux.restorecon(file)) { 10411 throw new IOException("Failed to restorecon"); 10412 } 10413 return file; 10414 } catch (ErrnoException e) { 10415 if (e.errno == EEXIST) continue; 10416 throw e.rethrowAsIOException(); 10417 } 10418 } 10419 throw new IOException("Failed to create temp file"); 10420 } 10421 10422 @Override 10423 public void deletePackageAsUser(final String packageName, 10424 final IPackageDeleteObserver observer, 10425 final int userId, final int flags) { 10426 mContext.enforceCallingOrSelfPermission( 10427 android.Manifest.permission.DELETE_PACKAGES, null); 10428 final int uid = Binder.getCallingUid(); 10429 if (UserHandle.getUserId(uid) != userId) { 10430 mContext.enforceCallingPermission( 10431 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10432 "deletePackage for user " + userId); 10433 } 10434 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10435 try { 10436 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 10437 } catch (RemoteException re) { 10438 } 10439 return; 10440 } 10441 10442 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10443 // Queue up an async operation since the package deletion may take a little while. 10444 mHandler.post(new Runnable() { 10445 public void run() { 10446 mHandler.removeCallbacks(this); 10447 final int returnCode = deletePackageX(packageName, userId, flags); 10448 if (observer != null) { 10449 try { 10450 observer.packageDeleted(packageName, returnCode); 10451 } catch (RemoteException e) { 10452 Log.i(TAG, "Observer no longer exists."); 10453 } //end catch 10454 } //end if 10455 } //end run 10456 }); 10457 } 10458 10459 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10460 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10461 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10462 try { 10463 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10464 || dpm.isDeviceOwner(packageName))) { 10465 return true; 10466 } 10467 } catch (RemoteException e) { 10468 } 10469 return false; 10470 } 10471 10472 /** 10473 * This method is an internal method that could be get invoked either 10474 * to delete an installed package or to clean up a failed installation. 10475 * After deleting an installed package, a broadcast is sent to notify any 10476 * listeners that the package has been installed. For cleaning up a failed 10477 * installation, the broadcast is not necessary since the package's 10478 * installation wouldn't have sent the initial broadcast either 10479 * The key steps in deleting a package are 10480 * deleting the package information in internal structures like mPackages, 10481 * deleting the packages base directories through installd 10482 * updating mSettings to reflect current status 10483 * persisting settings for later use 10484 * sending a broadcast if necessary 10485 */ 10486 private int deletePackageX(String packageName, int userId, int flags) { 10487 final PackageRemovedInfo info = new PackageRemovedInfo(); 10488 final boolean res; 10489 10490 if (isPackageDeviceAdmin(packageName, userId)) { 10491 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10492 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10493 } 10494 10495 boolean removedForAllUsers = false; 10496 boolean systemUpdate = false; 10497 10498 // for the uninstall-updates case and restricted profiles, remember the per- 10499 // userhandle installed state 10500 int[] allUsers; 10501 boolean[] perUserInstalled; 10502 synchronized (mPackages) { 10503 PackageSetting ps = mSettings.mPackages.get(packageName); 10504 allUsers = sUserManager.getUserIds(); 10505 perUserInstalled = new boolean[allUsers.length]; 10506 for (int i = 0; i < allUsers.length; i++) { 10507 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10508 } 10509 } 10510 10511 synchronized (mInstallLock) { 10512 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10513 res = deletePackageLI(packageName, 10514 (flags & PackageManager.DELETE_ALL_USERS) != 0 10515 ? UserHandle.ALL : new UserHandle(userId), 10516 true, allUsers, perUserInstalled, 10517 flags | REMOVE_CHATTY, info, true); 10518 systemUpdate = info.isRemovedPackageSystemUpdate; 10519 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10520 removedForAllUsers = true; 10521 } 10522 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10523 + " removedForAllUsers=" + removedForAllUsers); 10524 } 10525 10526 if (res) { 10527 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10528 10529 // If the removed package was a system update, the old system package 10530 // was re-enabled; we need to broadcast this information 10531 if (systemUpdate) { 10532 Bundle extras = new Bundle(1); 10533 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10534 ? info.removedAppId : info.uid); 10535 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10536 10537 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10538 extras, null, null, null); 10539 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10540 extras, null, null, null); 10541 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10542 null, packageName, null, null); 10543 } 10544 } 10545 // Force a gc here. 10546 Runtime.getRuntime().gc(); 10547 // Delete the resources here after sending the broadcast to let 10548 // other processes clean up before deleting resources. 10549 if (info.args != null) { 10550 synchronized (mInstallLock) { 10551 info.args.doPostDeleteLI(true); 10552 } 10553 } 10554 10555 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10556 } 10557 10558 static class PackageRemovedInfo { 10559 String removedPackage; 10560 int uid = -1; 10561 int removedAppId = -1; 10562 int[] removedUsers = null; 10563 boolean isRemovedPackageSystemUpdate = false; 10564 // Clean up resources deleted packages. 10565 InstallArgs args = null; 10566 10567 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10568 Bundle extras = new Bundle(1); 10569 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10570 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10571 if (replacing) { 10572 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10573 } 10574 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10575 if (removedPackage != null) { 10576 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10577 extras, null, null, removedUsers); 10578 if (fullRemove && !replacing) { 10579 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10580 extras, null, null, removedUsers); 10581 } 10582 } 10583 if (removedAppId >= 0) { 10584 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10585 removedUsers); 10586 } 10587 } 10588 } 10589 10590 /* 10591 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10592 * flag is not set, the data directory is removed as well. 10593 * make sure this flag is set for partially installed apps. If not its meaningless to 10594 * delete a partially installed application. 10595 */ 10596 private void removePackageDataLI(PackageSetting ps, 10597 int[] allUserHandles, boolean[] perUserInstalled, 10598 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10599 String packageName = ps.name; 10600 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10601 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10602 // Retrieve object to delete permissions for shared user later on 10603 final PackageSetting deletedPs; 10604 // reader 10605 synchronized (mPackages) { 10606 deletedPs = mSettings.mPackages.get(packageName); 10607 if (outInfo != null) { 10608 outInfo.removedPackage = packageName; 10609 outInfo.removedUsers = deletedPs != null 10610 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10611 : null; 10612 } 10613 } 10614 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10615 removeDataDirsLI(packageName); 10616 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10617 } 10618 // writer 10619 synchronized (mPackages) { 10620 if (deletedPs != null) { 10621 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10622 if (outInfo != null) { 10623 mSettings.mKeySetManagerService.removeAppKeySetData(packageName); 10624 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10625 } 10626 if (deletedPs != null) { 10627 updatePermissionsLPw(deletedPs.name, null, 0); 10628 if (deletedPs.sharedUser != null) { 10629 // remove permissions associated with package 10630 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10631 } 10632 } 10633 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10634 } 10635 // make sure to preserve per-user disabled state if this removal was just 10636 // a downgrade of a system app to the factory package 10637 if (allUserHandles != null && perUserInstalled != null) { 10638 if (DEBUG_REMOVE) { 10639 Slog.d(TAG, "Propagating install state across downgrade"); 10640 } 10641 for (int i = 0; i < allUserHandles.length; i++) { 10642 if (DEBUG_REMOVE) { 10643 Slog.d(TAG, " user " + allUserHandles[i] 10644 + " => " + perUserInstalled[i]); 10645 } 10646 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10647 } 10648 } 10649 } 10650 // can downgrade to reader 10651 if (writeSettings) { 10652 // Save settings now 10653 mSettings.writeLPr(); 10654 } 10655 } 10656 if (outInfo != null) { 10657 // A user ID was deleted here. Go through all users and remove it 10658 // from KeyStore. 10659 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10660 } 10661 } 10662 10663 static boolean locationIsPrivileged(File path) { 10664 try { 10665 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10666 .getCanonicalPath(); 10667 return path.getCanonicalPath().startsWith(privilegedAppDir); 10668 } catch (IOException e) { 10669 Slog.e(TAG, "Unable to access code path " + path); 10670 } 10671 return false; 10672 } 10673 10674 /* 10675 * Tries to delete system package. 10676 */ 10677 private boolean deleteSystemPackageLI(PackageSetting newPs, 10678 int[] allUserHandles, boolean[] perUserInstalled, 10679 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10680 final boolean applyUserRestrictions 10681 = (allUserHandles != null) && (perUserInstalled != null); 10682 PackageSetting disabledPs = null; 10683 // Confirm if the system package has been updated 10684 // An updated system app can be deleted. This will also have to restore 10685 // the system pkg from system partition 10686 // reader 10687 synchronized (mPackages) { 10688 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10689 } 10690 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10691 + " disabledPs=" + disabledPs); 10692 if (disabledPs == null) { 10693 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10694 return false; 10695 } else if (DEBUG_REMOVE) { 10696 Slog.d(TAG, "Deleting system pkg from data partition"); 10697 } 10698 if (DEBUG_REMOVE) { 10699 if (applyUserRestrictions) { 10700 Slog.d(TAG, "Remembering install states:"); 10701 for (int i = 0; i < allUserHandles.length; i++) { 10702 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10703 } 10704 } 10705 } 10706 // Delete the updated package 10707 outInfo.isRemovedPackageSystemUpdate = true; 10708 if (disabledPs.versionCode < newPs.versionCode) { 10709 // Delete data for downgrades 10710 flags &= ~PackageManager.DELETE_KEEP_DATA; 10711 } else { 10712 // Preserve data by setting flag 10713 flags |= PackageManager.DELETE_KEEP_DATA; 10714 } 10715 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10716 allUserHandles, perUserInstalled, outInfo, writeSettings); 10717 if (!ret) { 10718 return false; 10719 } 10720 // writer 10721 synchronized (mPackages) { 10722 // Reinstate the old system package 10723 mSettings.enableSystemPackageLPw(newPs.name); 10724 // Remove any native libraries from the upgraded package. 10725 NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString); 10726 } 10727 // Install the system package 10728 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10729 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10730 if (locationIsPrivileged(disabledPs.codePath)) { 10731 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10732 } 10733 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath, 10734 parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null); 10735 10736 if (newPkg == null) { 10737 Slog.w(TAG, "Failed to restore system package:" + newPs.name 10738 + " with error:" + mLastScanError); 10739 return false; 10740 } 10741 // writer 10742 synchronized (mPackages) { 10743 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10744 setInternalAppNativeLibraryPath(newPkg, ps); 10745 updatePermissionsLPw(newPkg.packageName, newPkg, 10746 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10747 if (applyUserRestrictions) { 10748 if (DEBUG_REMOVE) { 10749 Slog.d(TAG, "Propagating install state across reinstall"); 10750 } 10751 for (int i = 0; i < allUserHandles.length; i++) { 10752 if (DEBUG_REMOVE) { 10753 Slog.d(TAG, " user " + allUserHandles[i] 10754 + " => " + perUserInstalled[i]); 10755 } 10756 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10757 } 10758 // Regardless of writeSettings we need to ensure that this restriction 10759 // state propagation is persisted 10760 mSettings.writeAllUsersPackageRestrictionsLPr(); 10761 } 10762 // can downgrade to reader here 10763 if (writeSettings) { 10764 mSettings.writeLPr(); 10765 } 10766 } 10767 return true; 10768 } 10769 10770 private boolean deleteInstalledPackageLI(PackageSetting ps, 10771 boolean deleteCodeAndResources, int flags, 10772 int[] allUserHandles, boolean[] perUserInstalled, 10773 PackageRemovedInfo outInfo, boolean writeSettings) { 10774 if (outInfo != null) { 10775 outInfo.uid = ps.appId; 10776 } 10777 10778 // Delete package data from internal structures and also remove data if flag is set 10779 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10780 10781 // Delete application code and resources 10782 if (deleteCodeAndResources && (outInfo != null)) { 10783 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10784 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 10785 getAppInstructionSetFromSettings(ps)); 10786 } 10787 return true; 10788 } 10789 10790 @Override 10791 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10792 int userId) { 10793 mContext.enforceCallingOrSelfPermission( 10794 android.Manifest.permission.DELETE_PACKAGES, null); 10795 synchronized (mPackages) { 10796 PackageSetting ps = mSettings.mPackages.get(packageName); 10797 if (ps == null) { 10798 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10799 return false; 10800 } 10801 if (!ps.getInstalled(userId)) { 10802 // Can't block uninstall for an app that is not installed or enabled. 10803 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10804 return false; 10805 } 10806 ps.setBlockUninstall(blockUninstall, userId); 10807 mSettings.writePackageRestrictionsLPr(userId); 10808 } 10809 return true; 10810 } 10811 10812 @Override 10813 public boolean getBlockUninstallForUser(String packageName, int userId) { 10814 synchronized (mPackages) { 10815 PackageSetting ps = mSettings.mPackages.get(packageName); 10816 if (ps == null) { 10817 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10818 return false; 10819 } 10820 return ps.getBlockUninstall(userId); 10821 } 10822 } 10823 10824 /* 10825 * This method handles package deletion in general 10826 */ 10827 private boolean deletePackageLI(String packageName, UserHandle user, 10828 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10829 int flags, PackageRemovedInfo outInfo, 10830 boolean writeSettings) { 10831 if (packageName == null) { 10832 Slog.w(TAG, "Attempt to delete null packageName."); 10833 return false; 10834 } 10835 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10836 PackageSetting ps; 10837 boolean dataOnly = false; 10838 int removeUser = -1; 10839 int appId = -1; 10840 synchronized (mPackages) { 10841 ps = mSettings.mPackages.get(packageName); 10842 if (ps == null) { 10843 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10844 return false; 10845 } 10846 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10847 && user.getIdentifier() != UserHandle.USER_ALL) { 10848 // The caller is asking that the package only be deleted for a single 10849 // user. To do this, we just mark its uninstalled state and delete 10850 // its data. If this is a system app, we only allow this to happen if 10851 // they have set the special DELETE_SYSTEM_APP which requests different 10852 // semantics than normal for uninstalling system apps. 10853 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10854 ps.setUserState(user.getIdentifier(), 10855 COMPONENT_ENABLED_STATE_DEFAULT, 10856 false, //installed 10857 true, //stopped 10858 true, //notLaunched 10859 false, //blocked 10860 null, null, null, 10861 false // blockUninstall 10862 ); 10863 if (!isSystemApp(ps)) { 10864 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10865 // Other user still have this package installed, so all 10866 // we need to do is clear this user's data and save that 10867 // it is uninstalled. 10868 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10869 removeUser = user.getIdentifier(); 10870 appId = ps.appId; 10871 mSettings.writePackageRestrictionsLPr(removeUser); 10872 } else { 10873 // We need to set it back to 'installed' so the uninstall 10874 // broadcasts will be sent correctly. 10875 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10876 ps.setInstalled(true, user.getIdentifier()); 10877 } 10878 } else { 10879 // This is a system app, so we assume that the 10880 // other users still have this package installed, so all 10881 // we need to do is clear this user's data and save that 10882 // it is uninstalled. 10883 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10884 removeUser = user.getIdentifier(); 10885 appId = ps.appId; 10886 mSettings.writePackageRestrictionsLPr(removeUser); 10887 } 10888 } 10889 } 10890 10891 if (removeUser >= 0) { 10892 // From above, we determined that we are deleting this only 10893 // for a single user. Continue the work here. 10894 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10895 if (outInfo != null) { 10896 outInfo.removedPackage = packageName; 10897 outInfo.removedAppId = appId; 10898 outInfo.removedUsers = new int[] {removeUser}; 10899 } 10900 mInstaller.clearUserData(packageName, removeUser); 10901 removeKeystoreDataIfNeeded(removeUser, appId); 10902 schedulePackageCleaning(packageName, removeUser, false); 10903 return true; 10904 } 10905 10906 if (dataOnly) { 10907 // Delete application data first 10908 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10909 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10910 return true; 10911 } 10912 10913 boolean ret = false; 10914 if (isSystemApp(ps)) { 10915 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10916 // When an updated system application is deleted we delete the existing resources as well and 10917 // fall back to existing code in system partition 10918 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10919 flags, outInfo, writeSettings); 10920 } else { 10921 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10922 // Kill application pre-emptively especially for apps on sd. 10923 killApplication(packageName, ps.appId, "uninstall pkg"); 10924 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10925 allUserHandles, perUserInstalled, 10926 outInfo, writeSettings); 10927 } 10928 10929 return ret; 10930 } 10931 10932 private final class ClearStorageConnection implements ServiceConnection { 10933 IMediaContainerService mContainerService; 10934 10935 @Override 10936 public void onServiceConnected(ComponentName name, IBinder service) { 10937 synchronized (this) { 10938 mContainerService = IMediaContainerService.Stub.asInterface(service); 10939 notifyAll(); 10940 } 10941 } 10942 10943 @Override 10944 public void onServiceDisconnected(ComponentName name) { 10945 } 10946 } 10947 10948 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10949 final boolean mounted; 10950 if (Environment.isExternalStorageEmulated()) { 10951 mounted = true; 10952 } else { 10953 final String status = Environment.getExternalStorageState(); 10954 10955 mounted = status.equals(Environment.MEDIA_MOUNTED) 10956 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 10957 } 10958 10959 if (!mounted) { 10960 return; 10961 } 10962 10963 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 10964 int[] users; 10965 if (userId == UserHandle.USER_ALL) { 10966 users = sUserManager.getUserIds(); 10967 } else { 10968 users = new int[] { userId }; 10969 } 10970 final ClearStorageConnection conn = new ClearStorageConnection(); 10971 if (mContext.bindServiceAsUser( 10972 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 10973 try { 10974 for (int curUser : users) { 10975 long timeout = SystemClock.uptimeMillis() + 5000; 10976 synchronized (conn) { 10977 long now = SystemClock.uptimeMillis(); 10978 while (conn.mContainerService == null && now < timeout) { 10979 try { 10980 conn.wait(timeout - now); 10981 } catch (InterruptedException e) { 10982 } 10983 } 10984 } 10985 if (conn.mContainerService == null) { 10986 return; 10987 } 10988 10989 final UserEnvironment userEnv = new UserEnvironment(curUser); 10990 clearDirectory(conn.mContainerService, 10991 userEnv.buildExternalStorageAppCacheDirs(packageName)); 10992 if (allData) { 10993 clearDirectory(conn.mContainerService, 10994 userEnv.buildExternalStorageAppDataDirs(packageName)); 10995 clearDirectory(conn.mContainerService, 10996 userEnv.buildExternalStorageAppMediaDirs(packageName)); 10997 } 10998 } 10999 } finally { 11000 mContext.unbindService(conn); 11001 } 11002 } 11003 } 11004 11005 @Override 11006 public void clearApplicationUserData(final String packageName, 11007 final IPackageDataObserver observer, final int userId) { 11008 mContext.enforceCallingOrSelfPermission( 11009 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11010 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11011 // Queue up an async operation since the package deletion may take a little while. 11012 mHandler.post(new Runnable() { 11013 public void run() { 11014 mHandler.removeCallbacks(this); 11015 final boolean succeeded; 11016 synchronized (mInstallLock) { 11017 succeeded = clearApplicationUserDataLI(packageName, userId); 11018 } 11019 clearExternalStorageDataSync(packageName, userId, true); 11020 if (succeeded) { 11021 // invoke DeviceStorageMonitor's update method to clear any notifications 11022 DeviceStorageMonitorInternal 11023 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11024 if (dsm != null) { 11025 dsm.checkMemory(); 11026 } 11027 } 11028 if(observer != null) { 11029 try { 11030 observer.onRemoveCompleted(packageName, succeeded); 11031 } catch (RemoteException e) { 11032 Log.i(TAG, "Observer no longer exists."); 11033 } 11034 } //end if observer 11035 } //end run 11036 }); 11037 } 11038 11039 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11040 if (packageName == null) { 11041 Slog.w(TAG, "Attempt to delete null packageName."); 11042 return false; 11043 } 11044 PackageParser.Package p; 11045 boolean dataOnly = false; 11046 final int appId; 11047 synchronized (mPackages) { 11048 p = mPackages.get(packageName); 11049 if (p == null) { 11050 dataOnly = true; 11051 PackageSetting ps = mSettings.mPackages.get(packageName); 11052 if ((ps == null) || (ps.pkg == null)) { 11053 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11054 return false; 11055 } 11056 p = ps.pkg; 11057 } 11058 if (!dataOnly) { 11059 // need to check this only for fully installed applications 11060 if (p == null) { 11061 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11062 return false; 11063 } 11064 final ApplicationInfo applicationInfo = p.applicationInfo; 11065 if (applicationInfo == null) { 11066 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11067 return false; 11068 } 11069 } 11070 if (p != null && p.applicationInfo != null) { 11071 appId = p.applicationInfo.uid; 11072 } else { 11073 appId = -1; 11074 } 11075 } 11076 int retCode = mInstaller.clearUserData(packageName, userId); 11077 if (retCode < 0) { 11078 Slog.w(TAG, "Couldn't remove cache files for package: " 11079 + packageName); 11080 return false; 11081 } 11082 removeKeystoreDataIfNeeded(userId, appId); 11083 return true; 11084 } 11085 11086 /** 11087 * Remove entries from the keystore daemon. Will only remove it if the 11088 * {@code appId} is valid. 11089 */ 11090 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11091 if (appId < 0) { 11092 return; 11093 } 11094 11095 final KeyStore keyStore = KeyStore.getInstance(); 11096 if (keyStore != null) { 11097 if (userId == UserHandle.USER_ALL) { 11098 for (final int individual : sUserManager.getUserIds()) { 11099 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11100 } 11101 } else { 11102 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11103 } 11104 } else { 11105 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11106 } 11107 } 11108 11109 @Override 11110 public void deleteApplicationCacheFiles(final String packageName, 11111 final IPackageDataObserver observer) { 11112 mContext.enforceCallingOrSelfPermission( 11113 android.Manifest.permission.DELETE_CACHE_FILES, null); 11114 // Queue up an async operation since the package deletion may take a little while. 11115 final int userId = UserHandle.getCallingUserId(); 11116 mHandler.post(new Runnable() { 11117 public void run() { 11118 mHandler.removeCallbacks(this); 11119 final boolean succeded; 11120 synchronized (mInstallLock) { 11121 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11122 } 11123 clearExternalStorageDataSync(packageName, userId, false); 11124 if(observer != null) { 11125 try { 11126 observer.onRemoveCompleted(packageName, succeded); 11127 } catch (RemoteException e) { 11128 Log.i(TAG, "Observer no longer exists."); 11129 } 11130 } //end if observer 11131 } //end run 11132 }); 11133 } 11134 11135 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11136 if (packageName == null) { 11137 Slog.w(TAG, "Attempt to delete null packageName."); 11138 return false; 11139 } 11140 PackageParser.Package p; 11141 synchronized (mPackages) { 11142 p = mPackages.get(packageName); 11143 } 11144 if (p == null) { 11145 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11146 return false; 11147 } 11148 final ApplicationInfo applicationInfo = p.applicationInfo; 11149 if (applicationInfo == null) { 11150 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11151 return false; 11152 } 11153 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11154 if (retCode < 0) { 11155 Slog.w(TAG, "Couldn't remove cache files for package: " 11156 + packageName + " u" + userId); 11157 return false; 11158 } 11159 return true; 11160 } 11161 11162 @Override 11163 public void getPackageSizeInfo(final String packageName, int userHandle, 11164 final IPackageStatsObserver observer) { 11165 mContext.enforceCallingOrSelfPermission( 11166 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11167 if (packageName == null) { 11168 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11169 } 11170 11171 PackageStats stats = new PackageStats(packageName, userHandle); 11172 11173 /* 11174 * Queue up an async operation since the package measurement may take a 11175 * little while. 11176 */ 11177 Message msg = mHandler.obtainMessage(INIT_COPY); 11178 msg.obj = new MeasureParams(stats, observer); 11179 mHandler.sendMessage(msg); 11180 } 11181 11182 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11183 PackageStats pStats) { 11184 if (packageName == null) { 11185 Slog.w(TAG, "Attempt to get size of null packageName."); 11186 return false; 11187 } 11188 PackageParser.Package p; 11189 boolean dataOnly = false; 11190 String libDirPath = null; 11191 String asecPath = null; 11192 PackageSetting ps = null; 11193 synchronized (mPackages) { 11194 p = mPackages.get(packageName); 11195 ps = mSettings.mPackages.get(packageName); 11196 if(p == null) { 11197 dataOnly = true; 11198 if((ps == null) || (ps.pkg == null)) { 11199 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11200 return false; 11201 } 11202 p = ps.pkg; 11203 } 11204 if (ps != null) { 11205 libDirPath = ps.nativeLibraryPathString; 11206 } 11207 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11208 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11209 if (secureContainerId != null) { 11210 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11211 } 11212 } 11213 } 11214 String publicSrcDir = null; 11215 if(!dataOnly) { 11216 final ApplicationInfo applicationInfo = p.applicationInfo; 11217 if (applicationInfo == null) { 11218 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11219 return false; 11220 } 11221 if (isForwardLocked(p)) { 11222 publicSrcDir = applicationInfo.getBaseResourcePath(); 11223 } 11224 } 11225 // TODO: extend to measure size of split APKs 11226 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirPath, 11227 publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps), 11228 pStats); 11229 if (res < 0) { 11230 return false; 11231 } 11232 11233 // Fix-up for forward-locked applications in ASEC containers. 11234 if (!isExternal(p)) { 11235 pStats.codeSize += pStats.externalCodeSize; 11236 pStats.externalCodeSize = 0L; 11237 } 11238 11239 return true; 11240 } 11241 11242 11243 @Override 11244 public void addPackageToPreferred(String packageName) { 11245 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11246 } 11247 11248 @Override 11249 public void removePackageFromPreferred(String packageName) { 11250 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11251 } 11252 11253 @Override 11254 public List<PackageInfo> getPreferredPackages(int flags) { 11255 return new ArrayList<PackageInfo>(); 11256 } 11257 11258 private int getUidTargetSdkVersionLockedLPr(int uid) { 11259 Object obj = mSettings.getUserIdLPr(uid); 11260 if (obj instanceof SharedUserSetting) { 11261 final SharedUserSetting sus = (SharedUserSetting) obj; 11262 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11263 final Iterator<PackageSetting> it = sus.packages.iterator(); 11264 while (it.hasNext()) { 11265 final PackageSetting ps = it.next(); 11266 if (ps.pkg != null) { 11267 int v = ps.pkg.applicationInfo.targetSdkVersion; 11268 if (v < vers) vers = v; 11269 } 11270 } 11271 return vers; 11272 } else if (obj instanceof PackageSetting) { 11273 final PackageSetting ps = (PackageSetting) obj; 11274 if (ps.pkg != null) { 11275 return ps.pkg.applicationInfo.targetSdkVersion; 11276 } 11277 } 11278 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11279 } 11280 11281 @Override 11282 public void addPreferredActivity(IntentFilter filter, int match, 11283 ComponentName[] set, ComponentName activity, int userId) { 11284 addPreferredActivityInternal(filter, match, set, activity, true, userId); 11285 } 11286 11287 private void addPreferredActivityInternal(IntentFilter filter, int match, 11288 ComponentName[] set, ComponentName activity, boolean always, int userId) { 11289 // writer 11290 int callingUid = Binder.getCallingUid(); 11291 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11292 if (filter.countActions() == 0) { 11293 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11294 return; 11295 } 11296 synchronized (mPackages) { 11297 if (mContext.checkCallingOrSelfPermission( 11298 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11299 != PackageManager.PERMISSION_GRANTED) { 11300 if (getUidTargetSdkVersionLockedLPr(callingUid) 11301 < Build.VERSION_CODES.FROYO) { 11302 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11303 + callingUid); 11304 return; 11305 } 11306 mContext.enforceCallingOrSelfPermission( 11307 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11308 } 11309 11310 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 11311 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11312 mSettings.editPreferredActivitiesLPw(userId).addFilter( 11313 new PreferredActivity(filter, match, set, activity, always)); 11314 mSettings.writePackageRestrictionsLPr(userId); 11315 } 11316 } 11317 11318 @Override 11319 public void replacePreferredActivity(IntentFilter filter, int match, 11320 ComponentName[] set, ComponentName activity) { 11321 if (filter.countActions() != 1) { 11322 throw new IllegalArgumentException( 11323 "replacePreferredActivity expects filter to have only 1 action."); 11324 } 11325 if (filter.countDataAuthorities() != 0 11326 || filter.countDataPaths() != 0 11327 || filter.countDataSchemes() > 1 11328 || filter.countDataTypes() != 0) { 11329 throw new IllegalArgumentException( 11330 "replacePreferredActivity expects filter to have no data authorities, " + 11331 "paths, or types; and at most one scheme."); 11332 } 11333 synchronized (mPackages) { 11334 if (mContext.checkCallingOrSelfPermission( 11335 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11336 != PackageManager.PERMISSION_GRANTED) { 11337 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11338 < Build.VERSION_CODES.FROYO) { 11339 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11340 + Binder.getCallingUid()); 11341 return; 11342 } 11343 mContext.enforceCallingOrSelfPermission( 11344 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11345 } 11346 11347 final int callingUserId = UserHandle.getCallingUserId(); 11348 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 11349 if (pir != null) { 11350 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 11351 if (filter.countDataSchemes() == 1) { 11352 Uri.Builder builder = new Uri.Builder(); 11353 builder.scheme(filter.getDataScheme(0)); 11354 intent.setData(builder.build()); 11355 } 11356 List<PreferredActivity> matches = pir.queryIntent( 11357 intent, null, true, callingUserId); 11358 if (DEBUG_PREFERRED) { 11359 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 11360 } 11361 for (int i = 0; i < matches.size(); i++) { 11362 PreferredActivity pa = matches.get(i); 11363 if (DEBUG_PREFERRED) { 11364 Slog.i(TAG, "Removing preferred activity " 11365 + pa.mPref.mComponent + ":"); 11366 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11367 } 11368 pir.removeFilter(pa); 11369 } 11370 } 11371 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 11372 } 11373 } 11374 11375 @Override 11376 public void clearPackagePreferredActivities(String packageName) { 11377 final int uid = Binder.getCallingUid(); 11378 // writer 11379 synchronized (mPackages) { 11380 PackageParser.Package pkg = mPackages.get(packageName); 11381 if (pkg == null || pkg.applicationInfo.uid != uid) { 11382 if (mContext.checkCallingOrSelfPermission( 11383 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11384 != PackageManager.PERMISSION_GRANTED) { 11385 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11386 < Build.VERSION_CODES.FROYO) { 11387 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11388 + Binder.getCallingUid()); 11389 return; 11390 } 11391 mContext.enforceCallingOrSelfPermission( 11392 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11393 } 11394 } 11395 11396 int user = UserHandle.getCallingUserId(); 11397 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11398 mSettings.writePackageRestrictionsLPr(user); 11399 scheduleWriteSettingsLocked(); 11400 } 11401 } 11402 } 11403 11404 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11405 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11406 ArrayList<PreferredActivity> removed = null; 11407 boolean changed = false; 11408 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11409 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11410 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11411 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11412 continue; 11413 } 11414 Iterator<PreferredActivity> it = pir.filterIterator(); 11415 while (it.hasNext()) { 11416 PreferredActivity pa = it.next(); 11417 // Mark entry for removal only if it matches the package name 11418 // and the entry is of type "always". 11419 if (packageName == null || 11420 (pa.mPref.mComponent.getPackageName().equals(packageName) 11421 && pa.mPref.mAlways)) { 11422 if (removed == null) { 11423 removed = new ArrayList<PreferredActivity>(); 11424 } 11425 removed.add(pa); 11426 } 11427 } 11428 if (removed != null) { 11429 for (int j=0; j<removed.size(); j++) { 11430 PreferredActivity pa = removed.get(j); 11431 pir.removeFilter(pa); 11432 } 11433 changed = true; 11434 } 11435 } 11436 return changed; 11437 } 11438 11439 @Override 11440 public void resetPreferredActivities(int userId) { 11441 mContext.enforceCallingOrSelfPermission( 11442 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11443 // writer 11444 synchronized (mPackages) { 11445 int user = UserHandle.getCallingUserId(); 11446 clearPackagePreferredActivitiesLPw(null, user); 11447 mSettings.readDefaultPreferredAppsLPw(this, user); 11448 mSettings.writePackageRestrictionsLPr(user); 11449 scheduleWriteSettingsLocked(); 11450 } 11451 } 11452 11453 @Override 11454 public int getPreferredActivities(List<IntentFilter> outFilters, 11455 List<ComponentName> outActivities, String packageName) { 11456 11457 int num = 0; 11458 final int userId = UserHandle.getCallingUserId(); 11459 // reader 11460 synchronized (mPackages) { 11461 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11462 if (pir != null) { 11463 final Iterator<PreferredActivity> it = pir.filterIterator(); 11464 while (it.hasNext()) { 11465 final PreferredActivity pa = it.next(); 11466 if (packageName == null 11467 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11468 && pa.mPref.mAlways)) { 11469 if (outFilters != null) { 11470 outFilters.add(new IntentFilter(pa)); 11471 } 11472 if (outActivities != null) { 11473 outActivities.add(pa.mPref.mComponent); 11474 } 11475 } 11476 } 11477 } 11478 } 11479 11480 return num; 11481 } 11482 11483 @Override 11484 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11485 int userId) { 11486 int callingUid = Binder.getCallingUid(); 11487 if (callingUid != Process.SYSTEM_UID) { 11488 throw new SecurityException( 11489 "addPersistentPreferredActivity can only be run by the system"); 11490 } 11491 if (filter.countActions() == 0) { 11492 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11493 return; 11494 } 11495 synchronized (mPackages) { 11496 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11497 " :"); 11498 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11499 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11500 new PersistentPreferredActivity(filter, activity)); 11501 mSettings.writePackageRestrictionsLPr(userId); 11502 } 11503 } 11504 11505 @Override 11506 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11507 int callingUid = Binder.getCallingUid(); 11508 if (callingUid != Process.SYSTEM_UID) { 11509 throw new SecurityException( 11510 "clearPackagePersistentPreferredActivities can only be run by the system"); 11511 } 11512 ArrayList<PersistentPreferredActivity> removed = null; 11513 boolean changed = false; 11514 synchronized (mPackages) { 11515 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11516 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11517 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11518 .valueAt(i); 11519 if (userId != thisUserId) { 11520 continue; 11521 } 11522 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11523 while (it.hasNext()) { 11524 PersistentPreferredActivity ppa = it.next(); 11525 // Mark entry for removal only if it matches the package name. 11526 if (ppa.mComponent.getPackageName().equals(packageName)) { 11527 if (removed == null) { 11528 removed = new ArrayList<PersistentPreferredActivity>(); 11529 } 11530 removed.add(ppa); 11531 } 11532 } 11533 if (removed != null) { 11534 for (int j=0; j<removed.size(); j++) { 11535 PersistentPreferredActivity ppa = removed.get(j); 11536 ppir.removeFilter(ppa); 11537 } 11538 changed = true; 11539 } 11540 } 11541 11542 if (changed) { 11543 mSettings.writePackageRestrictionsLPr(userId); 11544 } 11545 } 11546 } 11547 11548 @Override 11549 public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId, 11550 int targetUserId, int flags) { 11551 mContext.enforceCallingOrSelfPermission( 11552 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11553 if (intentFilter.countActions() == 0) { 11554 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11555 return; 11556 } 11557 synchronized (mPackages) { 11558 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11559 targetUserId, flags); 11560 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11561 mSettings.writePackageRestrictionsLPr(sourceUserId); 11562 } 11563 } 11564 11565 public void addCrossProfileIntentsForPackage(String packageName, 11566 int sourceUserId, int targetUserId) { 11567 mContext.enforceCallingOrSelfPermission( 11568 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11569 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11570 mSettings.writePackageRestrictionsLPr(sourceUserId); 11571 } 11572 11573 public void removeCrossProfileIntentsForPackage(String packageName, 11574 int sourceUserId, int targetUserId) { 11575 mContext.enforceCallingOrSelfPermission( 11576 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11577 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11578 mSettings.writePackageRestrictionsLPr(sourceUserId); 11579 } 11580 11581 @Override 11582 public void clearCrossProfileIntentFilters(int sourceUserId) { 11583 mContext.enforceCallingOrSelfPermission( 11584 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11585 synchronized (mPackages) { 11586 CrossProfileIntentResolver resolver = 11587 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11588 HashSet<CrossProfileIntentFilter> set = 11589 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11590 for (CrossProfileIntentFilter filter : set) { 11591 if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) { 11592 resolver.removeFilter(filter); 11593 } 11594 } 11595 mSettings.writePackageRestrictionsLPr(sourceUserId); 11596 } 11597 } 11598 11599 @Override 11600 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11601 Intent intent = new Intent(Intent.ACTION_MAIN); 11602 intent.addCategory(Intent.CATEGORY_HOME); 11603 11604 final int callingUserId = UserHandle.getCallingUserId(); 11605 List<ResolveInfo> list = queryIntentActivities(intent, null, 11606 PackageManager.GET_META_DATA, callingUserId); 11607 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11608 true, false, false, callingUserId); 11609 11610 allHomeCandidates.clear(); 11611 if (list != null) { 11612 for (ResolveInfo ri : list) { 11613 allHomeCandidates.add(ri); 11614 } 11615 } 11616 return (preferred == null || preferred.activityInfo == null) 11617 ? null 11618 : new ComponentName(preferred.activityInfo.packageName, 11619 preferred.activityInfo.name); 11620 } 11621 11622 @Override 11623 public void setApplicationEnabledSetting(String appPackageName, 11624 int newState, int flags, int userId, String callingPackage) { 11625 if (!sUserManager.exists(userId)) return; 11626 if (callingPackage == null) { 11627 callingPackage = Integer.toString(Binder.getCallingUid()); 11628 } 11629 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11630 } 11631 11632 @Override 11633 public void setComponentEnabledSetting(ComponentName componentName, 11634 int newState, int flags, int userId) { 11635 if (!sUserManager.exists(userId)) return; 11636 setEnabledSetting(componentName.getPackageName(), 11637 componentName.getClassName(), newState, flags, userId, null); 11638 } 11639 11640 private void setEnabledSetting(final String packageName, String className, int newState, 11641 final int flags, int userId, String callingPackage) { 11642 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11643 || newState == COMPONENT_ENABLED_STATE_ENABLED 11644 || newState == COMPONENT_ENABLED_STATE_DISABLED 11645 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11646 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11647 throw new IllegalArgumentException("Invalid new component state: " 11648 + newState); 11649 } 11650 PackageSetting pkgSetting; 11651 final int uid = Binder.getCallingUid(); 11652 final int permission = mContext.checkCallingOrSelfPermission( 11653 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11654 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11655 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11656 boolean sendNow = false; 11657 boolean isApp = (className == null); 11658 String componentName = isApp ? packageName : className; 11659 int packageUid = -1; 11660 ArrayList<String> components; 11661 11662 // writer 11663 synchronized (mPackages) { 11664 pkgSetting = mSettings.mPackages.get(packageName); 11665 if (pkgSetting == null) { 11666 if (className == null) { 11667 throw new IllegalArgumentException( 11668 "Unknown package: " + packageName); 11669 } 11670 throw new IllegalArgumentException( 11671 "Unknown component: " + packageName 11672 + "/" + className); 11673 } 11674 // Allow root and verify that userId is not being specified by a different user 11675 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11676 throw new SecurityException( 11677 "Permission Denial: attempt to change component state from pid=" 11678 + Binder.getCallingPid() 11679 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11680 } 11681 if (className == null) { 11682 // We're dealing with an application/package level state change 11683 if (pkgSetting.getEnabled(userId) == newState) { 11684 // Nothing to do 11685 return; 11686 } 11687 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11688 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11689 // Don't care about who enables an app. 11690 callingPackage = null; 11691 } 11692 pkgSetting.setEnabled(newState, userId, callingPackage); 11693 // pkgSetting.pkg.mSetEnabled = newState; 11694 } else { 11695 // We're dealing with a component level state change 11696 // First, verify that this is a valid class name. 11697 PackageParser.Package pkg = pkgSetting.pkg; 11698 if (pkg == null || !pkg.hasComponentClassName(className)) { 11699 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11700 throw new IllegalArgumentException("Component class " + className 11701 + " does not exist in " + packageName); 11702 } else { 11703 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11704 + className + " does not exist in " + packageName); 11705 } 11706 } 11707 switch (newState) { 11708 case COMPONENT_ENABLED_STATE_ENABLED: 11709 if (!pkgSetting.enableComponentLPw(className, userId)) { 11710 return; 11711 } 11712 break; 11713 case COMPONENT_ENABLED_STATE_DISABLED: 11714 if (!pkgSetting.disableComponentLPw(className, userId)) { 11715 return; 11716 } 11717 break; 11718 case COMPONENT_ENABLED_STATE_DEFAULT: 11719 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11720 return; 11721 } 11722 break; 11723 default: 11724 Slog.e(TAG, "Invalid new component state: " + newState); 11725 return; 11726 } 11727 } 11728 mSettings.writePackageRestrictionsLPr(userId); 11729 components = mPendingBroadcasts.get(userId, packageName); 11730 final boolean newPackage = components == null; 11731 if (newPackage) { 11732 components = new ArrayList<String>(); 11733 } 11734 if (!components.contains(componentName)) { 11735 components.add(componentName); 11736 } 11737 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11738 sendNow = true; 11739 // Purge entry from pending broadcast list if another one exists already 11740 // since we are sending one right away. 11741 mPendingBroadcasts.remove(userId, packageName); 11742 } else { 11743 if (newPackage) { 11744 mPendingBroadcasts.put(userId, packageName, components); 11745 } 11746 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11747 // Schedule a message 11748 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11749 } 11750 } 11751 } 11752 11753 long callingId = Binder.clearCallingIdentity(); 11754 try { 11755 if (sendNow) { 11756 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11757 sendPackageChangedBroadcast(packageName, 11758 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11759 } 11760 } finally { 11761 Binder.restoreCallingIdentity(callingId); 11762 } 11763 } 11764 11765 private void sendPackageChangedBroadcast(String packageName, 11766 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11767 if (DEBUG_INSTALL) 11768 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11769 + componentNames); 11770 Bundle extras = new Bundle(4); 11771 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11772 String nameList[] = new String[componentNames.size()]; 11773 componentNames.toArray(nameList); 11774 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11775 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11776 extras.putInt(Intent.EXTRA_UID, packageUid); 11777 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11778 new int[] {UserHandle.getUserId(packageUid)}); 11779 } 11780 11781 @Override 11782 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11783 if (!sUserManager.exists(userId)) return; 11784 final int uid = Binder.getCallingUid(); 11785 final int permission = mContext.checkCallingOrSelfPermission( 11786 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11787 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11788 enforceCrossUserPermission(uid, userId, true, "stop package"); 11789 // writer 11790 synchronized (mPackages) { 11791 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11792 uid, userId)) { 11793 scheduleWritePackageRestrictionsLocked(userId); 11794 } 11795 } 11796 } 11797 11798 @Override 11799 public String getInstallerPackageName(String packageName) { 11800 // reader 11801 synchronized (mPackages) { 11802 return mSettings.getInstallerPackageNameLPr(packageName); 11803 } 11804 } 11805 11806 @Override 11807 public int getApplicationEnabledSetting(String packageName, int userId) { 11808 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11809 int uid = Binder.getCallingUid(); 11810 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11811 // reader 11812 synchronized (mPackages) { 11813 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11814 } 11815 } 11816 11817 @Override 11818 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11819 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11820 int uid = Binder.getCallingUid(); 11821 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11822 // reader 11823 synchronized (mPackages) { 11824 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11825 } 11826 } 11827 11828 @Override 11829 public void enterSafeMode() { 11830 enforceSystemOrRoot("Only the system can request entering safe mode"); 11831 11832 if (!mSystemReady) { 11833 mSafeMode = true; 11834 } 11835 } 11836 11837 @Override 11838 public void systemReady() { 11839 mSystemReady = true; 11840 11841 // Read the compatibilty setting when the system is ready. 11842 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11843 mContext.getContentResolver(), 11844 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11845 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11846 if (DEBUG_SETTINGS) { 11847 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11848 } 11849 11850 synchronized (mPackages) { 11851 // Verify that all of the preferred activity components actually 11852 // exist. It is possible for applications to be updated and at 11853 // that point remove a previously declared activity component that 11854 // had been set as a preferred activity. We try to clean this up 11855 // the next time we encounter that preferred activity, but it is 11856 // possible for the user flow to never be able to return to that 11857 // situation so here we do a sanity check to make sure we haven't 11858 // left any junk around. 11859 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11860 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11861 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11862 removed.clear(); 11863 for (PreferredActivity pa : pir.filterSet()) { 11864 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11865 removed.add(pa); 11866 } 11867 } 11868 if (removed.size() > 0) { 11869 for (int r=0; r<removed.size(); r++) { 11870 PreferredActivity pa = removed.get(r); 11871 Slog.w(TAG, "Removing dangling preferred activity: " 11872 + pa.mPref.mComponent); 11873 pir.removeFilter(pa); 11874 } 11875 mSettings.writePackageRestrictionsLPr( 11876 mSettings.mPreferredActivities.keyAt(i)); 11877 } 11878 } 11879 } 11880 sUserManager.systemReady(); 11881 } 11882 11883 @Override 11884 public boolean isSafeMode() { 11885 return mSafeMode; 11886 } 11887 11888 @Override 11889 public boolean hasSystemUidErrors() { 11890 return mHasSystemUidErrors; 11891 } 11892 11893 static String arrayToString(int[] array) { 11894 StringBuffer buf = new StringBuffer(128); 11895 buf.append('['); 11896 if (array != null) { 11897 for (int i=0; i<array.length; i++) { 11898 if (i > 0) buf.append(", "); 11899 buf.append(array[i]); 11900 } 11901 } 11902 buf.append(']'); 11903 return buf.toString(); 11904 } 11905 11906 static class DumpState { 11907 public static final int DUMP_LIBS = 1 << 0; 11908 11909 public static final int DUMP_FEATURES = 1 << 1; 11910 11911 public static final int DUMP_RESOLVERS = 1 << 2; 11912 11913 public static final int DUMP_PERMISSIONS = 1 << 3; 11914 11915 public static final int DUMP_PACKAGES = 1 << 4; 11916 11917 public static final int DUMP_SHARED_USERS = 1 << 5; 11918 11919 public static final int DUMP_MESSAGES = 1 << 6; 11920 11921 public static final int DUMP_PROVIDERS = 1 << 7; 11922 11923 public static final int DUMP_VERIFIERS = 1 << 8; 11924 11925 public static final int DUMP_PREFERRED = 1 << 9; 11926 11927 public static final int DUMP_PREFERRED_XML = 1 << 10; 11928 11929 public static final int DUMP_KEYSETS = 1 << 11; 11930 11931 public static final int DUMP_VERSION = 1 << 12; 11932 11933 public static final int OPTION_SHOW_FILTERS = 1 << 0; 11934 11935 private int mTypes; 11936 11937 private int mOptions; 11938 11939 private boolean mTitlePrinted; 11940 11941 private SharedUserSetting mSharedUser; 11942 11943 public boolean isDumping(int type) { 11944 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 11945 return true; 11946 } 11947 11948 return (mTypes & type) != 0; 11949 } 11950 11951 public void setDump(int type) { 11952 mTypes |= type; 11953 } 11954 11955 public boolean isOptionEnabled(int option) { 11956 return (mOptions & option) != 0; 11957 } 11958 11959 public void setOptionEnabled(int option) { 11960 mOptions |= option; 11961 } 11962 11963 public boolean onTitlePrinted() { 11964 final boolean printed = mTitlePrinted; 11965 mTitlePrinted = true; 11966 return printed; 11967 } 11968 11969 public boolean getTitlePrinted() { 11970 return mTitlePrinted; 11971 } 11972 11973 public void setTitlePrinted(boolean enabled) { 11974 mTitlePrinted = enabled; 11975 } 11976 11977 public SharedUserSetting getSharedUser() { 11978 return mSharedUser; 11979 } 11980 11981 public void setSharedUser(SharedUserSetting user) { 11982 mSharedUser = user; 11983 } 11984 } 11985 11986 @Override 11987 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 11988 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 11989 != PackageManager.PERMISSION_GRANTED) { 11990 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 11991 + Binder.getCallingPid() 11992 + ", uid=" + Binder.getCallingUid() 11993 + " without permission " 11994 + android.Manifest.permission.DUMP); 11995 return; 11996 } 11997 11998 DumpState dumpState = new DumpState(); 11999 boolean fullPreferred = false; 12000 boolean checkin = false; 12001 12002 String packageName = null; 12003 12004 int opti = 0; 12005 while (opti < args.length) { 12006 String opt = args[opti]; 12007 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12008 break; 12009 } 12010 opti++; 12011 if ("-a".equals(opt)) { 12012 // Right now we only know how to print all. 12013 } else if ("-h".equals(opt)) { 12014 pw.println("Package manager dump options:"); 12015 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12016 pw.println(" --checkin: dump for a checkin"); 12017 pw.println(" -f: print details of intent filters"); 12018 pw.println(" -h: print this help"); 12019 pw.println(" cmd may be one of:"); 12020 pw.println(" l[ibraries]: list known shared libraries"); 12021 pw.println(" f[ibraries]: list device features"); 12022 pw.println(" k[eysets]: print known keysets"); 12023 pw.println(" r[esolvers]: dump intent resolvers"); 12024 pw.println(" perm[issions]: dump permissions"); 12025 pw.println(" pref[erred]: print preferred package settings"); 12026 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12027 pw.println(" prov[iders]: dump content providers"); 12028 pw.println(" p[ackages]: dump installed packages"); 12029 pw.println(" s[hared-users]: dump shared user IDs"); 12030 pw.println(" m[essages]: print collected runtime messages"); 12031 pw.println(" v[erifiers]: print package verifier info"); 12032 pw.println(" version: print database version info"); 12033 pw.println(" write: write current settings now"); 12034 pw.println(" <package.name>: info about given package"); 12035 return; 12036 } else if ("--checkin".equals(opt)) { 12037 checkin = true; 12038 } else if ("-f".equals(opt)) { 12039 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12040 } else { 12041 pw.println("Unknown argument: " + opt + "; use -h for help"); 12042 } 12043 } 12044 12045 // Is the caller requesting to dump a particular piece of data? 12046 if (opti < args.length) { 12047 String cmd = args[opti]; 12048 opti++; 12049 // Is this a package name? 12050 if ("android".equals(cmd) || cmd.contains(".")) { 12051 packageName = cmd; 12052 // When dumping a single package, we always dump all of its 12053 // filter information since the amount of data will be reasonable. 12054 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12055 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12056 dumpState.setDump(DumpState.DUMP_LIBS); 12057 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12058 dumpState.setDump(DumpState.DUMP_FEATURES); 12059 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12060 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12061 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12062 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12063 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12064 dumpState.setDump(DumpState.DUMP_PREFERRED); 12065 } else if ("preferred-xml".equals(cmd)) { 12066 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12067 if (opti < args.length && "--full".equals(args[opti])) { 12068 fullPreferred = true; 12069 opti++; 12070 } 12071 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12072 dumpState.setDump(DumpState.DUMP_PACKAGES); 12073 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12074 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12075 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12076 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12077 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12078 dumpState.setDump(DumpState.DUMP_MESSAGES); 12079 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12080 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12081 } else if ("version".equals(cmd)) { 12082 dumpState.setDump(DumpState.DUMP_VERSION); 12083 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12084 dumpState.setDump(DumpState.DUMP_KEYSETS); 12085 } else if ("write".equals(cmd)) { 12086 synchronized (mPackages) { 12087 mSettings.writeLPr(); 12088 pw.println("Settings written."); 12089 return; 12090 } 12091 } 12092 } 12093 12094 if (checkin) { 12095 pw.println("vers,1"); 12096 } 12097 12098 // reader 12099 synchronized (mPackages) { 12100 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12101 if (!checkin) { 12102 if (dumpState.onTitlePrinted()) 12103 pw.println(); 12104 pw.println("Database versions:"); 12105 pw.print(" SDK Version:"); 12106 pw.print(" internal="); 12107 pw.print(mSettings.mInternalSdkPlatform); 12108 pw.print(" external="); 12109 pw.println(mSettings.mExternalSdkPlatform); 12110 pw.print(" DB Version:"); 12111 pw.print(" internal="); 12112 pw.print(mSettings.mInternalDatabaseVersion); 12113 pw.print(" external="); 12114 pw.println(mSettings.mExternalDatabaseVersion); 12115 } 12116 } 12117 12118 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12119 if (!checkin) { 12120 if (dumpState.onTitlePrinted()) 12121 pw.println(); 12122 pw.println("Verifiers:"); 12123 pw.print(" Required: "); 12124 pw.print(mRequiredVerifierPackage); 12125 pw.print(" (uid="); 12126 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12127 pw.println(")"); 12128 } else if (mRequiredVerifierPackage != null) { 12129 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12130 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12131 } 12132 } 12133 12134 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12135 boolean printedHeader = false; 12136 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12137 while (it.hasNext()) { 12138 String name = it.next(); 12139 SharedLibraryEntry ent = mSharedLibraries.get(name); 12140 if (!checkin) { 12141 if (!printedHeader) { 12142 if (dumpState.onTitlePrinted()) 12143 pw.println(); 12144 pw.println("Libraries:"); 12145 printedHeader = true; 12146 } 12147 pw.print(" "); 12148 } else { 12149 pw.print("lib,"); 12150 } 12151 pw.print(name); 12152 if (!checkin) { 12153 pw.print(" -> "); 12154 } 12155 if (ent.path != null) { 12156 if (!checkin) { 12157 pw.print("(jar) "); 12158 pw.print(ent.path); 12159 } else { 12160 pw.print(",jar,"); 12161 pw.print(ent.path); 12162 } 12163 } else { 12164 if (!checkin) { 12165 pw.print("(apk) "); 12166 pw.print(ent.apk); 12167 } else { 12168 pw.print(",apk,"); 12169 pw.print(ent.apk); 12170 } 12171 } 12172 pw.println(); 12173 } 12174 } 12175 12176 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12177 if (dumpState.onTitlePrinted()) 12178 pw.println(); 12179 if (!checkin) { 12180 pw.println("Features:"); 12181 } 12182 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12183 while (it.hasNext()) { 12184 String name = it.next(); 12185 if (!checkin) { 12186 pw.print(" "); 12187 } else { 12188 pw.print("feat,"); 12189 } 12190 pw.println(name); 12191 } 12192 } 12193 12194 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12195 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12196 : "Activity Resolver Table:", " ", packageName, 12197 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12198 dumpState.setTitlePrinted(true); 12199 } 12200 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12201 : "Receiver Resolver Table:", " ", packageName, 12202 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12203 dumpState.setTitlePrinted(true); 12204 } 12205 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12206 : "Service Resolver Table:", " ", packageName, 12207 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12208 dumpState.setTitlePrinted(true); 12209 } 12210 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12211 : "Provider Resolver Table:", " ", packageName, 12212 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12213 dumpState.setTitlePrinted(true); 12214 } 12215 } 12216 12217 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12218 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12219 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12220 int user = mSettings.mPreferredActivities.keyAt(i); 12221 if (pir.dump(pw, 12222 dumpState.getTitlePrinted() 12223 ? "\nPreferred Activities User " + user + ":" 12224 : "Preferred Activities User " + user + ":", " ", 12225 packageName, true)) { 12226 dumpState.setTitlePrinted(true); 12227 } 12228 } 12229 } 12230 12231 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12232 pw.flush(); 12233 FileOutputStream fout = new FileOutputStream(fd); 12234 BufferedOutputStream str = new BufferedOutputStream(fout); 12235 XmlSerializer serializer = new FastXmlSerializer(); 12236 try { 12237 serializer.setOutput(str, "utf-8"); 12238 serializer.startDocument(null, true); 12239 serializer.setFeature( 12240 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12241 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12242 serializer.endDocument(); 12243 serializer.flush(); 12244 } catch (IllegalArgumentException e) { 12245 pw.println("Failed writing: " + e); 12246 } catch (IllegalStateException e) { 12247 pw.println("Failed writing: " + e); 12248 } catch (IOException e) { 12249 pw.println("Failed writing: " + e); 12250 } 12251 } 12252 12253 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12254 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12255 } 12256 12257 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12258 boolean printedSomething = false; 12259 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12260 if (packageName != null && !packageName.equals(p.info.packageName)) { 12261 continue; 12262 } 12263 if (!printedSomething) { 12264 if (dumpState.onTitlePrinted()) 12265 pw.println(); 12266 pw.println("Registered ContentProviders:"); 12267 printedSomething = true; 12268 } 12269 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12270 pw.print(" "); pw.println(p.toString()); 12271 } 12272 printedSomething = false; 12273 for (Map.Entry<String, PackageParser.Provider> entry : 12274 mProvidersByAuthority.entrySet()) { 12275 PackageParser.Provider p = entry.getValue(); 12276 if (packageName != null && !packageName.equals(p.info.packageName)) { 12277 continue; 12278 } 12279 if (!printedSomething) { 12280 if (dumpState.onTitlePrinted()) 12281 pw.println(); 12282 pw.println("ContentProvider Authorities:"); 12283 printedSomething = true; 12284 } 12285 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12286 pw.print(" "); pw.println(p.toString()); 12287 if (p.info != null && p.info.applicationInfo != null) { 12288 final String appInfo = p.info.applicationInfo.toString(); 12289 pw.print(" applicationInfo="); pw.println(appInfo); 12290 } 12291 } 12292 } 12293 12294 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12295 mSettings.mKeySetManagerService.dump(pw, packageName, dumpState); 12296 } 12297 12298 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12299 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12300 } 12301 12302 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12303 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12304 } 12305 12306 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12307 if (dumpState.onTitlePrinted()) 12308 pw.println(); 12309 mSettings.dumpReadMessagesLPr(pw, dumpState); 12310 12311 pw.println(); 12312 pw.println("Package warning messages:"); 12313 final File fname = getSettingsProblemFile(); 12314 FileInputStream in = null; 12315 try { 12316 in = new FileInputStream(fname); 12317 final int avail = in.available(); 12318 final byte[] data = new byte[avail]; 12319 in.read(data); 12320 pw.print(new String(data)); 12321 } catch (FileNotFoundException e) { 12322 } catch (IOException e) { 12323 } finally { 12324 if (in != null) { 12325 try { 12326 in.close(); 12327 } catch (IOException e) { 12328 } 12329 } 12330 } 12331 } 12332 } 12333 } 12334 12335 // ------- apps on sdcard specific code ------- 12336 static final boolean DEBUG_SD_INSTALL = false; 12337 12338 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12339 12340 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12341 12342 private boolean mMediaMounted = false; 12343 12344 private String getEncryptKey() { 12345 try { 12346 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12347 SD_ENCRYPTION_KEYSTORE_NAME); 12348 if (sdEncKey == null) { 12349 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12350 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12351 if (sdEncKey == null) { 12352 Slog.e(TAG, "Failed to create encryption keys"); 12353 return null; 12354 } 12355 } 12356 return sdEncKey; 12357 } catch (NoSuchAlgorithmException nsae) { 12358 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12359 return null; 12360 } catch (IOException ioe) { 12361 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12362 return null; 12363 } 12364 12365 } 12366 12367 /* package */static String getTempContainerId() { 12368 int tmpIdx = 1; 12369 String list[] = PackageHelper.getSecureContainerList(); 12370 if (list != null) { 12371 for (final String name : list) { 12372 // Ignore null and non-temporary container entries 12373 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12374 continue; 12375 } 12376 12377 String subStr = name.substring(mTempContainerPrefix.length()); 12378 try { 12379 int cid = Integer.parseInt(subStr); 12380 if (cid >= tmpIdx) { 12381 tmpIdx = cid + 1; 12382 } 12383 } catch (NumberFormatException e) { 12384 } 12385 } 12386 } 12387 return mTempContainerPrefix + tmpIdx; 12388 } 12389 12390 /* 12391 * Update media status on PackageManager. 12392 */ 12393 @Override 12394 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12395 int callingUid = Binder.getCallingUid(); 12396 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12397 throw new SecurityException("Media status can only be updated by the system"); 12398 } 12399 // reader; this apparently protects mMediaMounted, but should probably 12400 // be a different lock in that case. 12401 synchronized (mPackages) { 12402 Log.i(TAG, "Updating external media status from " 12403 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12404 + (mediaStatus ? "mounted" : "unmounted")); 12405 if (DEBUG_SD_INSTALL) 12406 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12407 + ", mMediaMounted=" + mMediaMounted); 12408 if (mediaStatus == mMediaMounted) { 12409 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12410 : 0, -1); 12411 mHandler.sendMessage(msg); 12412 return; 12413 } 12414 mMediaMounted = mediaStatus; 12415 } 12416 // Queue up an async operation since the package installation may take a 12417 // little while. 12418 mHandler.post(new Runnable() { 12419 public void run() { 12420 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12421 } 12422 }); 12423 } 12424 12425 /** 12426 * Called by MountService when the initial ASECs to scan are available. 12427 * Should block until all the ASEC containers are finished being scanned. 12428 */ 12429 public void scanAvailableAsecs() { 12430 updateExternalMediaStatusInner(true, false, false); 12431 if (mShouldRestoreconData) { 12432 SELinuxMMAC.setRestoreconDone(); 12433 mShouldRestoreconData = false; 12434 } 12435 } 12436 12437 /* 12438 * Collect information of applications on external media, map them against 12439 * existing containers and update information based on current mount status. 12440 * Please note that we always have to report status if reportStatus has been 12441 * set to true especially when unloading packages. 12442 */ 12443 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12444 boolean externalStorage) { 12445 // Collection of uids 12446 int uidArr[] = null; 12447 // Collection of stale containers 12448 HashSet<String> removeCids = new HashSet<String>(); 12449 // Collection of packages on external media with valid containers. 12450 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12451 // Get list of secure containers. 12452 final String list[] = PackageHelper.getSecureContainerList(); 12453 if (list == null || list.length == 0) { 12454 Log.i(TAG, "No secure containers on sdcard"); 12455 } else { 12456 // Process list of secure containers and categorize them 12457 // as active or stale based on their package internal state. 12458 int uidList[] = new int[list.length]; 12459 int num = 0; 12460 // reader 12461 synchronized (mPackages) { 12462 for (String cid : list) { 12463 if (DEBUG_SD_INSTALL) 12464 Log.i(TAG, "Processing container " + cid); 12465 String pkgName = getAsecPackageName(cid); 12466 if (pkgName == null) { 12467 if (DEBUG_SD_INSTALL) 12468 Log.i(TAG, "Container : " + cid + " stale"); 12469 removeCids.add(cid); 12470 continue; 12471 } 12472 if (DEBUG_SD_INSTALL) 12473 Log.i(TAG, "Looking for pkg : " + pkgName); 12474 12475 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12476 if (ps == null) { 12477 Log.i(TAG, "Deleting container with no matching settings " + cid); 12478 removeCids.add(cid); 12479 continue; 12480 } 12481 12482 /* 12483 * Skip packages that are not external if we're unmounting 12484 * external storage. 12485 */ 12486 if (externalStorage && !isMounted && !isExternal(ps)) { 12487 continue; 12488 } 12489 12490 final AsecInstallArgs args = new AsecInstallArgs(cid, 12491 getAppInstructionSetFromSettings(ps), 12492 isForwardLocked(ps)); 12493 // The package status is changed only if the code path 12494 // matches between settings and the container id. 12495 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12496 if (DEBUG_SD_INSTALL) { 12497 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12498 + " at code path: " + ps.codePathString); 12499 } 12500 12501 // We do have a valid package installed on sdcard 12502 processCids.put(args, ps.codePathString); 12503 final int uid = ps.appId; 12504 if (uid != -1) { 12505 uidList[num++] = uid; 12506 } 12507 } else { 12508 Log.i(TAG, "Deleting stale container for " + cid); 12509 removeCids.add(cid); 12510 } 12511 } 12512 } 12513 12514 if (num > 0) { 12515 // Sort uid list 12516 Arrays.sort(uidList, 0, num); 12517 // Throw away duplicates 12518 uidArr = new int[num]; 12519 uidArr[0] = uidList[0]; 12520 int di = 0; 12521 for (int i = 1; i < num; i++) { 12522 if (uidList[i - 1] != uidList[i]) { 12523 uidArr[di++] = uidList[i]; 12524 } 12525 } 12526 } 12527 } 12528 // Process packages with valid entries. 12529 if (isMounted) { 12530 if (DEBUG_SD_INSTALL) 12531 Log.i(TAG, "Loading packages"); 12532 loadMediaPackages(processCids, uidArr, removeCids); 12533 startCleaningPackages(); 12534 } else { 12535 if (DEBUG_SD_INSTALL) 12536 Log.i(TAG, "Unloading packages"); 12537 unloadMediaPackages(processCids, uidArr, reportStatus); 12538 } 12539 } 12540 12541 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12542 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12543 int size = pkgList.size(); 12544 if (size > 0) { 12545 // Send broadcasts here 12546 Bundle extras = new Bundle(); 12547 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12548 .toArray(new String[size])); 12549 if (uidArr != null) { 12550 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12551 } 12552 if (replacing) { 12553 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12554 } 12555 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12556 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12557 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12558 } 12559 } 12560 12561 /* 12562 * Look at potentially valid container ids from processCids If package 12563 * information doesn't match the one on record or package scanning fails, 12564 * the cid is added to list of removeCids. We currently don't delete stale 12565 * containers. 12566 */ 12567 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12568 HashSet<String> removeCids) { 12569 ArrayList<String> pkgList = new ArrayList<String>(); 12570 Set<AsecInstallArgs> keys = processCids.keySet(); 12571 boolean doGc = false; 12572 for (AsecInstallArgs args : keys) { 12573 String codePath = processCids.get(args); 12574 if (DEBUG_SD_INSTALL) 12575 Log.i(TAG, "Loading container : " + args.cid); 12576 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12577 try { 12578 // Make sure there are no container errors first. 12579 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12580 Slog.e(TAG, "Failed to mount cid : " + args.cid 12581 + " when installing from sdcard"); 12582 continue; 12583 } 12584 // Check code path here. 12585 if (codePath == null || !codePath.equals(args.getCodePath())) { 12586 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12587 + " does not match one in settings " + codePath); 12588 continue; 12589 } 12590 // Parse package 12591 int parseFlags = mDefParseFlags; 12592 if (args.isExternal()) { 12593 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12594 } 12595 if (args.isFwdLocked()) { 12596 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12597 } 12598 12599 doGc = true; 12600 synchronized (mInstallLock) { 12601 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 12602 0, 0, null, null); 12603 // Scan the package 12604 if (pkg != null) { 12605 /* 12606 * TODO why is the lock being held? doPostInstall is 12607 * called in other places without the lock. This needs 12608 * to be straightened out. 12609 */ 12610 // writer 12611 synchronized (mPackages) { 12612 retCode = PackageManager.INSTALL_SUCCEEDED; 12613 pkgList.add(pkg.packageName); 12614 // Post process args 12615 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12616 pkg.applicationInfo.uid); 12617 } 12618 } else { 12619 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12620 } 12621 } 12622 12623 } finally { 12624 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12625 // Don't destroy container here. Wait till gc clears things 12626 // up. 12627 removeCids.add(args.cid); 12628 } 12629 } 12630 } 12631 // writer 12632 synchronized (mPackages) { 12633 // If the platform SDK has changed since the last time we booted, 12634 // we need to re-grant app permission to catch any new ones that 12635 // appear. This is really a hack, and means that apps can in some 12636 // cases get permissions that the user didn't initially explicitly 12637 // allow... it would be nice to have some better way to handle 12638 // this situation. 12639 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12640 if (regrantPermissions) 12641 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12642 + mSdkVersion + "; regranting permissions for external storage"); 12643 mSettings.mExternalSdkPlatform = mSdkVersion; 12644 12645 // Make sure group IDs have been assigned, and any permission 12646 // changes in other apps are accounted for 12647 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12648 | (regrantPermissions 12649 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12650 : 0)); 12651 12652 mSettings.updateExternalDatabaseVersion(); 12653 12654 // can downgrade to reader 12655 // Persist settings 12656 mSettings.writeLPr(); 12657 } 12658 // Send a broadcast to let everyone know we are done processing 12659 if (pkgList.size() > 0) { 12660 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12661 } 12662 // Force gc to avoid any stale parser references that we might have. 12663 if (doGc) { 12664 Runtime.getRuntime().gc(); 12665 } 12666 // List stale containers and destroy stale temporary containers. 12667 if (removeCids != null) { 12668 for (String cid : removeCids) { 12669 if (cid.startsWith(mTempContainerPrefix)) { 12670 Log.i(TAG, "Destroying stale temporary container " + cid); 12671 PackageHelper.destroySdDir(cid); 12672 } else { 12673 Log.w(TAG, "Container " + cid + " is stale"); 12674 } 12675 } 12676 } 12677 } 12678 12679 /* 12680 * Utility method to unload a list of specified containers 12681 */ 12682 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12683 // Just unmount all valid containers. 12684 for (AsecInstallArgs arg : cidArgs) { 12685 synchronized (mInstallLock) { 12686 arg.doPostDeleteLI(false); 12687 } 12688 } 12689 } 12690 12691 /* 12692 * Unload packages mounted on external media. This involves deleting package 12693 * data from internal structures, sending broadcasts about diabled packages, 12694 * gc'ing to free up references, unmounting all secure containers 12695 * corresponding to packages on external media, and posting a 12696 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12697 * that we always have to post this message if status has been requested no 12698 * matter what. 12699 */ 12700 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12701 final boolean reportStatus) { 12702 if (DEBUG_SD_INSTALL) 12703 Log.i(TAG, "unloading media packages"); 12704 ArrayList<String> pkgList = new ArrayList<String>(); 12705 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12706 final Set<AsecInstallArgs> keys = processCids.keySet(); 12707 for (AsecInstallArgs args : keys) { 12708 String pkgName = args.getPackageName(); 12709 if (DEBUG_SD_INSTALL) 12710 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12711 // Delete package internally 12712 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12713 synchronized (mInstallLock) { 12714 boolean res = deletePackageLI(pkgName, null, false, null, null, 12715 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12716 if (res) { 12717 pkgList.add(pkgName); 12718 } else { 12719 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12720 failedList.add(args); 12721 } 12722 } 12723 } 12724 12725 // reader 12726 synchronized (mPackages) { 12727 // We didn't update the settings after removing each package; 12728 // write them now for all packages. 12729 mSettings.writeLPr(); 12730 } 12731 12732 // We have to absolutely send UPDATED_MEDIA_STATUS only 12733 // after confirming that all the receivers processed the ordered 12734 // broadcast when packages get disabled, force a gc to clean things up. 12735 // and unload all the containers. 12736 if (pkgList.size() > 0) { 12737 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12738 new IIntentReceiver.Stub() { 12739 public void performReceive(Intent intent, int resultCode, String data, 12740 Bundle extras, boolean ordered, boolean sticky, 12741 int sendingUser) throws RemoteException { 12742 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12743 reportStatus ? 1 : 0, 1, keys); 12744 mHandler.sendMessage(msg); 12745 } 12746 }); 12747 } else { 12748 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12749 keys); 12750 mHandler.sendMessage(msg); 12751 } 12752 } 12753 12754 /** Binder call */ 12755 @Override 12756 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12757 final int flags) { 12758 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12759 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12760 int returnCode = PackageManager.MOVE_SUCCEEDED; 12761 int currFlags = 0; 12762 int newFlags = 0; 12763 // reader 12764 synchronized (mPackages) { 12765 PackageParser.Package pkg = mPackages.get(packageName); 12766 if (pkg == null) { 12767 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12768 } else { 12769 // Disable moving fwd locked apps and system packages 12770 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12771 Slog.w(TAG, "Cannot move system application"); 12772 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12773 } else if (pkg.mOperationPending) { 12774 Slog.w(TAG, "Attempt to move package which has pending operations"); 12775 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12776 } else { 12777 // Find install location first 12778 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12779 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12780 Slog.w(TAG, "Ambigous flags specified for move location."); 12781 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12782 } else { 12783 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12784 : PackageManager.INSTALL_INTERNAL; 12785 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12786 : PackageManager.INSTALL_INTERNAL; 12787 12788 if (newFlags == currFlags) { 12789 Slog.w(TAG, "No move required. Trying to move to same location"); 12790 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12791 } else { 12792 if (isForwardLocked(pkg)) { 12793 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12794 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12795 } 12796 } 12797 } 12798 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12799 pkg.mOperationPending = true; 12800 } 12801 } 12802 } 12803 12804 /* 12805 * TODO this next block probably shouldn't be inside the lock. We 12806 * can't guarantee these won't change after this is fired off 12807 * anyway. 12808 */ 12809 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12810 processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user), 12811 returnCode); 12812 } else { 12813 Message msg = mHandler.obtainMessage(INIT_COPY); 12814 final String instructionSet = getAppInstructionSet(pkg.applicationInfo); 12815 InstallArgs srcArgs = createInstallArgsForExisting(currFlags, 12816 pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(), 12817 pkg.applicationInfo.nativeLibraryDir, instructionSet); 12818 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 12819 instructionSet, pkg.applicationInfo.uid, user); 12820 msg.obj = mp; 12821 mHandler.sendMessage(msg); 12822 } 12823 } 12824 } 12825 12826 private void processPendingMove(final MoveParams mp, final int currentStatus) { 12827 // Queue up an async operation since the package deletion may take a 12828 // little while. 12829 mHandler.post(new Runnable() { 12830 public void run() { 12831 // TODO fix this; this does nothing. 12832 mHandler.removeCallbacks(this); 12833 int returnCode = currentStatus; 12834 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 12835 int uidArr[] = null; 12836 ArrayList<String> pkgList = null; 12837 synchronized (mPackages) { 12838 PackageParser.Package pkg = mPackages.get(mp.packageName); 12839 if (pkg == null) { 12840 Slog.w(TAG, " Package " + mp.packageName 12841 + " doesn't exist. Aborting move"); 12842 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12843 } else if (!mp.srcArgs.getCodePath().equals( 12844 pkg.applicationInfo.getCodePath())) { 12845 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 12846 + mp.srcArgs.getCodePath() + " to " 12847 + pkg.applicationInfo.getCodePath() 12848 + " Aborting move and returning error"); 12849 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12850 } else { 12851 uidArr = new int[] { 12852 pkg.applicationInfo.uid 12853 }; 12854 pkgList = new ArrayList<String>(); 12855 pkgList.add(mp.packageName); 12856 } 12857 } 12858 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12859 // Send resources unavailable broadcast 12860 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 12861 // Update package code and resource paths 12862 synchronized (mInstallLock) { 12863 synchronized (mPackages) { 12864 PackageParser.Package pkg = mPackages.get(mp.packageName); 12865 // Recheck for package again. 12866 if (pkg == null) { 12867 Slog.w(TAG, " Package " + mp.packageName 12868 + " doesn't exist. Aborting move"); 12869 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12870 } else if (!mp.srcArgs.getCodePath().equals( 12871 pkg.applicationInfo.getCodePath())) { 12872 Slog.w(TAG, "Package " + mp.packageName 12873 + " code path changed from " + mp.srcArgs.getCodePath() 12874 + " to " + pkg.applicationInfo.getCodePath() 12875 + " Aborting move and returning error"); 12876 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12877 } else { 12878 final String oldCodePath = pkg.codePath; 12879 final String newCodePath = mp.targetArgs.getCodePath(); 12880 final String newResPath = mp.targetArgs.getResourcePath(); 12881 final String newNativePath = mp.targetArgs 12882 .getNativeLibraryPath(); 12883 12884 final File newNativeDir = new File(newNativePath); 12885 12886 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 12887 NativeLibraryHelper.Handle handle = null; 12888 try { 12889 handle = NativeLibraryHelper.Handle.create( 12890 new File(newCodePath)); 12891 final int abi = NativeLibraryHelper.findSupportedAbi( 12892 handle, Build.SUPPORTED_ABIS); 12893 if (abi >= 0) { 12894 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 12895 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 12896 } 12897 } catch (IOException ioe) { 12898 Slog.w(TAG, "Unable to extract native libs for package :" 12899 + mp.packageName, ioe); 12900 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12901 } finally { 12902 IoUtils.closeQuietly(handle); 12903 } 12904 } 12905 final int[] users = sUserManager.getUserIds(); 12906 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12907 for (int user : users) { 12908 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 12909 newNativePath, user) < 0) { 12910 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12911 } 12912 } 12913 } 12914 12915 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12916 pkg.codePath = newCodePath; 12917 pkg.baseCodePath = newCodePath; 12918 // Move dex files around 12919 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 12920 // Moving of dex files failed. Set 12921 // error code and abort move. 12922 pkg.codePath = oldCodePath; 12923 pkg.baseCodePath = oldCodePath; 12924 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12925 } 12926 } 12927 12928 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12929 pkg.applicationInfo.setCodePath(newCodePath); 12930 pkg.applicationInfo.setBaseCodePath(newCodePath); 12931 pkg.applicationInfo.setSplitCodePaths(null); 12932 pkg.applicationInfo.setResourcePath(newResPath); 12933 pkg.applicationInfo.setBaseResourcePath(newResPath); 12934 pkg.applicationInfo.setSplitResourcePaths(null); 12935 pkg.applicationInfo.nativeLibraryDir = newNativePath; 12936 12937 PackageSetting ps = (PackageSetting) pkg.mExtras; 12938 ps.codePath = new File(pkg.applicationInfo.getCodePath()); 12939 ps.codePathString = ps.codePath.getPath(); 12940 ps.resourcePath = new File( 12941 pkg.applicationInfo.getResourcePath()); 12942 ps.resourcePathString = ps.resourcePath.getPath(); 12943 ps.nativeLibraryPathString = newNativePath; 12944 // Set the application info flag 12945 // correctly. 12946 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 12947 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12948 } else { 12949 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12950 } 12951 ps.setFlags(pkg.applicationInfo.flags); 12952 mAppDirs.remove(oldCodePath); 12953 mAppDirs.put(newCodePath, pkg); 12954 // Persist settings 12955 mSettings.writeLPr(); 12956 } 12957 } 12958 } 12959 } 12960 // Send resources available broadcast 12961 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12962 } 12963 } 12964 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12965 // Clean up failed installation 12966 if (mp.targetArgs != null) { 12967 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 12968 -1); 12969 } 12970 } else { 12971 // Force a gc to clear things up. 12972 Runtime.getRuntime().gc(); 12973 // Delete older code 12974 synchronized (mInstallLock) { 12975 mp.srcArgs.doPostDeleteLI(true); 12976 } 12977 } 12978 12979 // Allow more operations on this file if we didn't fail because 12980 // an operation was already pending for this package. 12981 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 12982 synchronized (mPackages) { 12983 PackageParser.Package pkg = mPackages.get(mp.packageName); 12984 if (pkg != null) { 12985 pkg.mOperationPending = false; 12986 } 12987 } 12988 } 12989 12990 IPackageMoveObserver observer = mp.observer; 12991 if (observer != null) { 12992 try { 12993 observer.packageMoved(mp.packageName, returnCode); 12994 } catch (RemoteException e) { 12995 Log.i(TAG, "Observer no longer exists."); 12996 } 12997 } 12998 } 12999 }); 13000 } 13001 13002 @Override 13003 public boolean setInstallLocation(int loc) { 13004 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13005 null); 13006 if (getInstallLocation() == loc) { 13007 return true; 13008 } 13009 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13010 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13011 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13012 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13013 return true; 13014 } 13015 return false; 13016 } 13017 13018 @Override 13019 public int getInstallLocation() { 13020 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13021 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13022 PackageHelper.APP_INSTALL_AUTO); 13023 } 13024 13025 /** Called by UserManagerService */ 13026 void cleanUpUserLILPw(int userHandle) { 13027 mDirtyUsers.remove(userHandle); 13028 mSettings.removeUserLPr(userHandle); 13029 mPendingBroadcasts.remove(userHandle); 13030 if (mInstaller != null) { 13031 // Technically, we shouldn't be doing this with the package lock 13032 // held. However, this is very rare, and there is already so much 13033 // other disk I/O going on, that we'll let it slide for now. 13034 mInstaller.removeUserDataDirs(userHandle); 13035 } 13036 mUserNeedsBadging.delete(userHandle); 13037 } 13038 13039 /** Called by UserManagerService */ 13040 void createNewUserLILPw(int userHandle, File path) { 13041 if (mInstaller != null) { 13042 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13043 } 13044 } 13045 13046 @Override 13047 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13048 mContext.enforceCallingOrSelfPermission( 13049 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13050 "Only package verification agents can read the verifier device identity"); 13051 13052 synchronized (mPackages) { 13053 return mSettings.getVerifierDeviceIdentityLPw(); 13054 } 13055 } 13056 13057 @Override 13058 public void setPermissionEnforced(String permission, boolean enforced) { 13059 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13060 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13061 synchronized (mPackages) { 13062 if (mSettings.mReadExternalStorageEnforced == null 13063 || mSettings.mReadExternalStorageEnforced != enforced) { 13064 mSettings.mReadExternalStorageEnforced = enforced; 13065 mSettings.writeLPr(); 13066 } 13067 } 13068 // kill any non-foreground processes so we restart them and 13069 // grant/revoke the GID. 13070 final IActivityManager am = ActivityManagerNative.getDefault(); 13071 if (am != null) { 13072 final long token = Binder.clearCallingIdentity(); 13073 try { 13074 am.killProcessesBelowForeground("setPermissionEnforcement"); 13075 } catch (RemoteException e) { 13076 } finally { 13077 Binder.restoreCallingIdentity(token); 13078 } 13079 } 13080 } else { 13081 throw new IllegalArgumentException("No selective enforcement for " + permission); 13082 } 13083 } 13084 13085 @Override 13086 @Deprecated 13087 public boolean isPermissionEnforced(String permission) { 13088 return true; 13089 } 13090 13091 @Override 13092 public boolean isStorageLow() { 13093 final long token = Binder.clearCallingIdentity(); 13094 try { 13095 final DeviceStorageMonitorInternal 13096 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13097 if (dsm != null) { 13098 return dsm.isMemoryLow(); 13099 } else { 13100 return false; 13101 } 13102 } finally { 13103 Binder.restoreCallingIdentity(token); 13104 } 13105 } 13106 13107 @Override 13108 public IPackageInstaller getPackageInstaller() { 13109 return mInstallerService; 13110 } 13111 13112 private boolean userNeedsBadging(int userId) { 13113 int index = mUserNeedsBadging.indexOfKey(userId); 13114 if (index < 0) { 13115 final UserInfo userInfo; 13116 final long token = Binder.clearCallingIdentity(); 13117 try { 13118 userInfo = sUserManager.getUserInfo(userId); 13119 } finally { 13120 Binder.restoreCallingIdentity(token); 13121 } 13122 final boolean b; 13123 if (userInfo != null && userInfo.isManagedProfile()) { 13124 b = true; 13125 } else { 13126 b = false; 13127 } 13128 mUserNeedsBadging.put(userId, b); 13129 return b; 13130 } 13131 return mUserNeedsBadging.valueAt(index); 13132 } 13133} 13134