PackageManagerService.java revision d746057f2414cba2bdc69257cc5be8cb681bb592
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 if (!isApkFile(file)) { 4114 // Ignore entries which are not apk's 4115 continue; 4116 } 4117 PackageParser.Package pkg = scanPackageLI(file, 4118 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null, null); 4119 // Don't mess around with apps in system partition. 4120 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4121 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) { 4122 // Delete the apk 4123 Slog.w(TAG, "Cleaning up failed install of " + file); 4124 file.delete(); 4125 } 4126 } 4127 } 4128 4129 private static File getSettingsProblemFile() { 4130 File dataDir = Environment.getDataDirectory(); 4131 File systemDir = new File(dataDir, "system"); 4132 File fname = new File(systemDir, "uiderrors.txt"); 4133 return fname; 4134 } 4135 4136 static void reportSettingsProblem(int priority, String msg) { 4137 try { 4138 File fname = getSettingsProblemFile(); 4139 FileOutputStream out = new FileOutputStream(fname, true); 4140 PrintWriter pw = new FastPrintWriter(out); 4141 SimpleDateFormat formatter = new SimpleDateFormat(); 4142 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4143 pw.println(dateString + ": " + msg); 4144 pw.close(); 4145 FileUtils.setPermissions( 4146 fname.toString(), 4147 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4148 -1, -1); 4149 } catch (java.io.IOException e) { 4150 } 4151 Slog.println(priority, TAG, msg); 4152 } 4153 4154 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps, 4155 PackageParser.Package pkg, File srcFile, int parseFlags) { 4156 if (ps != null 4157 && ps.codePath.equals(srcFile) 4158 && ps.timeStamp == srcFile.lastModified() 4159 && !isCompatSignatureUpdateNeeded(pkg)) { 4160 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4161 if (ps.signatures.mSignatures != null 4162 && ps.signatures.mSignatures.length != 0 4163 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4164 // Optimization: reuse the existing cached certificates 4165 // if the package appears to be unchanged. 4166 pkg.mSignatures = ps.signatures.mSignatures; 4167 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4168 pkg.mSigningKeys = ksms.getPublicKeysFromKeySet(mSigningKeySetId); 4169 return true; 4170 } 4171 4172 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them."); 4173 } else { 4174 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4175 } 4176 4177 try { 4178 pp.collectCertificates(pkg, parseFlags); 4179 pp.collectManifestDigest(pkg); 4180 } catch (PackageParserException e) { 4181 mLastScanError = e.error; 4182 return false; 4183 } 4184 return true; 4185 } 4186 4187 /* 4188 * Scan a package and return the newly parsed package. 4189 * Returns null in case of errors and the error code is stored in mLastScanError 4190 */ 4191 private PackageParser.Package scanPackageLI(File scanFile, 4192 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 4193 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 4194 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4195 parseFlags |= mDefParseFlags; 4196 PackageParser pp = new PackageParser(); 4197 pp.setSeparateProcesses(mSeparateProcesses); 4198 pp.setOnlyCoreApps(mOnlyCore); 4199 pp.setDisplayMetrics(mMetrics); 4200 4201 if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) { 4202 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4203 } 4204 4205 final PackageParser.Package pkg; 4206 try { 4207 pkg = pp.parsePackage(scanFile, parseFlags); 4208 } catch (PackageParserException e) { 4209 mLastScanError = e.error; 4210 return null; 4211 } 4212 4213 PackageSetting ps = null; 4214 PackageSetting updatedPkg; 4215 // reader 4216 synchronized (mPackages) { 4217 // Look to see if we already know about this package. 4218 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4219 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4220 // This package has been renamed to its original name. Let's 4221 // use that. 4222 ps = mSettings.peekPackageLPr(oldName); 4223 } 4224 // If there was no original package, see one for the real package name. 4225 if (ps == null) { 4226 ps = mSettings.peekPackageLPr(pkg.packageName); 4227 } 4228 // Check to see if this package could be hiding/updating a system 4229 // package. Must look for it either under the original or real 4230 // package name depending on our state. 4231 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4232 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4233 } 4234 boolean updatedPkgBetter = false; 4235 // First check if this is a system package that may involve an update 4236 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4237 if (ps != null && !ps.codePath.equals(scanFile)) { 4238 // The path has changed from what was last scanned... check the 4239 // version of the new path against what we have stored to determine 4240 // what to do. 4241 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4242 if (pkg.mVersionCode < ps.versionCode) { 4243 // The system package has been updated and the code path does not match 4244 // Ignore entry. Skip it. 4245 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4246 + " ignored: updated version " + ps.versionCode 4247 + " better than this " + pkg.mVersionCode); 4248 if (!updatedPkg.codePath.equals(scanFile)) { 4249 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4250 + ps.name + " changing from " + updatedPkg.codePathString 4251 + " to " + scanFile); 4252 updatedPkg.codePath = scanFile; 4253 updatedPkg.codePathString = scanFile.toString(); 4254 // This is the point at which we know that the system-disk APK 4255 // for this package has moved during a reboot (e.g. due to an OTA), 4256 // so we need to reevaluate it for privilege policy. 4257 if (locationIsPrivileged(scanFile)) { 4258 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4259 } 4260 } 4261 updatedPkg.pkg = pkg; 4262 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4263 return null; 4264 } else { 4265 // The current app on the system partition is better than 4266 // what we have updated to on the data partition; switch 4267 // back to the system partition version. 4268 // At this point, its safely assumed that package installation for 4269 // apps in system partition will go through. If not there won't be a working 4270 // version of the app 4271 // writer 4272 synchronized (mPackages) { 4273 // Just remove the loaded entries from package lists. 4274 mPackages.remove(ps.name); 4275 } 4276 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4277 + "reverting from " + ps.codePathString 4278 + ": new version " + pkg.mVersionCode 4279 + " better than installed " + ps.versionCode); 4280 4281 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4282 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4283 getAppInstructionSetFromSettings(ps)); 4284 synchronized (mInstallLock) { 4285 args.cleanUpResourcesLI(); 4286 } 4287 synchronized (mPackages) { 4288 mSettings.enableSystemPackageLPw(ps.name); 4289 } 4290 updatedPkgBetter = true; 4291 } 4292 } 4293 } 4294 4295 if (updatedPkg != null) { 4296 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4297 // initially 4298 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4299 4300 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4301 // flag set initially 4302 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4303 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4304 } 4305 } 4306 // Verify certificates against what was last scanned 4307 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) { 4308 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName); 4309 return null; 4310 } 4311 4312 /* 4313 * A new system app appeared, but we already had a non-system one of the 4314 * same name installed earlier. 4315 */ 4316 boolean shouldHideSystemApp = false; 4317 if (updatedPkg == null && ps != null 4318 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4319 /* 4320 * Check to make sure the signatures match first. If they don't, 4321 * wipe the installed application and its data. 4322 */ 4323 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4324 != PackageManager.SIGNATURE_MATCH) { 4325 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4326 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4327 ps = null; 4328 } else { 4329 /* 4330 * If the newly-added system app is an older version than the 4331 * already installed version, hide it. It will be scanned later 4332 * and re-added like an update. 4333 */ 4334 if (pkg.mVersionCode < ps.versionCode) { 4335 shouldHideSystemApp = true; 4336 } else { 4337 /* 4338 * The newly found system app is a newer version that the 4339 * one previously installed. Simply remove the 4340 * already-installed application and replace it with our own 4341 * while keeping the application data. 4342 */ 4343 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4344 + ps.codePathString + ": new version " + pkg.mVersionCode 4345 + " better than installed " + ps.versionCode); 4346 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4347 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4348 getAppInstructionSetFromSettings(ps)); 4349 synchronized (mInstallLock) { 4350 args.cleanUpResourcesLI(); 4351 } 4352 } 4353 } 4354 } 4355 4356 // The apk is forward locked (not public) if its code and resources 4357 // are kept in different files. (except for app in either system or 4358 // vendor path). 4359 // TODO grab this value from PackageSettings 4360 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4361 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4362 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4363 } 4364 } 4365 4366 // TODO: extend to support forward-locked splits 4367 String resourcePath = null; 4368 String baseResourcePath = null; 4369 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4370 if (ps != null && ps.resourcePathString != null) { 4371 resourcePath = ps.resourcePathString; 4372 baseResourcePath = ps.resourcePathString; 4373 } else { 4374 // Should not happen at all. Just log an error. 4375 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4376 } 4377 } else { 4378 resourcePath = pkg.codePath; 4379 baseResourcePath = pkg.baseCodePath; 4380 } 4381 4382 // Set application objects path explicitly. 4383 pkg.applicationInfo.setCodePath(pkg.codePath); 4384 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4385 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4386 pkg.applicationInfo.setResourcePath(resourcePath); 4387 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4388 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4389 4390 // Note that we invoke the following method only if we are about to unpack an application 4391 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4392 | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride); 4393 4394 /* 4395 * If the system app should be overridden by a previously installed 4396 * data, hide the system app now and let the /data/app scan pick it up 4397 * again. 4398 */ 4399 if (shouldHideSystemApp) { 4400 synchronized (mPackages) { 4401 /* 4402 * We have to grant systems permissions before we hide, because 4403 * grantPermissions will assume the package update is trying to 4404 * expand its permissions. 4405 */ 4406 grantPermissionsLPw(pkg, true); 4407 mSettings.disableSystemPackageLPw(pkg.packageName); 4408 } 4409 } 4410 4411 return scannedPkg; 4412 } 4413 4414 private static String fixProcessName(String defProcessName, 4415 String processName, int uid) { 4416 if (processName == null) { 4417 return defProcessName; 4418 } 4419 return processName; 4420 } 4421 4422 private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) { 4423 if (pkgSetting.signatures.mSignatures != null) { 4424 // Already existing package. Make sure signatures match 4425 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4426 == PackageManager.SIGNATURE_MATCH; 4427 if (!match) { 4428 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4429 == PackageManager.SIGNATURE_MATCH; 4430 } 4431 if (!match) { 4432 Slog.e(TAG, "Package " + pkg.packageName 4433 + " signatures do not match the previously installed version; ignoring!"); 4434 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 4435 return false; 4436 } 4437 } 4438 4439 // Check for shared user signatures 4440 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4441 // Already existing package. Make sure signatures match 4442 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4443 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4444 if (!match) { 4445 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4446 == PackageManager.SIGNATURE_MATCH; 4447 } 4448 if (!match) { 4449 Slog.e(TAG, "Package " + pkg.packageName 4450 + " has no signatures that match those in shared user " 4451 + pkgSetting.sharedUser.name + "; ignoring!"); 4452 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 4453 return false; 4454 } 4455 } 4456 return true; 4457 } 4458 4459 /** 4460 * Enforces that only the system UID or root's UID can call a method exposed 4461 * via Binder. 4462 * 4463 * @param message used as message if SecurityException is thrown 4464 * @throws SecurityException if the caller is not system or root 4465 */ 4466 private static final void enforceSystemOrRoot(String message) { 4467 final int uid = Binder.getCallingUid(); 4468 if (uid != Process.SYSTEM_UID && uid != 0) { 4469 throw new SecurityException(message); 4470 } 4471 } 4472 4473 @Override 4474 public void performBootDexOpt() { 4475 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4476 4477 final HashSet<PackageParser.Package> pkgs; 4478 synchronized (mPackages) { 4479 pkgs = mDeferredDexOpt; 4480 mDeferredDexOpt = null; 4481 } 4482 4483 if (pkgs != null) { 4484 // Filter out packages that aren't recently used. 4485 // 4486 // The exception is first boot of a non-eng device, which 4487 // should do a full dexopt. 4488 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4489 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4490 // TODO: add a property to control this? 4491 long dexOptLRUThresholdInMinutes; 4492 if (eng) { 4493 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4494 } else { 4495 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4496 } 4497 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4498 4499 int total = pkgs.size(); 4500 int skipped = 0; 4501 long now = System.currentTimeMillis(); 4502 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4503 PackageParser.Package pkg = i.next(); 4504 long then = pkg.mLastPackageUsageTimeInMills; 4505 if (then + dexOptLRUThresholdInMills < now) { 4506 if (DEBUG_DEXOPT) { 4507 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4508 ((then == 0) ? "never" : new Date(then))); 4509 } 4510 i.remove(); 4511 skipped++; 4512 } 4513 } 4514 if (DEBUG_DEXOPT) { 4515 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4516 } 4517 } 4518 4519 int i = 0; 4520 for (PackageParser.Package pkg : pkgs) { 4521 i++; 4522 if (DEBUG_DEXOPT) { 4523 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4524 + ": " + pkg.packageName); 4525 } 4526 if (!isFirstBoot()) { 4527 try { 4528 ActivityManagerNative.getDefault().showBootMessage( 4529 mContext.getResources().getString( 4530 R.string.android_upgrading_apk, 4531 i, pkgs.size()), true); 4532 } catch (RemoteException e) { 4533 } 4534 } 4535 PackageParser.Package p = pkg; 4536 synchronized (mInstallLock) { 4537 if (p.mDexOptNeeded) { 4538 performDexOptLI(p, false /* force dex */, false /* defer */, 4539 true /* include dependencies */); 4540 } 4541 } 4542 } 4543 } 4544 } 4545 4546 @Override 4547 public boolean performDexOpt(String packageName) { 4548 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4549 return performDexOpt(packageName, true); 4550 } 4551 4552 public boolean performDexOpt(String packageName, boolean updateUsage) { 4553 4554 PackageParser.Package p; 4555 synchronized (mPackages) { 4556 p = mPackages.get(packageName); 4557 if (p == null) { 4558 return false; 4559 } 4560 if (updateUsage) { 4561 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4562 } 4563 mPackageUsage.write(false); 4564 if (!p.mDexOptNeeded) { 4565 return false; 4566 } 4567 } 4568 4569 synchronized (mInstallLock) { 4570 return performDexOptLI(p, false /* force dex */, false /* defer */, 4571 true /* include dependencies */) == DEX_OPT_PERFORMED; 4572 } 4573 } 4574 4575 public HashSet<String> getPackagesThatNeedDexOpt() { 4576 HashSet<String> pkgs = null; 4577 synchronized (mPackages) { 4578 for (PackageParser.Package p : mPackages.values()) { 4579 if (DEBUG_DEXOPT) { 4580 Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded); 4581 } 4582 if (!p.mDexOptNeeded) { 4583 continue; 4584 } 4585 if (pkgs == null) { 4586 pkgs = new HashSet<String>(); 4587 } 4588 pkgs.add(p.packageName); 4589 } 4590 } 4591 return pkgs; 4592 } 4593 4594 public void shutdown() { 4595 mPackageUsage.write(true); 4596 } 4597 4598 private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet, 4599 boolean forceDex, boolean defer, HashSet<String> done) { 4600 for (int i=0; i<libs.size(); i++) { 4601 PackageParser.Package libPkg; 4602 String libName; 4603 synchronized (mPackages) { 4604 libName = libs.get(i); 4605 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4606 if (lib != null && lib.apk != null) { 4607 libPkg = mPackages.get(lib.apk); 4608 } else { 4609 libPkg = null; 4610 } 4611 } 4612 if (libPkg != null && !done.contains(libName)) { 4613 performDexOptLI(libPkg, instructionSet, forceDex, defer, done); 4614 } 4615 } 4616 } 4617 4618 static final int DEX_OPT_SKIPPED = 0; 4619 static final int DEX_OPT_PERFORMED = 1; 4620 static final int DEX_OPT_DEFERRED = 2; 4621 static final int DEX_OPT_FAILED = -1; 4622 4623 private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride, 4624 boolean forceDex, boolean defer, HashSet<String> done) { 4625 final String instructionSet = instructionSetOverride != null ? 4626 instructionSetOverride : getAppInstructionSet(pkg.applicationInfo); 4627 4628 if (done != null) { 4629 done.add(pkg.packageName); 4630 if (pkg.usesLibraries != null) { 4631 performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done); 4632 } 4633 if (pkg.usesOptionalLibraries != null) { 4634 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done); 4635 } 4636 } 4637 4638 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0) { 4639 final Collection<String> paths = pkg.getAllCodePaths(); 4640 for (String path : paths) { 4641 try { 4642 boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path, 4643 pkg.packageName, instructionSet, defer); 4644 // There are three basic cases here: 4645 // 1.) we need to dexopt, either because we are forced or it is needed 4646 // 2.) we are defering a needed dexopt 4647 // 3.) we are skipping an unneeded dexopt 4648 if (forceDex || (!defer && isDexOptNeededInternal)) { 4649 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName); 4650 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4651 int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4652 pkg.packageName, instructionSet); 4653 // Note that we ran dexopt, since rerunning will 4654 // probably just result in an error again. 4655 pkg.mDexOptNeeded = false; 4656 if (ret < 0) { 4657 return DEX_OPT_FAILED; 4658 } 4659 return DEX_OPT_PERFORMED; 4660 } 4661 if (defer && isDexOptNeededInternal) { 4662 if (mDeferredDexOpt == null) { 4663 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4664 } 4665 mDeferredDexOpt.add(pkg); 4666 return DEX_OPT_DEFERRED; 4667 } 4668 pkg.mDexOptNeeded = false; 4669 return DEX_OPT_SKIPPED; 4670 } catch (FileNotFoundException e) { 4671 Slog.w(TAG, "Apk not found for dexopt: " + path); 4672 return DEX_OPT_FAILED; 4673 } catch (IOException e) { 4674 Slog.w(TAG, "IOException reading apk: " + path, e); 4675 return DEX_OPT_FAILED; 4676 } catch (StaleDexCacheError e) { 4677 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4678 return DEX_OPT_FAILED; 4679 } catch (Exception e) { 4680 Slog.w(TAG, "Exception when doing dexopt : ", e); 4681 return DEX_OPT_FAILED; 4682 } 4683 } 4684 } 4685 return DEX_OPT_SKIPPED; 4686 } 4687 4688 private String getAppInstructionSet(ApplicationInfo info) { 4689 String instructionSet = getPreferredInstructionSet(); 4690 4691 if (info.cpuAbi != null) { 4692 instructionSet = VMRuntime.getInstructionSet(info.cpuAbi); 4693 } 4694 4695 return instructionSet; 4696 } 4697 4698 private String getAppInstructionSetFromSettings(PackageSetting ps) { 4699 String instructionSet = getPreferredInstructionSet(); 4700 4701 if (ps.cpuAbiString != null) { 4702 instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString); 4703 } 4704 4705 return instructionSet; 4706 } 4707 4708 private static String getPreferredInstructionSet() { 4709 if (sPreferredInstructionSet == null) { 4710 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4711 } 4712 4713 return sPreferredInstructionSet; 4714 } 4715 4716 private static List<String> getAllInstructionSets() { 4717 final String[] allAbis = Build.SUPPORTED_ABIS; 4718 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4719 4720 for (String abi : allAbis) { 4721 final String instructionSet = VMRuntime.getInstructionSet(abi); 4722 if (!allInstructionSets.contains(instructionSet)) { 4723 allInstructionSets.add(instructionSet); 4724 } 4725 } 4726 4727 return allInstructionSets; 4728 } 4729 4730 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer, 4731 boolean inclDependencies) { 4732 HashSet<String> done; 4733 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4734 done = new HashSet<String>(); 4735 done.add(pkg.packageName); 4736 } else { 4737 done = null; 4738 } 4739 return performDexOptLI(pkg, null /* instruction set override */, forceDex, defer, done); 4740 } 4741 4742 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4743 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4744 Slog.w(TAG, "Unable to update from " + oldPkg.name 4745 + " to " + newPkg.packageName 4746 + ": old package not in system partition"); 4747 return false; 4748 } else if (mPackages.get(oldPkg.name) != null) { 4749 Slog.w(TAG, "Unable to update from " + oldPkg.name 4750 + " to " + newPkg.packageName 4751 + ": old package still exists"); 4752 return false; 4753 } 4754 return true; 4755 } 4756 4757 File getDataPathForUser(int userId) { 4758 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4759 } 4760 4761 private File getDataPathForPackage(String packageName, int userId) { 4762 /* 4763 * Until we fully support multiple users, return the directory we 4764 * previously would have. The PackageManagerTests will need to be 4765 * revised when this is changed back.. 4766 */ 4767 if (userId == 0) { 4768 return new File(mAppDataDir, packageName); 4769 } else { 4770 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4771 + File.separator + packageName); 4772 } 4773 } 4774 4775 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4776 int[] users = sUserManager.getUserIds(); 4777 int res = mInstaller.install(packageName, uid, uid, seinfo); 4778 if (res < 0) { 4779 return res; 4780 } 4781 for (int user : users) { 4782 if (user != 0) { 4783 res = mInstaller.createUserData(packageName, 4784 UserHandle.getUid(user, uid), user, seinfo); 4785 if (res < 0) { 4786 return res; 4787 } 4788 } 4789 } 4790 return res; 4791 } 4792 4793 private int removeDataDirsLI(String packageName) { 4794 int[] users = sUserManager.getUserIds(); 4795 int res = 0; 4796 for (int user : users) { 4797 int resInner = mInstaller.remove(packageName, user); 4798 if (resInner < 0) { 4799 res = resInner; 4800 } 4801 } 4802 4803 final File nativeLibraryFile = new File(mAppLibInstallDir, packageName); 4804 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 4805 if (!nativeLibraryFile.delete()) { 4806 Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath()); 4807 } 4808 4809 return res; 4810 } 4811 4812 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4813 PackageParser.Package changingLib) { 4814 if (file.path != null) { 4815 usesLibraryFiles.add(file.path); 4816 return; 4817 } 4818 PackageParser.Package p = mPackages.get(file.apk); 4819 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4820 // If we are doing this while in the middle of updating a library apk, 4821 // then we need to make sure to use that new apk for determining the 4822 // dependencies here. (We haven't yet finished committing the new apk 4823 // to the package manager state.) 4824 if (p == null || p.packageName.equals(changingLib.packageName)) { 4825 p = changingLib; 4826 } 4827 } 4828 if (p != null) { 4829 usesLibraryFiles.addAll(p.getAllCodePaths()); 4830 } 4831 } 4832 4833 private boolean updateSharedLibrariesLPw(PackageParser.Package pkg, 4834 PackageParser.Package changingLib) { 4835 // We might be upgrading from a version of the platform that did not 4836 // provide per-package native library directories for system apps. 4837 // Fix that up here. 4838 if (isSystemApp(pkg)) { 4839 PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName); 4840 setInternalAppNativeLibraryPath(pkg, ps); 4841 } 4842 4843 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4844 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4845 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4846 for (int i=0; i<N; i++) { 4847 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4848 if (file == null) { 4849 Slog.e(TAG, "Package " + pkg.packageName 4850 + " requires unavailable shared library " 4851 + pkg.usesLibraries.get(i) + "; failing!"); 4852 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 4853 return false; 4854 } 4855 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4856 } 4857 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4858 for (int i=0; i<N; i++) { 4859 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4860 if (file == null) { 4861 Slog.w(TAG, "Package " + pkg.packageName 4862 + " desires unavailable shared library " 4863 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4864 } else { 4865 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4866 } 4867 } 4868 N = usesLibraryFiles.size(); 4869 if (N > 0) { 4870 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4871 } else { 4872 pkg.usesLibraryFiles = null; 4873 } 4874 } 4875 return true; 4876 } 4877 4878 private static boolean hasString(List<String> list, List<String> which) { 4879 if (list == null) { 4880 return false; 4881 } 4882 for (int i=list.size()-1; i>=0; i--) { 4883 for (int j=which.size()-1; j>=0; j--) { 4884 if (which.get(j).equals(list.get(i))) { 4885 return true; 4886 } 4887 } 4888 } 4889 return false; 4890 } 4891 4892 private void updateAllSharedLibrariesLPw() { 4893 for (PackageParser.Package pkg : mPackages.values()) { 4894 updateSharedLibrariesLPw(pkg, null); 4895 } 4896 } 4897 4898 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4899 PackageParser.Package changingPkg) { 4900 ArrayList<PackageParser.Package> res = null; 4901 for (PackageParser.Package pkg : mPackages.values()) { 4902 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4903 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4904 if (res == null) { 4905 res = new ArrayList<PackageParser.Package>(); 4906 } 4907 res.add(pkg); 4908 updateSharedLibrariesLPw(pkg, changingPkg); 4909 } 4910 } 4911 return res; 4912 } 4913 4914 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, 4915 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 4916 final File scanFile = new File(pkg.codePath); 4917 if (pkg.applicationInfo.getCodePath() == null || 4918 pkg.applicationInfo.getResourcePath() == null) { 4919 // Bail out. The resource and code paths haven't been set. 4920 Slog.w(TAG, " Code and resource paths haven't been set correctly"); 4921 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK; 4922 return null; 4923 } 4924 4925 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4926 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4927 } 4928 4929 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4930 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4931 } 4932 4933 if (mCustomResolverComponentName != null && 4934 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4935 setUpCustomResolverActivity(pkg); 4936 } 4937 4938 if (pkg.packageName.equals("android")) { 4939 synchronized (mPackages) { 4940 if (mAndroidApplication != null) { 4941 Slog.w(TAG, "*************************************************"); 4942 Slog.w(TAG, "Core android package being redefined. Skipping."); 4943 Slog.w(TAG, " file=" + scanFile); 4944 Slog.w(TAG, "*************************************************"); 4945 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4946 return null; 4947 } 4948 4949 // Set up information for our fall-back user intent resolution activity. 4950 mPlatformPackage = pkg; 4951 pkg.mVersionCode = mSdkVersion; 4952 mAndroidApplication = pkg.applicationInfo; 4953 4954 if (!mResolverReplaced) { 4955 mResolveActivity.applicationInfo = mAndroidApplication; 4956 mResolveActivity.name = ResolverActivity.class.getName(); 4957 mResolveActivity.packageName = mAndroidApplication.packageName; 4958 mResolveActivity.processName = "system:ui"; 4959 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 4960 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 4961 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 4962 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 4963 mResolveActivity.exported = true; 4964 mResolveActivity.enabled = true; 4965 mResolveInfo.activityInfo = mResolveActivity; 4966 mResolveInfo.priority = 0; 4967 mResolveInfo.preferredOrder = 0; 4968 mResolveInfo.match = 0; 4969 mResolveComponentName = new ComponentName( 4970 mAndroidApplication.packageName, mResolveActivity.name); 4971 } 4972 } 4973 } 4974 4975 if (DEBUG_PACKAGE_SCANNING) { 4976 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4977 Log.d(TAG, "Scanning package " + pkg.packageName); 4978 } 4979 4980 if (mPackages.containsKey(pkg.packageName) 4981 || mSharedLibraries.containsKey(pkg.packageName)) { 4982 Slog.w(TAG, "Application package " + pkg.packageName 4983 + " already installed. Skipping duplicate."); 4984 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4985 return null; 4986 } 4987 4988 // Initialize package source and resource directories 4989 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 4990 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 4991 4992 SharedUserSetting suid = null; 4993 PackageSetting pkgSetting = null; 4994 4995 if (!isSystemApp(pkg)) { 4996 // Only system apps can use these features. 4997 pkg.mOriginalPackages = null; 4998 pkg.mRealPackage = null; 4999 pkg.mAdoptPermissions = null; 5000 } 5001 5002 // writer 5003 synchronized (mPackages) { 5004 if (pkg.mSharedUserId != null) { 5005 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5006 if (suid == null) { 5007 Slog.w(TAG, "Creating application package " + pkg.packageName 5008 + " for shared user failed"); 5009 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5010 return null; 5011 } 5012 if (DEBUG_PACKAGE_SCANNING) { 5013 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5014 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5015 + "): packages=" + suid.packages); 5016 } 5017 } 5018 5019 // Check if we are renaming from an original package name. 5020 PackageSetting origPackage = null; 5021 String realName = null; 5022 if (pkg.mOriginalPackages != null) { 5023 // This package may need to be renamed to a previously 5024 // installed name. Let's check on that... 5025 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5026 if (pkg.mOriginalPackages.contains(renamed)) { 5027 // This package had originally been installed as the 5028 // original name, and we have already taken care of 5029 // transitioning to the new one. Just update the new 5030 // one to continue using the old name. 5031 realName = pkg.mRealPackage; 5032 if (!pkg.packageName.equals(renamed)) { 5033 // Callers into this function may have already taken 5034 // care of renaming the package; only do it here if 5035 // it is not already done. 5036 pkg.setPackageName(renamed); 5037 } 5038 5039 } else { 5040 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5041 if ((origPackage = mSettings.peekPackageLPr( 5042 pkg.mOriginalPackages.get(i))) != null) { 5043 // We do have the package already installed under its 5044 // original name... should we use it? 5045 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5046 // New package is not compatible with original. 5047 origPackage = null; 5048 continue; 5049 } else if (origPackage.sharedUser != null) { 5050 // Make sure uid is compatible between packages. 5051 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5052 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5053 + " to " + pkg.packageName + ": old uid " 5054 + origPackage.sharedUser.name 5055 + " differs from " + pkg.mSharedUserId); 5056 origPackage = null; 5057 continue; 5058 } 5059 } else { 5060 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5061 + pkg.packageName + " to old name " + origPackage.name); 5062 } 5063 break; 5064 } 5065 } 5066 } 5067 } 5068 5069 if (mTransferedPackages.contains(pkg.packageName)) { 5070 Slog.w(TAG, "Package " + pkg.packageName 5071 + " was transferred to another, but its .apk remains"); 5072 } 5073 5074 // Just create the setting, don't add it yet. For already existing packages 5075 // the PkgSetting exists already and doesn't have to be created. 5076 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5077 destResourceFile, pkg.applicationInfo.nativeLibraryDir, 5078 pkg.applicationInfo.cpuAbi, 5079 pkg.applicationInfo.flags, user, false); 5080 if (pkgSetting == null) { 5081 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed"); 5082 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5083 return null; 5084 } 5085 5086 if (pkgSetting.origPackage != null) { 5087 // If we are first transitioning from an original package, 5088 // fix up the new package's name now. We need to do this after 5089 // looking up the package under its new name, so getPackageLP 5090 // can take care of fiddling things correctly. 5091 pkg.setPackageName(origPackage.name); 5092 5093 // File a report about this. 5094 String msg = "New package " + pkgSetting.realName 5095 + " renamed to replace old package " + pkgSetting.name; 5096 reportSettingsProblem(Log.WARN, msg); 5097 5098 // Make a note of it. 5099 mTransferedPackages.add(origPackage.name); 5100 5101 // No longer need to retain this. 5102 pkgSetting.origPackage = null; 5103 } 5104 5105 if (realName != null) { 5106 // Make a note of it. 5107 mTransferedPackages.add(pkg.packageName); 5108 } 5109 5110 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5111 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5112 } 5113 5114 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5115 // Check all shared libraries and map to their actual file path. 5116 // We only do this here for apps not on a system dir, because those 5117 // are the only ones that can fail an install due to this. We 5118 // will take care of the system apps by updating all of their 5119 // library paths after the scan is done. 5120 if (!updateSharedLibrariesLPw(pkg, null)) { 5121 return null; 5122 } 5123 } 5124 5125 if (mFoundPolicyFile) { 5126 SELinuxMMAC.assignSeinfoValue(pkg); 5127 } 5128 5129 pkg.applicationInfo.uid = pkgSetting.appId; 5130 pkg.mExtras = pkgSetting; 5131 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5132 if (!verifySignaturesLP(pkgSetting, pkg)) { 5133 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5134 return null; 5135 } 5136 // The signature has changed, but this package is in the system 5137 // image... let's recover! 5138 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5139 // However... if this package is part of a shared user, but it 5140 // doesn't match the signature of the shared user, let's fail. 5141 // What this means is that you can't change the signatures 5142 // associated with an overall shared user, which doesn't seem all 5143 // that unreasonable. 5144 if (pkgSetting.sharedUser != null) { 5145 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5146 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5147 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser); 5148 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 5149 return null; 5150 } 5151 } 5152 // File a report about this. 5153 String msg = "System package " + pkg.packageName 5154 + " signature changed; retaining data."; 5155 reportSettingsProblem(Log.WARN, msg); 5156 } 5157 } else { 5158 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5159 Slog.e(TAG, "Package " + pkg.packageName 5160 + " upgrade keys do not match the previously installed version; "); 5161 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 5162 return null; 5163 } else { 5164 // signatures may have changed as result of upgrade 5165 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5166 } 5167 } 5168 // Verify that this new package doesn't have any content providers 5169 // that conflict with existing packages. Only do this if the 5170 // package isn't already installed, since we don't want to break 5171 // things that are installed. 5172 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5173 final int N = pkg.providers.size(); 5174 int i; 5175 for (i=0; i<N; i++) { 5176 PackageParser.Provider p = pkg.providers.get(i); 5177 if (p.info.authority != null) { 5178 String names[] = p.info.authority.split(";"); 5179 for (int j = 0; j < names.length; j++) { 5180 if (mProvidersByAuthority.containsKey(names[j])) { 5181 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5182 Slog.w(TAG, "Can't install because provider name " + names[j] + 5183 " (in package " + pkg.applicationInfo.packageName + 5184 ") is already used by " 5185 + ((other != null && other.getComponentName() != null) 5186 ? other.getComponentName().getPackageName() : "?")); 5187 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 5188 return null; 5189 } 5190 } 5191 } 5192 } 5193 } 5194 5195 if (pkg.mAdoptPermissions != null) { 5196 // This package wants to adopt ownership of permissions from 5197 // another package. 5198 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5199 final String origName = pkg.mAdoptPermissions.get(i); 5200 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5201 if (orig != null) { 5202 if (verifyPackageUpdateLPr(orig, pkg)) { 5203 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5204 + pkg.packageName); 5205 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5206 } 5207 } 5208 } 5209 } 5210 } 5211 5212 final String pkgName = pkg.packageName; 5213 5214 final long scanFileTime = scanFile.lastModified(); 5215 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5216 pkg.applicationInfo.processName = fixProcessName( 5217 pkg.applicationInfo.packageName, 5218 pkg.applicationInfo.processName, 5219 pkg.applicationInfo.uid); 5220 5221 File dataPath; 5222 if (mPlatformPackage == pkg) { 5223 // The system package is special. 5224 dataPath = new File (Environment.getDataDirectory(), "system"); 5225 pkg.applicationInfo.dataDir = dataPath.getPath(); 5226 } else { 5227 // This is a normal package, need to make its data directory. 5228 dataPath = getDataPathForPackage(pkg.packageName, 0); 5229 5230 boolean uidError = false; 5231 5232 if (dataPath.exists()) { 5233 int currentUid = 0; 5234 try { 5235 StructStat stat = Os.stat(dataPath.getPath()); 5236 currentUid = stat.st_uid; 5237 } catch (ErrnoException e) { 5238 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5239 } 5240 5241 // If we have mismatched owners for the data path, we have a problem. 5242 if (currentUid != pkg.applicationInfo.uid) { 5243 boolean recovered = false; 5244 if (currentUid == 0) { 5245 // The directory somehow became owned by root. Wow. 5246 // This is probably because the system was stopped while 5247 // installd was in the middle of messing with its libs 5248 // directory. Ask installd to fix that. 5249 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5250 pkg.applicationInfo.uid); 5251 if (ret >= 0) { 5252 recovered = true; 5253 String msg = "Package " + pkg.packageName 5254 + " unexpectedly changed to uid 0; recovered to " + 5255 + pkg.applicationInfo.uid; 5256 reportSettingsProblem(Log.WARN, msg); 5257 } 5258 } 5259 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5260 || (scanMode&SCAN_BOOTING) != 0)) { 5261 // If this is a system app, we can at least delete its 5262 // current data so the application will still work. 5263 int ret = removeDataDirsLI(pkgName); 5264 if (ret >= 0) { 5265 // TODO: Kill the processes first 5266 // Old data gone! 5267 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5268 ? "System package " : "Third party package "; 5269 String msg = prefix + pkg.packageName 5270 + " has changed from uid: " 5271 + currentUid + " to " 5272 + pkg.applicationInfo.uid + "; old data erased"; 5273 reportSettingsProblem(Log.WARN, msg); 5274 recovered = true; 5275 5276 // And now re-install the app. 5277 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5278 pkg.applicationInfo.seinfo); 5279 if (ret == -1) { 5280 // Ack should not happen! 5281 msg = prefix + pkg.packageName 5282 + " could not have data directory re-created after delete."; 5283 reportSettingsProblem(Log.WARN, msg); 5284 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5285 return null; 5286 } 5287 } 5288 if (!recovered) { 5289 mHasSystemUidErrors = true; 5290 } 5291 } else if (!recovered) { 5292 // If we allow this install to proceed, we will be broken. 5293 // Abort, abort! 5294 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED; 5295 return null; 5296 } 5297 if (!recovered) { 5298 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5299 + pkg.applicationInfo.uid + "/fs_" 5300 + currentUid; 5301 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5302 String msg = "Package " + pkg.packageName 5303 + " has mismatched uid: " 5304 + currentUid + " on disk, " 5305 + pkg.applicationInfo.uid + " in settings"; 5306 // writer 5307 synchronized (mPackages) { 5308 mSettings.mReadMessages.append(msg); 5309 mSettings.mReadMessages.append('\n'); 5310 uidError = true; 5311 if (!pkgSetting.uidError) { 5312 reportSettingsProblem(Log.ERROR, msg); 5313 } 5314 } 5315 } 5316 } 5317 pkg.applicationInfo.dataDir = dataPath.getPath(); 5318 if (mShouldRestoreconData) { 5319 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5320 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5321 pkg.applicationInfo.uid); 5322 } 5323 } else { 5324 if (DEBUG_PACKAGE_SCANNING) { 5325 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5326 Log.v(TAG, "Want this data dir: " + dataPath); 5327 } 5328 //invoke installer to do the actual installation 5329 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5330 pkg.applicationInfo.seinfo); 5331 if (ret < 0) { 5332 // Error from installer 5333 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5334 return null; 5335 } 5336 5337 if (dataPath.exists()) { 5338 pkg.applicationInfo.dataDir = dataPath.getPath(); 5339 } else { 5340 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5341 pkg.applicationInfo.dataDir = null; 5342 } 5343 } 5344 5345 /* 5346 * Set the data dir to the default "/data/data/<package name>/lib" 5347 * if we got here without anyone telling us different (e.g., apps 5348 * stored on SD card have their native libraries stored in the ASEC 5349 * container with the APK). 5350 * 5351 * This happens during an upgrade from a package settings file that 5352 * doesn't have a native library path attribute at all. 5353 */ 5354 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) { 5355 if (pkgSetting.nativeLibraryPathString == null) { 5356 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5357 } else { 5358 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString; 5359 } 5360 } 5361 pkgSetting.uidError = uidError; 5362 } 5363 5364 final String path = scanFile.getPath(); 5365 /* Note: We don't want to unpack the native binaries for 5366 * system applications, unless they have been updated 5367 * (the binaries are already under /system/lib). 5368 * Also, don't unpack libs for apps on the external card 5369 * since they should have their libraries in the ASEC 5370 * container already. 5371 * 5372 * In other words, we're going to unpack the binaries 5373 * only for non-system apps and system app upgrades. 5374 */ 5375 if (pkg.applicationInfo.nativeLibraryDir != null) { 5376 NativeLibraryHelper.Handle handle = null; 5377 try { 5378 handle = NativeLibraryHelper.Handle.create(scanFile); 5379 // Enable gross and lame hacks for apps that are built with old 5380 // SDK tools. We must scan their APKs for renderscript bitcode and 5381 // not launch them if it's present. Don't bother checking on devices 5382 // that don't have 64 bit support. 5383 String[] abiList = Build.SUPPORTED_ABIS; 5384 boolean hasLegacyRenderscriptBitcode = false; 5385 if (abiOverride != null) { 5386 abiList = new String[] { abiOverride }; 5387 } else if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && 5388 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5389 abiList = Build.SUPPORTED_32_BIT_ABIS; 5390 hasLegacyRenderscriptBitcode = true; 5391 } 5392 5393 File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5394 final String dataPathString = dataPath.getCanonicalPath(); 5395 5396 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5397 /* 5398 * Upgrading from a previous version of the OS sometimes 5399 * leaves native libraries in the /data/data/<app>/lib 5400 * directory for system apps even when they shouldn't be. 5401 * Recent changes in the JNI library search path 5402 * necessitates we remove those to match previous behavior. 5403 */ 5404 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) { 5405 Log.i(TAG, "removed obsolete native libraries for system package " 5406 + path); 5407 } 5408 if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5409 pkg.applicationInfo.cpuAbi = abiList[0]; 5410 pkgSetting.cpuAbiString = abiList[0]; 5411 } else { 5412 setInternalAppAbi(pkg, pkgSetting); 5413 } 5414 } else { 5415 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 5416 /* 5417 * Update native library dir if it starts with 5418 * /data/data 5419 */ 5420 if (nativeLibraryDir.getPath().startsWith(dataPathString)) { 5421 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5422 nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5423 } 5424 5425 try { 5426 int copyRet = copyNativeLibrariesForInternalApp(handle, 5427 nativeLibraryDir, abiList); 5428 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5429 Slog.e(TAG, "Unable to copy native libraries"); 5430 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5431 return null; 5432 } 5433 5434 // We've successfully copied native libraries across, so we make a 5435 // note of what ABI we're using 5436 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5437 pkg.applicationInfo.cpuAbi = abiList[copyRet]; 5438 } else if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5439 pkg.applicationInfo.cpuAbi = abiList[0]; 5440 } else { 5441 pkg.applicationInfo.cpuAbi = null; 5442 } 5443 } catch (IOException e) { 5444 Slog.e(TAG, "Unable to copy native libraries", e); 5445 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5446 return null; 5447 } 5448 } else { 5449 // We don't have to copy the shared libraries if we're in the ASEC container 5450 // but we still need to scan the file to figure out what ABI the app needs. 5451 // 5452 // TODO: This duplicates work done in the default container service. It's possible 5453 // to clean this up but we'll need to change the interface between this service 5454 // and IMediaContainerService (but doing so will spread this logic out, rather 5455 // than centralizing it). 5456 final int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5457 if (abi >= 0) { 5458 pkg.applicationInfo.cpuAbi = abiList[abi]; 5459 } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) { 5460 // Note that (non upgraded) system apps will not have any native 5461 // libraries bundled in their APK, but we're guaranteed not to be 5462 // such an app at this point. 5463 if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5464 pkg.applicationInfo.cpuAbi = abiList[0]; 5465 } else { 5466 pkg.applicationInfo.cpuAbi = null; 5467 } 5468 } else { 5469 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5470 return null; 5471 } 5472 } 5473 5474 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5475 final int[] userIds = sUserManager.getUserIds(); 5476 synchronized (mInstallLock) { 5477 for (int userId : userIds) { 5478 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 5479 pkg.applicationInfo.nativeLibraryDir, userId) < 0) { 5480 Slog.w(TAG, "Failed linking native library dir (user=" + userId 5481 + ")"); 5482 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5483 return null; 5484 } 5485 } 5486 } 5487 } 5488 5489 pkgSetting.cpuAbiString = pkg.applicationInfo.cpuAbi; 5490 } catch (IOException ioe) { 5491 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5492 } finally { 5493 IoUtils.closeQuietly(handle); 5494 } 5495 } 5496 5497 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5498 // We don't do this here during boot because we can do it all 5499 // at once after scanning all existing packages. 5500 // 5501 // We also do this *before* we perform dexopt on this package, so that 5502 // we can avoid redundant dexopts, and also to make sure we've got the 5503 // code and package path correct. 5504 if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5505 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) { 5506 mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE; 5507 return null; 5508 } 5509 } 5510 5511 if ((scanMode&SCAN_NO_DEX) == 0) { 5512 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5513 == DEX_OPT_FAILED) { 5514 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5515 removeDataDirsLI(pkg.packageName); 5516 } 5517 5518 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5519 return null; 5520 } 5521 } 5522 5523 if (mFactoryTest && pkg.requestedPermissions.contains( 5524 android.Manifest.permission.FACTORY_TEST)) { 5525 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5526 } 5527 5528 ArrayList<PackageParser.Package> clientLibPkgs = null; 5529 5530 // writer 5531 synchronized (mPackages) { 5532 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5533 // Only system apps can add new shared libraries. 5534 if (pkg.libraryNames != null) { 5535 for (int i=0; i<pkg.libraryNames.size(); i++) { 5536 String name = pkg.libraryNames.get(i); 5537 boolean allowed = false; 5538 if (isUpdatedSystemApp(pkg)) { 5539 // New library entries can only be added through the 5540 // system image. This is important to get rid of a lot 5541 // of nasty edge cases: for example if we allowed a non- 5542 // system update of the app to add a library, then uninstalling 5543 // the update would make the library go away, and assumptions 5544 // we made such as through app install filtering would now 5545 // have allowed apps on the device which aren't compatible 5546 // with it. Better to just have the restriction here, be 5547 // conservative, and create many fewer cases that can negatively 5548 // impact the user experience. 5549 final PackageSetting sysPs = mSettings 5550 .getDisabledSystemPkgLPr(pkg.packageName); 5551 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5552 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5553 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5554 allowed = true; 5555 allowed = true; 5556 break; 5557 } 5558 } 5559 } 5560 } else { 5561 allowed = true; 5562 } 5563 if (allowed) { 5564 if (!mSharedLibraries.containsKey(name)) { 5565 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5566 } else if (!name.equals(pkg.packageName)) { 5567 Slog.w(TAG, "Package " + pkg.packageName + " library " 5568 + name + " already exists; skipping"); 5569 } 5570 } else { 5571 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5572 + name + " that is not declared on system image; skipping"); 5573 } 5574 } 5575 if ((scanMode&SCAN_BOOTING) == 0) { 5576 // If we are not booting, we need to update any applications 5577 // that are clients of our shared library. If we are booting, 5578 // this will all be done once the scan is complete. 5579 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5580 } 5581 } 5582 } 5583 } 5584 5585 // We also need to dexopt any apps that are dependent on this library. Note that 5586 // if these fail, we should abort the install since installing the library will 5587 // result in some apps being broken. 5588 if (clientLibPkgs != null) { 5589 if ((scanMode&SCAN_NO_DEX) == 0) { 5590 for (int i=0; i<clientLibPkgs.size(); i++) { 5591 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5592 if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5593 == DEX_OPT_FAILED) { 5594 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5595 removeDataDirsLI(pkg.packageName); 5596 } 5597 5598 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5599 return null; 5600 } 5601 } 5602 } 5603 } 5604 5605 // Request the ActivityManager to kill the process(only for existing packages) 5606 // so that we do not end up in a confused state while the user is still using the older 5607 // version of the application while the new one gets installed. 5608 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5609 // If the package lives in an asec, tell everyone that the container is going 5610 // away so they can clean up any references to its resources (which would prevent 5611 // vold from being able to unmount the asec) 5612 if (isForwardLocked(pkg) || isExternal(pkg)) { 5613 if (DEBUG_INSTALL) { 5614 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5615 } 5616 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5617 final ArrayList<String> pkgList = new ArrayList<String>(1); 5618 pkgList.add(pkg.applicationInfo.packageName); 5619 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5620 } 5621 5622 // Post the request that it be killed now that the going-away broadcast is en route 5623 killApplication(pkg.applicationInfo.packageName, 5624 pkg.applicationInfo.uid, "update pkg"); 5625 } 5626 5627 // Also need to kill any apps that are dependent on the library. 5628 if (clientLibPkgs != null) { 5629 for (int i=0; i<clientLibPkgs.size(); i++) { 5630 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5631 killApplication(clientPkg.applicationInfo.packageName, 5632 clientPkg.applicationInfo.uid, "update lib"); 5633 } 5634 } 5635 5636 // writer 5637 synchronized (mPackages) { 5638 // We don't expect installation to fail beyond this point, 5639 if ((scanMode&SCAN_MONITOR) != 0) { 5640 mAppDirs.put(pkg.codePath, pkg); 5641 } 5642 // Add the new setting to mSettings 5643 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5644 // Add the new setting to mPackages 5645 mPackages.put(pkg.applicationInfo.packageName, pkg); 5646 // Make sure we don't accidentally delete its data. 5647 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5648 while (iter.hasNext()) { 5649 PackageCleanItem item = iter.next(); 5650 if (pkgName.equals(item.packageName)) { 5651 iter.remove(); 5652 } 5653 } 5654 5655 // Take care of first install / last update times. 5656 if (currentTime != 0) { 5657 if (pkgSetting.firstInstallTime == 0) { 5658 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5659 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5660 pkgSetting.lastUpdateTime = currentTime; 5661 } 5662 } else if (pkgSetting.firstInstallTime == 0) { 5663 // We need *something*. Take time time stamp of the file. 5664 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5665 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5666 if (scanFileTime != pkgSetting.timeStamp) { 5667 // A package on the system image has changed; consider this 5668 // to be an update. 5669 pkgSetting.lastUpdateTime = scanFileTime; 5670 } 5671 } 5672 5673 // Add the package's KeySets to the global KeySetManagerService 5674 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5675 try { 5676 // Old KeySetData no longer valid. 5677 ksms.removeAppKeySetData(pkg.packageName); 5678 ksms.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys); 5679 if (pkg.mKeySetMapping != null) { 5680 for (Map.Entry<String, Set<PublicKey>> entry : 5681 pkg.mKeySetMapping.entrySet()) { 5682 if (entry.getValue() != null) { 5683 ksms.addDefinedKeySetToPackage(pkg.packageName, 5684 entry.getValue(), entry.getKey()); 5685 } 5686 } 5687 if (pkg.mUpgradeKeySets != null 5688 && pkg.mKeySetMapping.keySet().containsAll(pkg.mUpgradeKeySets)) { 5689 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5690 ksms.addUpgradeKeySetToPackage(pkg.packageName, upgradeAlias); 5691 } 5692 } 5693 } 5694 } catch (NullPointerException e) { 5695 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5696 } catch (IllegalArgumentException e) { 5697 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5698 } 5699 5700 int N = pkg.providers.size(); 5701 StringBuilder r = null; 5702 int i; 5703 for (i=0; i<N; i++) { 5704 PackageParser.Provider p = pkg.providers.get(i); 5705 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5706 p.info.processName, pkg.applicationInfo.uid); 5707 mProviders.addProvider(p); 5708 p.syncable = p.info.isSyncable; 5709 if (p.info.authority != null) { 5710 String names[] = p.info.authority.split(";"); 5711 p.info.authority = null; 5712 for (int j = 0; j < names.length; j++) { 5713 if (j == 1 && p.syncable) { 5714 // We only want the first authority for a provider to possibly be 5715 // syncable, so if we already added this provider using a different 5716 // authority clear the syncable flag. We copy the provider before 5717 // changing it because the mProviders object contains a reference 5718 // to a provider that we don't want to change. 5719 // Only do this for the second authority since the resulting provider 5720 // object can be the same for all future authorities for this provider. 5721 p = new PackageParser.Provider(p); 5722 p.syncable = false; 5723 } 5724 if (!mProvidersByAuthority.containsKey(names[j])) { 5725 mProvidersByAuthority.put(names[j], p); 5726 if (p.info.authority == null) { 5727 p.info.authority = names[j]; 5728 } else { 5729 p.info.authority = p.info.authority + ";" + names[j]; 5730 } 5731 if (DEBUG_PACKAGE_SCANNING) { 5732 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5733 Log.d(TAG, "Registered content provider: " + names[j] 5734 + ", className = " + p.info.name + ", isSyncable = " 5735 + p.info.isSyncable); 5736 } 5737 } else { 5738 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5739 Slog.w(TAG, "Skipping provider name " + names[j] + 5740 " (in package " + pkg.applicationInfo.packageName + 5741 "): name already used by " 5742 + ((other != null && other.getComponentName() != null) 5743 ? other.getComponentName().getPackageName() : "?")); 5744 } 5745 } 5746 } 5747 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5748 if (r == null) { 5749 r = new StringBuilder(256); 5750 } else { 5751 r.append(' '); 5752 } 5753 r.append(p.info.name); 5754 } 5755 } 5756 if (r != null) { 5757 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5758 } 5759 5760 N = pkg.services.size(); 5761 r = null; 5762 for (i=0; i<N; i++) { 5763 PackageParser.Service s = pkg.services.get(i); 5764 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5765 s.info.processName, pkg.applicationInfo.uid); 5766 mServices.addService(s); 5767 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5768 if (r == null) { 5769 r = new StringBuilder(256); 5770 } else { 5771 r.append(' '); 5772 } 5773 r.append(s.info.name); 5774 } 5775 } 5776 if (r != null) { 5777 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5778 } 5779 5780 N = pkg.receivers.size(); 5781 r = null; 5782 for (i=0; i<N; i++) { 5783 PackageParser.Activity a = pkg.receivers.get(i); 5784 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5785 a.info.processName, pkg.applicationInfo.uid); 5786 mReceivers.addActivity(a, "receiver"); 5787 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5788 if (r == null) { 5789 r = new StringBuilder(256); 5790 } else { 5791 r.append(' '); 5792 } 5793 r.append(a.info.name); 5794 } 5795 } 5796 if (r != null) { 5797 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5798 } 5799 5800 N = pkg.activities.size(); 5801 r = null; 5802 for (i=0; i<N; i++) { 5803 PackageParser.Activity a = pkg.activities.get(i); 5804 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5805 a.info.processName, pkg.applicationInfo.uid); 5806 mActivities.addActivity(a, "activity"); 5807 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5808 if (r == null) { 5809 r = new StringBuilder(256); 5810 } else { 5811 r.append(' '); 5812 } 5813 r.append(a.info.name); 5814 } 5815 } 5816 if (r != null) { 5817 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5818 } 5819 5820 N = pkg.permissionGroups.size(); 5821 r = null; 5822 for (i=0; i<N; i++) { 5823 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5824 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5825 if (cur == null) { 5826 mPermissionGroups.put(pg.info.name, pg); 5827 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5828 if (r == null) { 5829 r = new StringBuilder(256); 5830 } else { 5831 r.append(' '); 5832 } 5833 r.append(pg.info.name); 5834 } 5835 } else { 5836 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5837 + pg.info.packageName + " ignored: original from " 5838 + cur.info.packageName); 5839 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5840 if (r == null) { 5841 r = new StringBuilder(256); 5842 } else { 5843 r.append(' '); 5844 } 5845 r.append("DUP:"); 5846 r.append(pg.info.name); 5847 } 5848 } 5849 } 5850 if (r != null) { 5851 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5852 } 5853 5854 N = pkg.permissions.size(); 5855 r = null; 5856 for (i=0; i<N; i++) { 5857 PackageParser.Permission p = pkg.permissions.get(i); 5858 HashMap<String, BasePermission> permissionMap = 5859 p.tree ? mSettings.mPermissionTrees 5860 : mSettings.mPermissions; 5861 p.group = mPermissionGroups.get(p.info.group); 5862 if (p.info.group == null || p.group != null) { 5863 BasePermission bp = permissionMap.get(p.info.name); 5864 if (bp == null) { 5865 bp = new BasePermission(p.info.name, p.info.packageName, 5866 BasePermission.TYPE_NORMAL); 5867 permissionMap.put(p.info.name, bp); 5868 } 5869 if (bp.perm == null) { 5870 if (bp.sourcePackage != null 5871 && !bp.sourcePackage.equals(p.info.packageName)) { 5872 // If this is a permission that was formerly defined by a non-system 5873 // app, but is now defined by a system app (following an upgrade), 5874 // discard the previous declaration and consider the system's to be 5875 // canonical. 5876 if (isSystemApp(p.owner)) { 5877 String msg = "New decl " + p.owner + " of permission " 5878 + p.info.name + " is system"; 5879 reportSettingsProblem(Log.WARN, msg); 5880 bp.sourcePackage = null; 5881 } 5882 } 5883 if (bp.sourcePackage == null 5884 || bp.sourcePackage.equals(p.info.packageName)) { 5885 BasePermission tree = findPermissionTreeLP(p.info.name); 5886 if (tree == null 5887 || tree.sourcePackage.equals(p.info.packageName)) { 5888 bp.packageSetting = pkgSetting; 5889 bp.perm = p; 5890 bp.uid = pkg.applicationInfo.uid; 5891 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5892 if (r == null) { 5893 r = new StringBuilder(256); 5894 } else { 5895 r.append(' '); 5896 } 5897 r.append(p.info.name); 5898 } 5899 } else { 5900 Slog.w(TAG, "Permission " + p.info.name + " from package " 5901 + p.info.packageName + " ignored: base tree " 5902 + tree.name + " is from package " 5903 + tree.sourcePackage); 5904 } 5905 } else { 5906 Slog.w(TAG, "Permission " + p.info.name + " from package " 5907 + p.info.packageName + " ignored: original from " 5908 + bp.sourcePackage); 5909 } 5910 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5911 if (r == null) { 5912 r = new StringBuilder(256); 5913 } else { 5914 r.append(' '); 5915 } 5916 r.append("DUP:"); 5917 r.append(p.info.name); 5918 } 5919 if (bp.perm == p) { 5920 bp.protectionLevel = p.info.protectionLevel; 5921 } 5922 } else { 5923 Slog.w(TAG, "Permission " + p.info.name + " from package " 5924 + p.info.packageName + " ignored: no group " 5925 + p.group); 5926 } 5927 } 5928 if (r != null) { 5929 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 5930 } 5931 5932 N = pkg.instrumentation.size(); 5933 r = null; 5934 for (i=0; i<N; i++) { 5935 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5936 a.info.packageName = pkg.applicationInfo.packageName; 5937 a.info.sourceDir = pkg.applicationInfo.sourceDir; 5938 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 5939 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 5940 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 5941 a.info.dataDir = pkg.applicationInfo.dataDir; 5942 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 5943 mInstrumentation.put(a.getComponentName(), a); 5944 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5945 if (r == null) { 5946 r = new StringBuilder(256); 5947 } else { 5948 r.append(' '); 5949 } 5950 r.append(a.info.name); 5951 } 5952 } 5953 if (r != null) { 5954 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 5955 } 5956 5957 if (pkg.protectedBroadcasts != null) { 5958 N = pkg.protectedBroadcasts.size(); 5959 for (i=0; i<N; i++) { 5960 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 5961 } 5962 } 5963 5964 pkgSetting.setTimeStamp(scanFileTime); 5965 5966 // Create idmap files for pairs of (packages, overlay packages). 5967 // Note: "android", ie framework-res.apk, is handled by native layers. 5968 if (pkg.mOverlayTarget != null) { 5969 // This is an overlay package. 5970 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 5971 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 5972 mOverlays.put(pkg.mOverlayTarget, 5973 new HashMap<String, PackageParser.Package>()); 5974 } 5975 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 5976 map.put(pkg.packageName, pkg); 5977 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 5978 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 5979 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 5980 return null; 5981 } 5982 } 5983 } else if (mOverlays.containsKey(pkg.packageName) && 5984 !pkg.packageName.equals("android")) { 5985 // This is a regular package, with one or more known overlay packages. 5986 createIdmapsForPackageLI(pkg); 5987 } 5988 } 5989 5990 return pkg; 5991 } 5992 5993 /** 5994 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 5995 * i.e, so that all packages can be run inside a single process if required. 5996 * 5997 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 5998 * this function will either try and make the ABI for all packages in {@code packagesForUser} 5999 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6000 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6001 * updating a package that belongs to a shared user. 6002 */ 6003 private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6004 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6005 String requiredInstructionSet = null; 6006 if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) { 6007 requiredInstructionSet = VMRuntime.getInstructionSet( 6008 scannedPackage.applicationInfo.cpuAbi); 6009 } 6010 6011 PackageSetting requirer = null; 6012 for (PackageSetting ps : packagesForUser) { 6013 // If packagesForUser contains scannedPackage, we skip it. This will happen 6014 // when scannedPackage is an update of an existing package. Without this check, 6015 // we will never be able to change the ABI of any package belonging to a shared 6016 // user, even if it's compatible with other packages. 6017 if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) { 6018 if (ps.cpuAbiString == null) { 6019 continue; 6020 } 6021 6022 final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString); 6023 if (requiredInstructionSet != null) { 6024 if (!instructionSet.equals(requiredInstructionSet)) { 6025 // We have a mismatch between instruction sets (say arm vs arm64). 6026 // bail out. 6027 String errorMessage = "Instruction set mismatch, " 6028 + ((requirer == null) ? "[caller]" : requirer) 6029 + " requires " + requiredInstructionSet + " whereas " + ps 6030 + " requires " + instructionSet; 6031 Slog.e(TAG, errorMessage); 6032 6033 reportSettingsProblem(Log.WARN, errorMessage); 6034 // Give up, don't bother making any other changes to the package settings. 6035 return false; 6036 } 6037 } else { 6038 requiredInstructionSet = instructionSet; 6039 requirer = ps; 6040 } 6041 } 6042 } 6043 6044 if (requiredInstructionSet != null) { 6045 String adjustedAbi; 6046 if (requirer != null) { 6047 // requirer != null implies that either scannedPackage was null or that scannedPackage 6048 // did not require an ABI, in which case we have to adjust scannedPackage to match 6049 // the ABI of the set (which is the same as requirer's ABI) 6050 adjustedAbi = requirer.cpuAbiString; 6051 if (scannedPackage != null) { 6052 scannedPackage.applicationInfo.cpuAbi = adjustedAbi; 6053 } 6054 } else { 6055 // requirer == null implies that we're updating all ABIs in the set to 6056 // match scannedPackage. 6057 adjustedAbi = scannedPackage.applicationInfo.cpuAbi; 6058 } 6059 6060 for (PackageSetting ps : packagesForUser) { 6061 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6062 if (ps.cpuAbiString != null) { 6063 continue; 6064 } 6065 6066 ps.cpuAbiString = adjustedAbi; 6067 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6068 ps.pkg.applicationInfo.cpuAbi = adjustedAbi; 6069 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6070 6071 if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) { 6072 ps.cpuAbiString = null; 6073 ps.pkg.applicationInfo.cpuAbi = null; 6074 return false; 6075 } else { 6076 mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet()); 6077 } 6078 } 6079 } 6080 } 6081 } 6082 6083 return true; 6084 } 6085 6086 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6087 synchronized (mPackages) { 6088 mResolverReplaced = true; 6089 // Set up information for custom user intent resolution activity. 6090 mResolveActivity.applicationInfo = pkg.applicationInfo; 6091 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6092 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6093 mResolveActivity.processName = null; 6094 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6095 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6096 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6097 mResolveActivity.theme = 0; 6098 mResolveActivity.exported = true; 6099 mResolveActivity.enabled = true; 6100 mResolveInfo.activityInfo = mResolveActivity; 6101 mResolveInfo.priority = 0; 6102 mResolveInfo.preferredOrder = 0; 6103 mResolveInfo.match = 0; 6104 mResolveComponentName = mCustomResolverComponentName; 6105 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6106 mResolveComponentName); 6107 } 6108 } 6109 6110 private String calculateApkRoot(final String codePathString) { 6111 final File codePath = new File(codePathString); 6112 final File codeRoot; 6113 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6114 codeRoot = Environment.getRootDirectory(); 6115 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6116 codeRoot = Environment.getOemDirectory(); 6117 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6118 codeRoot = Environment.getVendorDirectory(); 6119 } else { 6120 // Unrecognized code path; take its top real segment as the apk root: 6121 // e.g. /something/app/blah.apk => /something 6122 try { 6123 File f = codePath.getCanonicalFile(); 6124 File parent = f.getParentFile(); // non-null because codePath is a file 6125 File tmp; 6126 while ((tmp = parent.getParentFile()) != null) { 6127 f = parent; 6128 parent = tmp; 6129 } 6130 codeRoot = f; 6131 Slog.w(TAG, "Unrecognized code path " 6132 + codePath + " - using " + codeRoot); 6133 } catch (IOException e) { 6134 // Can't canonicalize the lib path -- shenanigans? 6135 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6136 return Environment.getRootDirectory().getPath(); 6137 } 6138 } 6139 return codeRoot.getPath(); 6140 } 6141 6142 // This is the initial scan-time determination of how to handle a given 6143 // package for purposes of native library location. 6144 private void setInternalAppNativeLibraryPath(PackageParser.Package pkg, 6145 PackageSetting pkgSetting) { 6146 // "bundled" here means system-installed with no overriding update 6147 final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg); 6148 final File codeFile = new File(pkg.applicationInfo.getCodePath()); 6149 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6150 final String nativeLibraryPath; 6151 if (bundledApk) { 6152 // If "/system/lib64/apkname" exists, assume that is the per-package 6153 // native library directory to use; otherwise use "/system/lib/apkname". 6154 String apkRoot = calculateApkRoot(pkg.applicationInfo.getCodePath()); 6155 File lib64 = new File(apkRoot, LIB64_DIR_NAME); 6156 File packLib64 = new File(lib64, apkName); 6157 File libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME); 6158 nativeLibraryPath = (new File(libDir, apkName)).getAbsolutePath(); 6159 } else { 6160 // We're installing an upgrade; use directory found during scan 6161 // TODO: consider deriving this based on instructionSet 6162 nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir; 6163 } 6164 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath; 6165 // pkgSetting might be null during rescan following uninstall of updates 6166 // to a bundled app, so accommodate that possibility. The settings in 6167 // that case will be established later from the parsed package. 6168 if (pkgSetting != null) { 6169 pkgSetting.nativeLibraryPathString = nativeLibraryPath; 6170 } 6171 } 6172 6173 // Deduces the required ABI of an upgraded system app. 6174 private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) { 6175 final String apkRoot = calculateApkRoot(pkg.applicationInfo.getCodePath()); 6176 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6177 6178 // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>" 6179 // or similar. 6180 final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath()); 6181 final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath()); 6182 6183 // Assume that the bundled native libraries always correspond to the 6184 // most preferred 32 or 64 bit ABI. 6185 if (lib64.exists()) { 6186 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6187 pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0]; 6188 } else if (lib.exists()) { 6189 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6190 pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0]; 6191 } else { 6192 // This is the case where the app has no native code. 6193 pkg.applicationInfo.cpuAbi = null; 6194 pkgSetting.cpuAbiString = null; 6195 } 6196 } 6197 6198 private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle, 6199 final File nativeLibraryDir, String[] abiList) throws IOException { 6200 if (!nativeLibraryDir.isDirectory()) { 6201 nativeLibraryDir.delete(); 6202 6203 if (!nativeLibraryDir.mkdir()) { 6204 throw new IOException("Cannot create " + nativeLibraryDir.getPath()); 6205 } 6206 6207 try { 6208 Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6209 } catch (ErrnoException e) { 6210 throw new IOException("Cannot chmod native library directory " 6211 + nativeLibraryDir.getPath(), e); 6212 } 6213 } else if (!SELinux.restorecon(nativeLibraryDir)) { 6214 throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath()); 6215 } 6216 6217 /* 6218 * If this is an internal application or our nativeLibraryPath points to 6219 * the app-lib directory, unpack the libraries if necessary. 6220 */ 6221 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6222 if (abi >= 0) { 6223 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, 6224 nativeLibraryDir, Build.SUPPORTED_ABIS[abi]); 6225 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6226 return copyRet; 6227 } 6228 } 6229 6230 return abi; 6231 } 6232 6233 private void killApplication(String pkgName, int appId, String reason) { 6234 // Request the ActivityManager to kill the process(only for existing packages) 6235 // so that we do not end up in a confused state while the user is still using the older 6236 // version of the application while the new one gets installed. 6237 IActivityManager am = ActivityManagerNative.getDefault(); 6238 if (am != null) { 6239 try { 6240 am.killApplicationWithAppId(pkgName, appId, reason); 6241 } catch (RemoteException e) { 6242 } 6243 } 6244 } 6245 6246 void removePackageLI(PackageSetting ps, boolean chatty) { 6247 if (DEBUG_INSTALL) { 6248 if (chatty) 6249 Log.d(TAG, "Removing package " + ps.name); 6250 } 6251 6252 // writer 6253 synchronized (mPackages) { 6254 mPackages.remove(ps.name); 6255 if (ps.codePathString != null) { 6256 mAppDirs.remove(ps.codePathString); 6257 } 6258 6259 final PackageParser.Package pkg = ps.pkg; 6260 if (pkg != null) { 6261 cleanPackageDataStructuresLILPw(pkg, chatty); 6262 } 6263 } 6264 } 6265 6266 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6267 if (DEBUG_INSTALL) { 6268 if (chatty) 6269 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6270 } 6271 6272 // writer 6273 synchronized (mPackages) { 6274 mPackages.remove(pkg.applicationInfo.packageName); 6275 if (pkg.codePath != null) { 6276 mAppDirs.remove(pkg.codePath); 6277 } 6278 cleanPackageDataStructuresLILPw(pkg, chatty); 6279 } 6280 } 6281 6282 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6283 int N = pkg.providers.size(); 6284 StringBuilder r = null; 6285 int i; 6286 for (i=0; i<N; i++) { 6287 PackageParser.Provider p = pkg.providers.get(i); 6288 mProviders.removeProvider(p); 6289 if (p.info.authority == null) { 6290 6291 /* There was another ContentProvider with this authority when 6292 * this app was installed so this authority is null, 6293 * Ignore it as we don't have to unregister the provider. 6294 */ 6295 continue; 6296 } 6297 String names[] = p.info.authority.split(";"); 6298 for (int j = 0; j < names.length; j++) { 6299 if (mProvidersByAuthority.get(names[j]) == p) { 6300 mProvidersByAuthority.remove(names[j]); 6301 if (DEBUG_REMOVE) { 6302 if (chatty) 6303 Log.d(TAG, "Unregistered content provider: " + names[j] 6304 + ", className = " + p.info.name + ", isSyncable = " 6305 + p.info.isSyncable); 6306 } 6307 } 6308 } 6309 if (DEBUG_REMOVE && chatty) { 6310 if (r == null) { 6311 r = new StringBuilder(256); 6312 } else { 6313 r.append(' '); 6314 } 6315 r.append(p.info.name); 6316 } 6317 } 6318 if (r != null) { 6319 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6320 } 6321 6322 N = pkg.services.size(); 6323 r = null; 6324 for (i=0; i<N; i++) { 6325 PackageParser.Service s = pkg.services.get(i); 6326 mServices.removeService(s); 6327 if (chatty) { 6328 if (r == null) { 6329 r = new StringBuilder(256); 6330 } else { 6331 r.append(' '); 6332 } 6333 r.append(s.info.name); 6334 } 6335 } 6336 if (r != null) { 6337 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6338 } 6339 6340 N = pkg.receivers.size(); 6341 r = null; 6342 for (i=0; i<N; i++) { 6343 PackageParser.Activity a = pkg.receivers.get(i); 6344 mReceivers.removeActivity(a, "receiver"); 6345 if (DEBUG_REMOVE && chatty) { 6346 if (r == null) { 6347 r = new StringBuilder(256); 6348 } else { 6349 r.append(' '); 6350 } 6351 r.append(a.info.name); 6352 } 6353 } 6354 if (r != null) { 6355 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6356 } 6357 6358 N = pkg.activities.size(); 6359 r = null; 6360 for (i=0; i<N; i++) { 6361 PackageParser.Activity a = pkg.activities.get(i); 6362 mActivities.removeActivity(a, "activity"); 6363 if (DEBUG_REMOVE && chatty) { 6364 if (r == null) { 6365 r = new StringBuilder(256); 6366 } else { 6367 r.append(' '); 6368 } 6369 r.append(a.info.name); 6370 } 6371 } 6372 if (r != null) { 6373 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6374 } 6375 6376 N = pkg.permissions.size(); 6377 r = null; 6378 for (i=0; i<N; i++) { 6379 PackageParser.Permission p = pkg.permissions.get(i); 6380 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6381 if (bp == null) { 6382 bp = mSettings.mPermissionTrees.get(p.info.name); 6383 } 6384 if (bp != null && bp.perm == p) { 6385 bp.perm = null; 6386 if (DEBUG_REMOVE && chatty) { 6387 if (r == null) { 6388 r = new StringBuilder(256); 6389 } else { 6390 r.append(' '); 6391 } 6392 r.append(p.info.name); 6393 } 6394 } 6395 } 6396 if (r != null) { 6397 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6398 } 6399 6400 N = pkg.instrumentation.size(); 6401 r = null; 6402 for (i=0; i<N; i++) { 6403 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6404 mInstrumentation.remove(a.getComponentName()); 6405 if (DEBUG_REMOVE && chatty) { 6406 if (r == null) { 6407 r = new StringBuilder(256); 6408 } else { 6409 r.append(' '); 6410 } 6411 r.append(a.info.name); 6412 } 6413 } 6414 if (r != null) { 6415 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6416 } 6417 6418 r = null; 6419 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6420 // Only system apps can hold shared libraries. 6421 if (pkg.libraryNames != null) { 6422 for (i=0; i<pkg.libraryNames.size(); i++) { 6423 String name = pkg.libraryNames.get(i); 6424 SharedLibraryEntry cur = mSharedLibraries.get(name); 6425 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6426 mSharedLibraries.remove(name); 6427 if (DEBUG_REMOVE && chatty) { 6428 if (r == null) { 6429 r = new StringBuilder(256); 6430 } else { 6431 r.append(' '); 6432 } 6433 r.append(name); 6434 } 6435 } 6436 } 6437 } 6438 } 6439 if (r != null) { 6440 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6441 } 6442 } 6443 6444 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6445 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6446 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6447 return true; 6448 } 6449 } 6450 return false; 6451 } 6452 6453 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6454 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6455 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6456 6457 private void updatePermissionsLPw(String changingPkg, 6458 PackageParser.Package pkgInfo, int flags) { 6459 // Make sure there are no dangling permission trees. 6460 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6461 while (it.hasNext()) { 6462 final BasePermission bp = it.next(); 6463 if (bp.packageSetting == null) { 6464 // We may not yet have parsed the package, so just see if 6465 // we still know about its settings. 6466 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6467 } 6468 if (bp.packageSetting == null) { 6469 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6470 + " from package " + bp.sourcePackage); 6471 it.remove(); 6472 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6473 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6474 Slog.i(TAG, "Removing old permission tree: " + bp.name 6475 + " from package " + bp.sourcePackage); 6476 flags |= UPDATE_PERMISSIONS_ALL; 6477 it.remove(); 6478 } 6479 } 6480 } 6481 6482 // Make sure all dynamic permissions have been assigned to a package, 6483 // and make sure there are no dangling permissions. 6484 it = mSettings.mPermissions.values().iterator(); 6485 while (it.hasNext()) { 6486 final BasePermission bp = it.next(); 6487 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6488 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6489 + bp.name + " pkg=" + bp.sourcePackage 6490 + " info=" + bp.pendingInfo); 6491 if (bp.packageSetting == null && bp.pendingInfo != null) { 6492 final BasePermission tree = findPermissionTreeLP(bp.name); 6493 if (tree != null && tree.perm != null) { 6494 bp.packageSetting = tree.packageSetting; 6495 bp.perm = new PackageParser.Permission(tree.perm.owner, 6496 new PermissionInfo(bp.pendingInfo)); 6497 bp.perm.info.packageName = tree.perm.info.packageName; 6498 bp.perm.info.name = bp.name; 6499 bp.uid = tree.uid; 6500 } 6501 } 6502 } 6503 if (bp.packageSetting == null) { 6504 // We may not yet have parsed the package, so just see if 6505 // we still know about its settings. 6506 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6507 } 6508 if (bp.packageSetting == null) { 6509 Slog.w(TAG, "Removing dangling permission: " + bp.name 6510 + " from package " + bp.sourcePackage); 6511 it.remove(); 6512 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6513 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6514 Slog.i(TAG, "Removing old permission: " + bp.name 6515 + " from package " + bp.sourcePackage); 6516 flags |= UPDATE_PERMISSIONS_ALL; 6517 it.remove(); 6518 } 6519 } 6520 } 6521 6522 // Now update the permissions for all packages, in particular 6523 // replace the granted permissions of the system packages. 6524 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6525 for (PackageParser.Package pkg : mPackages.values()) { 6526 if (pkg != pkgInfo) { 6527 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6528 } 6529 } 6530 } 6531 6532 if (pkgInfo != null) { 6533 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6534 } 6535 } 6536 6537 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6538 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6539 if (ps == null) { 6540 return; 6541 } 6542 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6543 HashSet<String> origPermissions = gp.grantedPermissions; 6544 boolean changedPermission = false; 6545 6546 if (replace) { 6547 ps.permissionsFixed = false; 6548 if (gp == ps) { 6549 origPermissions = new HashSet<String>(gp.grantedPermissions); 6550 gp.grantedPermissions.clear(); 6551 gp.gids = mGlobalGids; 6552 } 6553 } 6554 6555 if (gp.gids == null) { 6556 gp.gids = mGlobalGids; 6557 } 6558 6559 final int N = pkg.requestedPermissions.size(); 6560 for (int i=0; i<N; i++) { 6561 final String name = pkg.requestedPermissions.get(i); 6562 final boolean required = pkg.requestedPermissionsRequired.get(i); 6563 final BasePermission bp = mSettings.mPermissions.get(name); 6564 if (DEBUG_INSTALL) { 6565 if (gp != ps) { 6566 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6567 } 6568 } 6569 6570 if (bp == null || bp.packageSetting == null) { 6571 Slog.w(TAG, "Unknown permission " + name 6572 + " in package " + pkg.packageName); 6573 continue; 6574 } 6575 6576 final String perm = bp.name; 6577 boolean allowed; 6578 boolean allowedSig = false; 6579 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6580 if (level == PermissionInfo.PROTECTION_NORMAL 6581 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6582 // We grant a normal or dangerous permission if any of the following 6583 // are true: 6584 // 1) The permission is required 6585 // 2) The permission is optional, but was granted in the past 6586 // 3) The permission is optional, but was requested by an 6587 // app in /system (not /data) 6588 // 6589 // Otherwise, reject the permission. 6590 allowed = (required || origPermissions.contains(perm) 6591 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6592 } else if (bp.packageSetting == null) { 6593 // This permission is invalid; skip it. 6594 allowed = false; 6595 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6596 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6597 if (allowed) { 6598 allowedSig = true; 6599 } 6600 } else { 6601 allowed = false; 6602 } 6603 if (DEBUG_INSTALL) { 6604 if (gp != ps) { 6605 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6606 } 6607 } 6608 if (allowed) { 6609 if (!isSystemApp(ps) && ps.permissionsFixed) { 6610 // If this is an existing, non-system package, then 6611 // we can't add any new permissions to it. 6612 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6613 // Except... if this is a permission that was added 6614 // to the platform (note: need to only do this when 6615 // updating the platform). 6616 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6617 } 6618 } 6619 if (allowed) { 6620 if (!gp.grantedPermissions.contains(perm)) { 6621 changedPermission = true; 6622 gp.grantedPermissions.add(perm); 6623 gp.gids = appendInts(gp.gids, bp.gids); 6624 } else if (!ps.haveGids) { 6625 gp.gids = appendInts(gp.gids, bp.gids); 6626 } 6627 } else { 6628 Slog.w(TAG, "Not granting permission " + perm 6629 + " to package " + pkg.packageName 6630 + " because it was previously installed without"); 6631 } 6632 } else { 6633 if (gp.grantedPermissions.remove(perm)) { 6634 changedPermission = true; 6635 gp.gids = removeInts(gp.gids, bp.gids); 6636 Slog.i(TAG, "Un-granting permission " + perm 6637 + " from package " + pkg.packageName 6638 + " (protectionLevel=" + bp.protectionLevel 6639 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6640 + ")"); 6641 } else { 6642 Slog.w(TAG, "Not granting permission " + perm 6643 + " to package " + pkg.packageName 6644 + " (protectionLevel=" + bp.protectionLevel 6645 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6646 + ")"); 6647 } 6648 } 6649 } 6650 6651 if ((changedPermission || replace) && !ps.permissionsFixed && 6652 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6653 // This is the first that we have heard about this package, so the 6654 // permissions we have now selected are fixed until explicitly 6655 // changed. 6656 ps.permissionsFixed = true; 6657 } 6658 ps.haveGids = true; 6659 } 6660 6661 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6662 boolean allowed = false; 6663 final int NP = PackageParser.NEW_PERMISSIONS.length; 6664 for (int ip=0; ip<NP; ip++) { 6665 final PackageParser.NewPermissionInfo npi 6666 = PackageParser.NEW_PERMISSIONS[ip]; 6667 if (npi.name.equals(perm) 6668 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6669 allowed = true; 6670 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6671 + pkg.packageName); 6672 break; 6673 } 6674 } 6675 return allowed; 6676 } 6677 6678 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6679 BasePermission bp, HashSet<String> origPermissions) { 6680 boolean allowed; 6681 allowed = (compareSignatures( 6682 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6683 == PackageManager.SIGNATURE_MATCH) 6684 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6685 == PackageManager.SIGNATURE_MATCH); 6686 if (!allowed && (bp.protectionLevel 6687 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6688 if (isSystemApp(pkg)) { 6689 // For updated system applications, a system permission 6690 // is granted only if it had been defined by the original application. 6691 if (isUpdatedSystemApp(pkg)) { 6692 final PackageSetting sysPs = mSettings 6693 .getDisabledSystemPkgLPr(pkg.packageName); 6694 final GrantedPermissions origGp = sysPs.sharedUser != null 6695 ? sysPs.sharedUser : sysPs; 6696 6697 if (origGp.grantedPermissions.contains(perm)) { 6698 // If the original was granted this permission, we take 6699 // that grant decision as read and propagate it to the 6700 // update. 6701 allowed = true; 6702 } else { 6703 // The system apk may have been updated with an older 6704 // version of the one on the data partition, but which 6705 // granted a new system permission that it didn't have 6706 // before. In this case we do want to allow the app to 6707 // now get the new permission if the ancestral apk is 6708 // privileged to get it. 6709 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6710 for (int j=0; 6711 j<sysPs.pkg.requestedPermissions.size(); j++) { 6712 if (perm.equals( 6713 sysPs.pkg.requestedPermissions.get(j))) { 6714 allowed = true; 6715 break; 6716 } 6717 } 6718 } 6719 } 6720 } else { 6721 allowed = isPrivilegedApp(pkg); 6722 } 6723 } 6724 } 6725 if (!allowed && (bp.protectionLevel 6726 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6727 // For development permissions, a development permission 6728 // is granted only if it was already granted. 6729 allowed = origPermissions.contains(perm); 6730 } 6731 return allowed; 6732 } 6733 6734 final class ActivityIntentResolver 6735 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6736 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6737 boolean defaultOnly, int userId) { 6738 if (!sUserManager.exists(userId)) return null; 6739 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6740 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6741 } 6742 6743 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6744 int userId) { 6745 if (!sUserManager.exists(userId)) return null; 6746 mFlags = flags; 6747 return super.queryIntent(intent, resolvedType, 6748 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6749 } 6750 6751 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6752 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6753 if (!sUserManager.exists(userId)) return null; 6754 if (packageActivities == null) { 6755 return null; 6756 } 6757 mFlags = flags; 6758 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6759 final int N = packageActivities.size(); 6760 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6761 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6762 6763 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6764 for (int i = 0; i < N; ++i) { 6765 intentFilters = packageActivities.get(i).intents; 6766 if (intentFilters != null && intentFilters.size() > 0) { 6767 PackageParser.ActivityIntentInfo[] array = 6768 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6769 intentFilters.toArray(array); 6770 listCut.add(array); 6771 } 6772 } 6773 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6774 } 6775 6776 public final void addActivity(PackageParser.Activity a, String type) { 6777 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6778 mActivities.put(a.getComponentName(), a); 6779 if (DEBUG_SHOW_INFO) 6780 Log.v( 6781 TAG, " " + type + " " + 6782 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6783 if (DEBUG_SHOW_INFO) 6784 Log.v(TAG, " Class=" + a.info.name); 6785 final int NI = a.intents.size(); 6786 for (int j=0; j<NI; j++) { 6787 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6788 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6789 intent.setPriority(0); 6790 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6791 + a.className + " with priority > 0, forcing to 0"); 6792 } 6793 if (DEBUG_SHOW_INFO) { 6794 Log.v(TAG, " IntentFilter:"); 6795 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6796 } 6797 if (!intent.debugCheck()) { 6798 Log.w(TAG, "==> For Activity " + a.info.name); 6799 } 6800 addFilter(intent); 6801 } 6802 } 6803 6804 public final void removeActivity(PackageParser.Activity a, String type) { 6805 mActivities.remove(a.getComponentName()); 6806 if (DEBUG_SHOW_INFO) { 6807 Log.v(TAG, " " + type + " " 6808 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6809 : a.info.name) + ":"); 6810 Log.v(TAG, " Class=" + a.info.name); 6811 } 6812 final int NI = a.intents.size(); 6813 for (int j=0; j<NI; j++) { 6814 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6815 if (DEBUG_SHOW_INFO) { 6816 Log.v(TAG, " IntentFilter:"); 6817 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6818 } 6819 removeFilter(intent); 6820 } 6821 } 6822 6823 @Override 6824 protected boolean allowFilterResult( 6825 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 6826 ActivityInfo filterAi = filter.activity.info; 6827 for (int i=dest.size()-1; i>=0; i--) { 6828 ActivityInfo destAi = dest.get(i).activityInfo; 6829 if (destAi.name == filterAi.name 6830 && destAi.packageName == filterAi.packageName) { 6831 return false; 6832 } 6833 } 6834 return true; 6835 } 6836 6837 @Override 6838 protected ActivityIntentInfo[] newArray(int size) { 6839 return new ActivityIntentInfo[size]; 6840 } 6841 6842 @Override 6843 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 6844 if (!sUserManager.exists(userId)) return true; 6845 PackageParser.Package p = filter.activity.owner; 6846 if (p != null) { 6847 PackageSetting ps = (PackageSetting)p.mExtras; 6848 if (ps != null) { 6849 // System apps are never considered stopped for purposes of 6850 // filtering, because there may be no way for the user to 6851 // actually re-launch them. 6852 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 6853 && ps.getStopped(userId); 6854 } 6855 } 6856 return false; 6857 } 6858 6859 @Override 6860 protected boolean isPackageForFilter(String packageName, 6861 PackageParser.ActivityIntentInfo info) { 6862 return packageName.equals(info.activity.owner.packageName); 6863 } 6864 6865 @Override 6866 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 6867 int match, int userId) { 6868 if (!sUserManager.exists(userId)) return null; 6869 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 6870 return null; 6871 } 6872 final PackageParser.Activity activity = info.activity; 6873 if (mSafeMode && (activity.info.applicationInfo.flags 6874 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6875 return null; 6876 } 6877 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 6878 if (ps == null) { 6879 return null; 6880 } 6881 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 6882 ps.readUserState(userId), userId); 6883 if (ai == null) { 6884 return null; 6885 } 6886 final ResolveInfo res = new ResolveInfo(); 6887 res.activityInfo = ai; 6888 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 6889 res.filter = info; 6890 } 6891 res.priority = info.getPriority(); 6892 res.preferredOrder = activity.owner.mPreferredOrder; 6893 //System.out.println("Result: " + res.activityInfo.className + 6894 // " = " + res.priority); 6895 res.match = match; 6896 res.isDefault = info.hasDefault; 6897 res.labelRes = info.labelRes; 6898 res.nonLocalizedLabel = info.nonLocalizedLabel; 6899 if (userNeedsBadging(userId)) { 6900 res.noResourceId = true; 6901 } else { 6902 res.icon = info.icon; 6903 } 6904 res.system = isSystemApp(res.activityInfo.applicationInfo); 6905 return res; 6906 } 6907 6908 @Override 6909 protected void sortResults(List<ResolveInfo> results) { 6910 Collections.sort(results, mResolvePrioritySorter); 6911 } 6912 6913 @Override 6914 protected void dumpFilter(PrintWriter out, String prefix, 6915 PackageParser.ActivityIntentInfo filter) { 6916 out.print(prefix); out.print( 6917 Integer.toHexString(System.identityHashCode(filter.activity))); 6918 out.print(' '); 6919 filter.activity.printComponentShortName(out); 6920 out.print(" filter "); 6921 out.println(Integer.toHexString(System.identityHashCode(filter))); 6922 } 6923 6924// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 6925// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 6926// final List<ResolveInfo> retList = Lists.newArrayList(); 6927// while (i.hasNext()) { 6928// final ResolveInfo resolveInfo = i.next(); 6929// if (isEnabledLP(resolveInfo.activityInfo)) { 6930// retList.add(resolveInfo); 6931// } 6932// } 6933// return retList; 6934// } 6935 6936 // Keys are String (activity class name), values are Activity. 6937 private final HashMap<ComponentName, PackageParser.Activity> mActivities 6938 = new HashMap<ComponentName, PackageParser.Activity>(); 6939 private int mFlags; 6940 } 6941 6942 private final class ServiceIntentResolver 6943 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 6944 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6945 boolean defaultOnly, int userId) { 6946 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6947 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6948 } 6949 6950 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6951 int userId) { 6952 if (!sUserManager.exists(userId)) return null; 6953 mFlags = flags; 6954 return super.queryIntent(intent, resolvedType, 6955 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6956 } 6957 6958 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6959 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 6960 if (!sUserManager.exists(userId)) return null; 6961 if (packageServices == null) { 6962 return null; 6963 } 6964 mFlags = flags; 6965 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6966 final int N = packageServices.size(); 6967 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 6968 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 6969 6970 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 6971 for (int i = 0; i < N; ++i) { 6972 intentFilters = packageServices.get(i).intents; 6973 if (intentFilters != null && intentFilters.size() > 0) { 6974 PackageParser.ServiceIntentInfo[] array = 6975 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 6976 intentFilters.toArray(array); 6977 listCut.add(array); 6978 } 6979 } 6980 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6981 } 6982 6983 public final void addService(PackageParser.Service s) { 6984 mServices.put(s.getComponentName(), s); 6985 if (DEBUG_SHOW_INFO) { 6986 Log.v(TAG, " " 6987 + (s.info.nonLocalizedLabel != null 6988 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6989 Log.v(TAG, " Class=" + s.info.name); 6990 } 6991 final int NI = s.intents.size(); 6992 int j; 6993 for (j=0; j<NI; j++) { 6994 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6995 if (DEBUG_SHOW_INFO) { 6996 Log.v(TAG, " IntentFilter:"); 6997 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6998 } 6999 if (!intent.debugCheck()) { 7000 Log.w(TAG, "==> For Service " + s.info.name); 7001 } 7002 addFilter(intent); 7003 } 7004 } 7005 7006 public final void removeService(PackageParser.Service s) { 7007 mServices.remove(s.getComponentName()); 7008 if (DEBUG_SHOW_INFO) { 7009 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7010 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7011 Log.v(TAG, " Class=" + s.info.name); 7012 } 7013 final int NI = s.intents.size(); 7014 int j; 7015 for (j=0; j<NI; j++) { 7016 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7017 if (DEBUG_SHOW_INFO) { 7018 Log.v(TAG, " IntentFilter:"); 7019 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7020 } 7021 removeFilter(intent); 7022 } 7023 } 7024 7025 @Override 7026 protected boolean allowFilterResult( 7027 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7028 ServiceInfo filterSi = filter.service.info; 7029 for (int i=dest.size()-1; i>=0; i--) { 7030 ServiceInfo destAi = dest.get(i).serviceInfo; 7031 if (destAi.name == filterSi.name 7032 && destAi.packageName == filterSi.packageName) { 7033 return false; 7034 } 7035 } 7036 return true; 7037 } 7038 7039 @Override 7040 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7041 return new PackageParser.ServiceIntentInfo[size]; 7042 } 7043 7044 @Override 7045 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7046 if (!sUserManager.exists(userId)) return true; 7047 PackageParser.Package p = filter.service.owner; 7048 if (p != null) { 7049 PackageSetting ps = (PackageSetting)p.mExtras; 7050 if (ps != null) { 7051 // System apps are never considered stopped for purposes of 7052 // filtering, because there may be no way for the user to 7053 // actually re-launch them. 7054 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7055 && ps.getStopped(userId); 7056 } 7057 } 7058 return false; 7059 } 7060 7061 @Override 7062 protected boolean isPackageForFilter(String packageName, 7063 PackageParser.ServiceIntentInfo info) { 7064 return packageName.equals(info.service.owner.packageName); 7065 } 7066 7067 @Override 7068 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7069 int match, int userId) { 7070 if (!sUserManager.exists(userId)) return null; 7071 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7072 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7073 return null; 7074 } 7075 final PackageParser.Service service = info.service; 7076 if (mSafeMode && (service.info.applicationInfo.flags 7077 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7078 return null; 7079 } 7080 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7081 if (ps == null) { 7082 return null; 7083 } 7084 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7085 ps.readUserState(userId), userId); 7086 if (si == null) { 7087 return null; 7088 } 7089 final ResolveInfo res = new ResolveInfo(); 7090 res.serviceInfo = si; 7091 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7092 res.filter = filter; 7093 } 7094 res.priority = info.getPriority(); 7095 res.preferredOrder = service.owner.mPreferredOrder; 7096 //System.out.println("Result: " + res.activityInfo.className + 7097 // " = " + res.priority); 7098 res.match = match; 7099 res.isDefault = info.hasDefault; 7100 res.labelRes = info.labelRes; 7101 res.nonLocalizedLabel = info.nonLocalizedLabel; 7102 res.icon = info.icon; 7103 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7104 return res; 7105 } 7106 7107 @Override 7108 protected void sortResults(List<ResolveInfo> results) { 7109 Collections.sort(results, mResolvePrioritySorter); 7110 } 7111 7112 @Override 7113 protected void dumpFilter(PrintWriter out, String prefix, 7114 PackageParser.ServiceIntentInfo filter) { 7115 out.print(prefix); out.print( 7116 Integer.toHexString(System.identityHashCode(filter.service))); 7117 out.print(' '); 7118 filter.service.printComponentShortName(out); 7119 out.print(" filter "); 7120 out.println(Integer.toHexString(System.identityHashCode(filter))); 7121 } 7122 7123// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7124// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7125// final List<ResolveInfo> retList = Lists.newArrayList(); 7126// while (i.hasNext()) { 7127// final ResolveInfo resolveInfo = (ResolveInfo) i; 7128// if (isEnabledLP(resolveInfo.serviceInfo)) { 7129// retList.add(resolveInfo); 7130// } 7131// } 7132// return retList; 7133// } 7134 7135 // Keys are String (activity class name), values are Activity. 7136 private final HashMap<ComponentName, PackageParser.Service> mServices 7137 = new HashMap<ComponentName, PackageParser.Service>(); 7138 private int mFlags; 7139 }; 7140 7141 private final class ProviderIntentResolver 7142 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7143 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7144 boolean defaultOnly, int userId) { 7145 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7146 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7147 } 7148 7149 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7150 int userId) { 7151 if (!sUserManager.exists(userId)) 7152 return null; 7153 mFlags = flags; 7154 return super.queryIntent(intent, resolvedType, 7155 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7156 } 7157 7158 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7159 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7160 if (!sUserManager.exists(userId)) 7161 return null; 7162 if (packageProviders == null) { 7163 return null; 7164 } 7165 mFlags = flags; 7166 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7167 final int N = packageProviders.size(); 7168 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7169 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7170 7171 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7172 for (int i = 0; i < N; ++i) { 7173 intentFilters = packageProviders.get(i).intents; 7174 if (intentFilters != null && intentFilters.size() > 0) { 7175 PackageParser.ProviderIntentInfo[] array = 7176 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7177 intentFilters.toArray(array); 7178 listCut.add(array); 7179 } 7180 } 7181 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7182 } 7183 7184 public final void addProvider(PackageParser.Provider p) { 7185 if (mProviders.containsKey(p.getComponentName())) { 7186 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7187 return; 7188 } 7189 7190 mProviders.put(p.getComponentName(), p); 7191 if (DEBUG_SHOW_INFO) { 7192 Log.v(TAG, " " 7193 + (p.info.nonLocalizedLabel != null 7194 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7195 Log.v(TAG, " Class=" + p.info.name); 7196 } 7197 final int NI = p.intents.size(); 7198 int j; 7199 for (j = 0; j < NI; j++) { 7200 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7201 if (DEBUG_SHOW_INFO) { 7202 Log.v(TAG, " IntentFilter:"); 7203 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7204 } 7205 if (!intent.debugCheck()) { 7206 Log.w(TAG, "==> For Provider " + p.info.name); 7207 } 7208 addFilter(intent); 7209 } 7210 } 7211 7212 public final void removeProvider(PackageParser.Provider p) { 7213 mProviders.remove(p.getComponentName()); 7214 if (DEBUG_SHOW_INFO) { 7215 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7216 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7217 Log.v(TAG, " Class=" + p.info.name); 7218 } 7219 final int NI = p.intents.size(); 7220 int j; 7221 for (j = 0; j < NI; j++) { 7222 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7223 if (DEBUG_SHOW_INFO) { 7224 Log.v(TAG, " IntentFilter:"); 7225 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7226 } 7227 removeFilter(intent); 7228 } 7229 } 7230 7231 @Override 7232 protected boolean allowFilterResult( 7233 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7234 ProviderInfo filterPi = filter.provider.info; 7235 for (int i = dest.size() - 1; i >= 0; i--) { 7236 ProviderInfo destPi = dest.get(i).providerInfo; 7237 if (destPi.name == filterPi.name 7238 && destPi.packageName == filterPi.packageName) { 7239 return false; 7240 } 7241 } 7242 return true; 7243 } 7244 7245 @Override 7246 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7247 return new PackageParser.ProviderIntentInfo[size]; 7248 } 7249 7250 @Override 7251 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7252 if (!sUserManager.exists(userId)) 7253 return true; 7254 PackageParser.Package p = filter.provider.owner; 7255 if (p != null) { 7256 PackageSetting ps = (PackageSetting) p.mExtras; 7257 if (ps != null) { 7258 // System apps are never considered stopped for purposes of 7259 // filtering, because there may be no way for the user to 7260 // actually re-launch them. 7261 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7262 && ps.getStopped(userId); 7263 } 7264 } 7265 return false; 7266 } 7267 7268 @Override 7269 protected boolean isPackageForFilter(String packageName, 7270 PackageParser.ProviderIntentInfo info) { 7271 return packageName.equals(info.provider.owner.packageName); 7272 } 7273 7274 @Override 7275 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7276 int match, int userId) { 7277 if (!sUserManager.exists(userId)) 7278 return null; 7279 final PackageParser.ProviderIntentInfo info = filter; 7280 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7281 return null; 7282 } 7283 final PackageParser.Provider provider = info.provider; 7284 if (mSafeMode && (provider.info.applicationInfo.flags 7285 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7286 return null; 7287 } 7288 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7289 if (ps == null) { 7290 return null; 7291 } 7292 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7293 ps.readUserState(userId), userId); 7294 if (pi == null) { 7295 return null; 7296 } 7297 final ResolveInfo res = new ResolveInfo(); 7298 res.providerInfo = pi; 7299 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7300 res.filter = filter; 7301 } 7302 res.priority = info.getPriority(); 7303 res.preferredOrder = provider.owner.mPreferredOrder; 7304 res.match = match; 7305 res.isDefault = info.hasDefault; 7306 res.labelRes = info.labelRes; 7307 res.nonLocalizedLabel = info.nonLocalizedLabel; 7308 res.icon = info.icon; 7309 res.system = isSystemApp(res.providerInfo.applicationInfo); 7310 return res; 7311 } 7312 7313 @Override 7314 protected void sortResults(List<ResolveInfo> results) { 7315 Collections.sort(results, mResolvePrioritySorter); 7316 } 7317 7318 @Override 7319 protected void dumpFilter(PrintWriter out, String prefix, 7320 PackageParser.ProviderIntentInfo filter) { 7321 out.print(prefix); 7322 out.print( 7323 Integer.toHexString(System.identityHashCode(filter.provider))); 7324 out.print(' '); 7325 filter.provider.printComponentShortName(out); 7326 out.print(" filter "); 7327 out.println(Integer.toHexString(System.identityHashCode(filter))); 7328 } 7329 7330 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7331 = new HashMap<ComponentName, PackageParser.Provider>(); 7332 private int mFlags; 7333 }; 7334 7335 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7336 new Comparator<ResolveInfo>() { 7337 public int compare(ResolveInfo r1, ResolveInfo r2) { 7338 int v1 = r1.priority; 7339 int v2 = r2.priority; 7340 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7341 if (v1 != v2) { 7342 return (v1 > v2) ? -1 : 1; 7343 } 7344 v1 = r1.preferredOrder; 7345 v2 = r2.preferredOrder; 7346 if (v1 != v2) { 7347 return (v1 > v2) ? -1 : 1; 7348 } 7349 if (r1.isDefault != r2.isDefault) { 7350 return r1.isDefault ? -1 : 1; 7351 } 7352 v1 = r1.match; 7353 v2 = r2.match; 7354 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7355 if (v1 != v2) { 7356 return (v1 > v2) ? -1 : 1; 7357 } 7358 if (r1.system != r2.system) { 7359 return r1.system ? -1 : 1; 7360 } 7361 return 0; 7362 } 7363 }; 7364 7365 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7366 new Comparator<ProviderInfo>() { 7367 public int compare(ProviderInfo p1, ProviderInfo p2) { 7368 final int v1 = p1.initOrder; 7369 final int v2 = p2.initOrder; 7370 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7371 } 7372 }; 7373 7374 static final void sendPackageBroadcast(String action, String pkg, 7375 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7376 int[] userIds) { 7377 IActivityManager am = ActivityManagerNative.getDefault(); 7378 if (am != null) { 7379 try { 7380 if (userIds == null) { 7381 userIds = am.getRunningUserIds(); 7382 } 7383 for (int id : userIds) { 7384 final Intent intent = new Intent(action, 7385 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7386 if (extras != null) { 7387 intent.putExtras(extras); 7388 } 7389 if (targetPkg != null) { 7390 intent.setPackage(targetPkg); 7391 } 7392 // Modify the UID when posting to other users 7393 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7394 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7395 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7396 intent.putExtra(Intent.EXTRA_UID, uid); 7397 } 7398 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7399 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7400 if (DEBUG_BROADCASTS) { 7401 RuntimeException here = new RuntimeException("here"); 7402 here.fillInStackTrace(); 7403 Slog.d(TAG, "Sending to user " + id + ": " 7404 + intent.toShortString(false, true, false, false) 7405 + " " + intent.getExtras(), here); 7406 } 7407 am.broadcastIntent(null, intent, null, finishedReceiver, 7408 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7409 finishedReceiver != null, false, id); 7410 } 7411 } catch (RemoteException ex) { 7412 } 7413 } 7414 } 7415 7416 /** 7417 * Check if the external storage media is available. This is true if there 7418 * is a mounted external storage medium or if the external storage is 7419 * emulated. 7420 */ 7421 private boolean isExternalMediaAvailable() { 7422 return mMediaMounted || Environment.isExternalStorageEmulated(); 7423 } 7424 7425 @Override 7426 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7427 // writer 7428 synchronized (mPackages) { 7429 if (!isExternalMediaAvailable()) { 7430 // If the external storage is no longer mounted at this point, 7431 // the caller may not have been able to delete all of this 7432 // packages files and can not delete any more. Bail. 7433 return null; 7434 } 7435 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7436 if (lastPackage != null) { 7437 pkgs.remove(lastPackage); 7438 } 7439 if (pkgs.size() > 0) { 7440 return pkgs.get(0); 7441 } 7442 } 7443 return null; 7444 } 7445 7446 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7447 if (false) { 7448 RuntimeException here = new RuntimeException("here"); 7449 here.fillInStackTrace(); 7450 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7451 + " andCode=" + andCode, here); 7452 } 7453 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7454 userId, andCode ? 1 : 0, packageName)); 7455 } 7456 7457 void startCleaningPackages() { 7458 // reader 7459 synchronized (mPackages) { 7460 if (!isExternalMediaAvailable()) { 7461 return; 7462 } 7463 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7464 return; 7465 } 7466 } 7467 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7468 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7469 IActivityManager am = ActivityManagerNative.getDefault(); 7470 if (am != null) { 7471 try { 7472 am.startService(null, intent, null, UserHandle.USER_OWNER); 7473 } catch (RemoteException e) { 7474 } 7475 } 7476 } 7477 7478 private final class AppDirObserver extends FileObserver { 7479 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 7480 super(path, mask); 7481 mRootDir = path; 7482 mIsRom = isrom; 7483 mIsPrivileged = isPrivileged; 7484 } 7485 7486 public void onEvent(int event, String path) { 7487 String removedPackage = null; 7488 int removedAppId = -1; 7489 int[] removedUsers = null; 7490 String addedPackage = null; 7491 int addedAppId = -1; 7492 int[] addedUsers = null; 7493 7494 // TODO post a message to the handler to obtain serial ordering 7495 synchronized (mInstallLock) { 7496 String fullPathStr = null; 7497 File fullPath = null; 7498 if (path != null) { 7499 fullPath = new File(mRootDir, path); 7500 fullPathStr = fullPath.getPath(); 7501 } 7502 7503 if (DEBUG_APP_DIR_OBSERVER) 7504 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 7505 7506 if (!isApkFile(fullPath)) { 7507 if (DEBUG_APP_DIR_OBSERVER) 7508 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 7509 return; 7510 } 7511 7512 // Ignore packages that are being installed or 7513 // have just been installed. 7514 if (ignoreCodePath(fullPathStr)) { 7515 return; 7516 } 7517 PackageParser.Package p = null; 7518 PackageSetting ps = null; 7519 // reader 7520 synchronized (mPackages) { 7521 p = mAppDirs.get(fullPathStr); 7522 if (p != null) { 7523 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 7524 if (ps != null) { 7525 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7526 } else { 7527 removedUsers = sUserManager.getUserIds(); 7528 } 7529 } 7530 addedUsers = sUserManager.getUserIds(); 7531 } 7532 if ((event&REMOVE_EVENTS) != 0) { 7533 if (ps != null) { 7534 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 7535 removePackageLI(ps, true); 7536 removedPackage = ps.name; 7537 removedAppId = ps.appId; 7538 } 7539 } 7540 7541 if ((event&ADD_EVENTS) != 0) { 7542 if (p == null) { 7543 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 7544 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 7545 if (mIsRom) { 7546 flags |= PackageParser.PARSE_IS_SYSTEM 7547 | PackageParser.PARSE_IS_SYSTEM_DIR; 7548 if (mIsPrivileged) { 7549 flags |= PackageParser.PARSE_IS_PRIVILEGED; 7550 } 7551 } 7552 p = scanPackageLI(fullPath, flags, 7553 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 7554 System.currentTimeMillis(), UserHandle.ALL, null); 7555 if (p != null) { 7556 /* 7557 * TODO this seems dangerous as the package may have 7558 * changed since we last acquired the mPackages 7559 * lock. 7560 */ 7561 // writer 7562 synchronized (mPackages) { 7563 updatePermissionsLPw(p.packageName, p, 7564 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 7565 } 7566 addedPackage = p.applicationInfo.packageName; 7567 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 7568 } 7569 } 7570 } 7571 7572 // reader 7573 synchronized (mPackages) { 7574 mSettings.writeLPr(); 7575 } 7576 } 7577 7578 if (removedPackage != null) { 7579 Bundle extras = new Bundle(1); 7580 extras.putInt(Intent.EXTRA_UID, removedAppId); 7581 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 7582 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7583 extras, null, null, removedUsers); 7584 } 7585 if (addedPackage != null) { 7586 Bundle extras = new Bundle(1); 7587 extras.putInt(Intent.EXTRA_UID, addedAppId); 7588 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 7589 extras, null, null, addedUsers); 7590 } 7591 } 7592 7593 private final String mRootDir; 7594 private final boolean mIsRom; 7595 private final boolean mIsPrivileged; 7596 } 7597 7598 /* 7599 * The old-style observer methods all just trampoline to the newer signature with 7600 * expanded install observer API. The older API continues to work but does not 7601 * supply the additional details of the Observer2 API. 7602 */ 7603 7604 /* Called when a downloaded package installation has been confirmed by the user */ 7605 public void installPackage( 7606 final Uri packageURI, final IPackageInstallObserver observer, final int flags) { 7607 installPackageEtc(packageURI, observer, null, flags, null); 7608 } 7609 7610 /* Called when a downloaded package installation has been confirmed by the user */ 7611 @Override 7612 public void installPackage( 7613 final Uri packageURI, final IPackageInstallObserver observer, final int flags, 7614 final String installerPackageName) { 7615 installPackageWithVerificationEtc(packageURI, observer, null, flags, 7616 installerPackageName, null, null, null); 7617 } 7618 7619 @Override 7620 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer, 7621 int flags, String installerPackageName, Uri verificationURI, 7622 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7623 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7624 VerificationParams.NO_UID, manifestDigest); 7625 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7626 installerPackageName, verificationParams, encryptionParams); 7627 } 7628 7629 @Override 7630 public void installPackageWithVerificationAndEncryption(Uri packageURI, 7631 IPackageInstallObserver observer, int flags, String installerPackageName, 7632 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7633 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7634 installerPackageName, verificationParams, encryptionParams); 7635 } 7636 7637 /* 7638 * And here are the "live" versions that take both observer arguments 7639 */ 7640 public void installPackageEtc( 7641 final Uri packageURI, final IPackageInstallObserver observer, 7642 IPackageInstallObserver2 observer2, final int flags) { 7643 installPackageEtc(packageURI, observer, observer2, flags, null); 7644 } 7645 7646 public void installPackageEtc( 7647 final Uri packageURI, final IPackageInstallObserver observer, 7648 final IPackageInstallObserver2 observer2, final int flags, 7649 final String installerPackageName) { 7650 installPackageWithVerificationEtc(packageURI, observer, observer2, flags, 7651 installerPackageName, null, null, null); 7652 } 7653 7654 @Override 7655 public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer, 7656 IPackageInstallObserver2 observer2, 7657 int flags, String installerPackageName, Uri verificationURI, 7658 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7659 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7660 VerificationParams.NO_UID, manifestDigest); 7661 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags, 7662 installerPackageName, verificationParams, encryptionParams); 7663 } 7664 7665 /* 7666 * All of the installPackage...*() methods redirect to this one for the master implementation 7667 */ 7668 public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI, 7669 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7670 int flags, String installerPackageName, 7671 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7672 if (observer == null && observer2 == null) { 7673 throw new IllegalArgumentException("No install observer supplied"); 7674 } 7675 installPackageWithVerificationEncryptionAndAbiOverrideEtc(packageURI, observer, observer2, 7676 flags, installerPackageName, verificationParams, encryptionParams, null); 7677 } 7678 7679 @Override 7680 public void installPackageWithVerificationEncryptionAndAbiOverrideEtc(Uri packageURI, 7681 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7682 int flags, String installerPackageName, 7683 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams, 7684 String packageAbiOverride) { 7685 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7686 null); 7687 7688 final int uid = Binder.getCallingUid(); 7689 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7690 try { 7691 if (observer != null) { 7692 observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7693 } 7694 if (observer2 != null) { 7695 observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7696 } 7697 } catch (RemoteException re) { 7698 } 7699 return; 7700 } 7701 7702 UserHandle user; 7703 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7704 user = UserHandle.ALL; 7705 } else { 7706 user = new UserHandle(UserHandle.getUserId(uid)); 7707 } 7708 7709 final int filteredFlags; 7710 7711 if (uid == Process.SHELL_UID || uid == 0) { 7712 if (DEBUG_INSTALL) { 7713 Slog.v(TAG, "Install from ADB"); 7714 } 7715 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7716 } else { 7717 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7718 } 7719 7720 verificationParams.setInstallerUid(uid); 7721 7722 if (!"file".equals(packageURI.getScheme())) { 7723 throw new UnsupportedOperationException("Only file:// URIs are supported"); 7724 } 7725 final File fromFile = new File(packageURI.getPath()); 7726 7727 if (encryptionParams != null) { 7728 throw new UnsupportedOperationException("ContainerEncryptionParams not supported"); 7729 } 7730 7731 final Message msg = mHandler.obtainMessage(INIT_COPY); 7732 msg.obj = new InstallParams(fromFile, observer, observer2, filteredFlags, 7733 installerPackageName, verificationParams, user, packageAbiOverride); 7734 mHandler.sendMessage(msg); 7735 } 7736 7737 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7738 Bundle extras = new Bundle(1); 7739 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7740 7741 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7742 packageName, extras, null, null, new int[] {userId}); 7743 try { 7744 IActivityManager am = ActivityManagerNative.getDefault(); 7745 final boolean isSystem = 7746 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7747 if (isSystem && am.isUserRunning(userId, false)) { 7748 // The just-installed/enabled app is bundled on the system, so presumed 7749 // to be able to run automatically without needing an explicit launch. 7750 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7751 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7752 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7753 .setPackage(packageName); 7754 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7755 android.app.AppOpsManager.OP_NONE, false, false, userId); 7756 } 7757 } catch (RemoteException e) { 7758 // shouldn't happen 7759 Slog.w(TAG, "Unable to bootstrap installed package", e); 7760 } 7761 } 7762 7763 @Override 7764 public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked, 7765 int userId) { 7766 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7767 PackageSetting pkgSetting; 7768 final int uid = Binder.getCallingUid(); 7769 if (UserHandle.getUserId(uid) != userId) { 7770 mContext.enforceCallingOrSelfPermission( 7771 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7772 "setApplicationBlockedSetting for user " + userId); 7773 } 7774 7775 if (blocked && isPackageDeviceAdmin(packageName, userId)) { 7776 Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin"); 7777 return false; 7778 } 7779 7780 long callingId = Binder.clearCallingIdentity(); 7781 try { 7782 boolean sendAdded = false; 7783 boolean sendRemoved = false; 7784 // writer 7785 synchronized (mPackages) { 7786 pkgSetting = mSettings.mPackages.get(packageName); 7787 if (pkgSetting == null) { 7788 return false; 7789 } 7790 if (pkgSetting.getBlocked(userId) != blocked) { 7791 pkgSetting.setBlocked(blocked, userId); 7792 mSettings.writePackageRestrictionsLPr(userId); 7793 if (blocked) { 7794 sendRemoved = true; 7795 } else { 7796 sendAdded = true; 7797 } 7798 } 7799 } 7800 if (sendAdded) { 7801 sendPackageAddedForUser(packageName, pkgSetting, userId); 7802 return true; 7803 } 7804 if (sendRemoved) { 7805 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7806 "blocking pkg"); 7807 sendPackageBlockedForUser(packageName, pkgSetting, userId); 7808 } 7809 } finally { 7810 Binder.restoreCallingIdentity(callingId); 7811 } 7812 return false; 7813 } 7814 7815 private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting, 7816 int userId) { 7817 final PackageRemovedInfo info = new PackageRemovedInfo(); 7818 info.removedPackage = packageName; 7819 info.removedUsers = new int[] {userId}; 7820 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7821 info.sendBroadcast(false, false, false); 7822 } 7823 7824 /** 7825 * Returns true if application is not found or there was an error. Otherwise it returns 7826 * the blocked state of the package for the given user. 7827 */ 7828 @Override 7829 public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) { 7830 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7831 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7832 "getApplicationBlocked for user " + userId); 7833 PackageSetting pkgSetting; 7834 long callingId = Binder.clearCallingIdentity(); 7835 try { 7836 // writer 7837 synchronized (mPackages) { 7838 pkgSetting = mSettings.mPackages.get(packageName); 7839 if (pkgSetting == null) { 7840 return true; 7841 } 7842 return pkgSetting.getBlocked(userId); 7843 } 7844 } finally { 7845 Binder.restoreCallingIdentity(callingId); 7846 } 7847 } 7848 7849 void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer2, 7850 PackageInstallerParams params, String installerPackageName, int installerUid, 7851 UserHandle user) { 7852 Slog.e(TAG, "TODO: install stage!"); 7853 try { 7854 observer2.packageInstalled(packageName, null, 7855 PackageManager.INSTALL_FAILED_INTERNAL_ERROR); 7856 } catch (RemoteException ignored) { 7857 } 7858 } 7859 7860 /** 7861 * @hide 7862 */ 7863 @Override 7864 public int installExistingPackageAsUser(String packageName, int userId) { 7865 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7866 null); 7867 PackageSetting pkgSetting; 7868 final int uid = Binder.getCallingUid(); 7869 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7870 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7871 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7872 } 7873 7874 long callingId = Binder.clearCallingIdentity(); 7875 try { 7876 boolean sendAdded = false; 7877 Bundle extras = new Bundle(1); 7878 7879 // writer 7880 synchronized (mPackages) { 7881 pkgSetting = mSettings.mPackages.get(packageName); 7882 if (pkgSetting == null) { 7883 return PackageManager.INSTALL_FAILED_INVALID_URI; 7884 } 7885 if (!pkgSetting.getInstalled(userId)) { 7886 pkgSetting.setInstalled(true, userId); 7887 pkgSetting.setBlocked(false, userId); 7888 mSettings.writePackageRestrictionsLPr(userId); 7889 sendAdded = true; 7890 } 7891 } 7892 7893 if (sendAdded) { 7894 sendPackageAddedForUser(packageName, pkgSetting, userId); 7895 } 7896 } finally { 7897 Binder.restoreCallingIdentity(callingId); 7898 } 7899 7900 return PackageManager.INSTALL_SUCCEEDED; 7901 } 7902 7903 boolean isUserRestricted(int userId, String restrictionKey) { 7904 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7905 if (restrictions.getBoolean(restrictionKey, false)) { 7906 Log.w(TAG, "User is restricted: " + restrictionKey); 7907 return true; 7908 } 7909 return false; 7910 } 7911 7912 @Override 7913 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7914 mContext.enforceCallingOrSelfPermission( 7915 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7916 "Only package verification agents can verify applications"); 7917 7918 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7919 final PackageVerificationResponse response = new PackageVerificationResponse( 7920 verificationCode, Binder.getCallingUid()); 7921 msg.arg1 = id; 7922 msg.obj = response; 7923 mHandler.sendMessage(msg); 7924 } 7925 7926 @Override 7927 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7928 long millisecondsToDelay) { 7929 mContext.enforceCallingOrSelfPermission( 7930 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7931 "Only package verification agents can extend verification timeouts"); 7932 7933 final PackageVerificationState state = mPendingVerification.get(id); 7934 final PackageVerificationResponse response = new PackageVerificationResponse( 7935 verificationCodeAtTimeout, Binder.getCallingUid()); 7936 7937 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7938 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7939 } 7940 if (millisecondsToDelay < 0) { 7941 millisecondsToDelay = 0; 7942 } 7943 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7944 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7945 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7946 } 7947 7948 if ((state != null) && !state.timeoutExtended()) { 7949 state.extendTimeout(); 7950 7951 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7952 msg.arg1 = id; 7953 msg.obj = response; 7954 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7955 } 7956 } 7957 7958 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7959 int verificationCode, UserHandle user) { 7960 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7961 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7962 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7963 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7964 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 7965 7966 mContext.sendBroadcastAsUser(intent, user, 7967 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 7968 } 7969 7970 private ComponentName matchComponentForVerifier(String packageName, 7971 List<ResolveInfo> receivers) { 7972 ActivityInfo targetReceiver = null; 7973 7974 final int NR = receivers.size(); 7975 for (int i = 0; i < NR; i++) { 7976 final ResolveInfo info = receivers.get(i); 7977 if (info.activityInfo == null) { 7978 continue; 7979 } 7980 7981 if (packageName.equals(info.activityInfo.packageName)) { 7982 targetReceiver = info.activityInfo; 7983 break; 7984 } 7985 } 7986 7987 if (targetReceiver == null) { 7988 return null; 7989 } 7990 7991 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 7992 } 7993 7994 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 7995 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 7996 if (pkgInfo.verifiers.length == 0) { 7997 return null; 7998 } 7999 8000 final int N = pkgInfo.verifiers.length; 8001 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8002 for (int i = 0; i < N; i++) { 8003 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8004 8005 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8006 receivers); 8007 if (comp == null) { 8008 continue; 8009 } 8010 8011 final int verifierUid = getUidForVerifier(verifierInfo); 8012 if (verifierUid == -1) { 8013 continue; 8014 } 8015 8016 if (DEBUG_VERIFY) { 8017 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8018 + " with the correct signature"); 8019 } 8020 sufficientVerifiers.add(comp); 8021 verificationState.addSufficientVerifier(verifierUid); 8022 } 8023 8024 return sufficientVerifiers; 8025 } 8026 8027 private int getUidForVerifier(VerifierInfo verifierInfo) { 8028 synchronized (mPackages) { 8029 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8030 if (pkg == null) { 8031 return -1; 8032 } else if (pkg.mSignatures.length != 1) { 8033 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8034 + " has more than one signature; ignoring"); 8035 return -1; 8036 } 8037 8038 /* 8039 * If the public key of the package's signature does not match 8040 * our expected public key, then this is a different package and 8041 * we should skip. 8042 */ 8043 8044 final byte[] expectedPublicKey; 8045 try { 8046 final Signature verifierSig = pkg.mSignatures[0]; 8047 final PublicKey publicKey = verifierSig.getPublicKey(); 8048 expectedPublicKey = publicKey.getEncoded(); 8049 } catch (CertificateException e) { 8050 return -1; 8051 } 8052 8053 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8054 8055 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8056 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8057 + " does not have the expected public key; ignoring"); 8058 return -1; 8059 } 8060 8061 return pkg.applicationInfo.uid; 8062 } 8063 } 8064 8065 @Override 8066 public void finishPackageInstall(int token) { 8067 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8068 8069 if (DEBUG_INSTALL) { 8070 Slog.v(TAG, "BM finishing package install for " + token); 8071 } 8072 8073 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8074 mHandler.sendMessage(msg); 8075 } 8076 8077 /** 8078 * Get the verification agent timeout. 8079 * 8080 * @return verification timeout in milliseconds 8081 */ 8082 private long getVerificationTimeout() { 8083 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8084 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8085 DEFAULT_VERIFICATION_TIMEOUT); 8086 } 8087 8088 /** 8089 * Get the default verification agent response code. 8090 * 8091 * @return default verification response code 8092 */ 8093 private int getDefaultVerificationResponse() { 8094 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8095 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8096 DEFAULT_VERIFICATION_RESPONSE); 8097 } 8098 8099 /** 8100 * Check whether or not package verification has been enabled. 8101 * 8102 * @return true if verification should be performed 8103 */ 8104 private boolean isVerificationEnabled(int userId, int flags) { 8105 if (!DEFAULT_VERIFY_ENABLE) { 8106 return false; 8107 } 8108 8109 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8110 8111 // Check if installing from ADB 8112 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8113 // Do not run verification in a test harness environment 8114 if (ActivityManager.isRunningInTestHarness()) { 8115 return false; 8116 } 8117 if (ensureVerifyAppsEnabled) { 8118 return true; 8119 } 8120 // Check if the developer does not want package verification for ADB installs 8121 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8122 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8123 return false; 8124 } 8125 } 8126 8127 if (ensureVerifyAppsEnabled) { 8128 return true; 8129 } 8130 8131 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8132 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8133 } 8134 8135 /** 8136 * Get the "allow unknown sources" setting. 8137 * 8138 * @return the current "allow unknown sources" setting 8139 */ 8140 private int getUnknownSourcesSettings() { 8141 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8142 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8143 -1); 8144 } 8145 8146 @Override 8147 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8148 final int uid = Binder.getCallingUid(); 8149 // writer 8150 synchronized (mPackages) { 8151 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8152 if (targetPackageSetting == null) { 8153 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8154 } 8155 8156 PackageSetting installerPackageSetting; 8157 if (installerPackageName != null) { 8158 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8159 if (installerPackageSetting == null) { 8160 throw new IllegalArgumentException("Unknown installer package: " 8161 + installerPackageName); 8162 } 8163 } else { 8164 installerPackageSetting = null; 8165 } 8166 8167 Signature[] callerSignature; 8168 Object obj = mSettings.getUserIdLPr(uid); 8169 if (obj != null) { 8170 if (obj instanceof SharedUserSetting) { 8171 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8172 } else if (obj instanceof PackageSetting) { 8173 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8174 } else { 8175 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8176 } 8177 } else { 8178 throw new SecurityException("Unknown calling uid " + uid); 8179 } 8180 8181 // Verify: can't set installerPackageName to a package that is 8182 // not signed with the same cert as the caller. 8183 if (installerPackageSetting != null) { 8184 if (compareSignatures(callerSignature, 8185 installerPackageSetting.signatures.mSignatures) 8186 != PackageManager.SIGNATURE_MATCH) { 8187 throw new SecurityException( 8188 "Caller does not have same cert as new installer package " 8189 + installerPackageName); 8190 } 8191 } 8192 8193 // Verify: if target already has an installer package, it must 8194 // be signed with the same cert as the caller. 8195 if (targetPackageSetting.installerPackageName != null) { 8196 PackageSetting setting = mSettings.mPackages.get( 8197 targetPackageSetting.installerPackageName); 8198 // If the currently set package isn't valid, then it's always 8199 // okay to change it. 8200 if (setting != null) { 8201 if (compareSignatures(callerSignature, 8202 setting.signatures.mSignatures) 8203 != PackageManager.SIGNATURE_MATCH) { 8204 throw new SecurityException( 8205 "Caller does not have same cert as old installer package " 8206 + targetPackageSetting.installerPackageName); 8207 } 8208 } 8209 } 8210 8211 // Okay! 8212 targetPackageSetting.installerPackageName = installerPackageName; 8213 scheduleWriteSettingsLocked(); 8214 } 8215 } 8216 8217 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8218 // Queue up an async operation since the package installation may take a little while. 8219 mHandler.post(new Runnable() { 8220 public void run() { 8221 mHandler.removeCallbacks(this); 8222 // Result object to be returned 8223 PackageInstalledInfo res = new PackageInstalledInfo(); 8224 res.returnCode = currentStatus; 8225 res.uid = -1; 8226 res.pkg = null; 8227 res.removedInfo = new PackageRemovedInfo(); 8228 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8229 args.doPreInstall(res.returnCode); 8230 synchronized (mInstallLock) { 8231 installPackageLI(args, true, res); 8232 } 8233 args.doPostInstall(res.returnCode, res.uid); 8234 } 8235 8236 // A restore should be performed at this point if (a) the install 8237 // succeeded, (b) the operation is not an update, and (c) the new 8238 // package has a backupAgent defined. 8239 final boolean update = res.removedInfo.removedPackage != null; 8240 boolean doRestore = (!update 8241 && res.pkg != null 8242 && res.pkg.applicationInfo.backupAgentName != null); 8243 8244 // Set up the post-install work request bookkeeping. This will be used 8245 // and cleaned up by the post-install event handling regardless of whether 8246 // there's a restore pass performed. Token values are >= 1. 8247 int token; 8248 if (mNextInstallToken < 0) mNextInstallToken = 1; 8249 token = mNextInstallToken++; 8250 8251 PostInstallData data = new PostInstallData(args, res); 8252 mRunningInstalls.put(token, data); 8253 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8254 8255 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8256 // Pass responsibility to the Backup Manager. It will perform a 8257 // restore if appropriate, then pass responsibility back to the 8258 // Package Manager to run the post-install observer callbacks 8259 // and broadcasts. 8260 IBackupManager bm = IBackupManager.Stub.asInterface( 8261 ServiceManager.getService(Context.BACKUP_SERVICE)); 8262 if (bm != null) { 8263 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8264 + " to BM for possible restore"); 8265 try { 8266 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8267 } catch (RemoteException e) { 8268 // can't happen; the backup manager is local 8269 } catch (Exception e) { 8270 Slog.e(TAG, "Exception trying to enqueue restore", e); 8271 doRestore = false; 8272 } 8273 } else { 8274 Slog.e(TAG, "Backup Manager not found!"); 8275 doRestore = false; 8276 } 8277 } 8278 8279 if (!doRestore) { 8280 // No restore possible, or the Backup Manager was mysteriously not 8281 // available -- just fire the post-install work request directly. 8282 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8283 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8284 mHandler.sendMessage(msg); 8285 } 8286 } 8287 }); 8288 } 8289 8290 private abstract class HandlerParams { 8291 private static final int MAX_RETRIES = 4; 8292 8293 /** 8294 * Number of times startCopy() has been attempted and had a non-fatal 8295 * error. 8296 */ 8297 private int mRetries = 0; 8298 8299 /** User handle for the user requesting the information or installation. */ 8300 private final UserHandle mUser; 8301 8302 HandlerParams(UserHandle user) { 8303 mUser = user; 8304 } 8305 8306 UserHandle getUser() { 8307 return mUser; 8308 } 8309 8310 final boolean startCopy() { 8311 boolean res; 8312 try { 8313 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8314 8315 if (++mRetries > MAX_RETRIES) { 8316 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8317 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8318 handleServiceError(); 8319 return false; 8320 } else { 8321 handleStartCopy(); 8322 res = true; 8323 } 8324 } catch (RemoteException e) { 8325 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8326 mHandler.sendEmptyMessage(MCS_RECONNECT); 8327 res = false; 8328 } 8329 handleReturnCode(); 8330 return res; 8331 } 8332 8333 final void serviceError() { 8334 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8335 handleServiceError(); 8336 handleReturnCode(); 8337 } 8338 8339 abstract void handleStartCopy() throws RemoteException; 8340 abstract void handleServiceError(); 8341 abstract void handleReturnCode(); 8342 } 8343 8344 class MeasureParams extends HandlerParams { 8345 private final PackageStats mStats; 8346 private boolean mSuccess; 8347 8348 private final IPackageStatsObserver mObserver; 8349 8350 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8351 super(new UserHandle(stats.userHandle)); 8352 mObserver = observer; 8353 mStats = stats; 8354 } 8355 8356 @Override 8357 public String toString() { 8358 return "MeasureParams{" 8359 + Integer.toHexString(System.identityHashCode(this)) 8360 + " " + mStats.packageName + "}"; 8361 } 8362 8363 @Override 8364 void handleStartCopy() throws RemoteException { 8365 synchronized (mInstallLock) { 8366 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8367 } 8368 8369 if (mSuccess) { 8370 final boolean mounted; 8371 if (Environment.isExternalStorageEmulated()) { 8372 mounted = true; 8373 } else { 8374 final String status = Environment.getExternalStorageState(); 8375 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8376 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8377 } 8378 8379 if (mounted) { 8380 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8381 8382 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8383 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8384 8385 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8386 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8387 8388 // Always subtract cache size, since it's a subdirectory 8389 mStats.externalDataSize -= mStats.externalCacheSize; 8390 8391 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8392 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8393 8394 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8395 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8396 } 8397 } 8398 } 8399 8400 @Override 8401 void handleReturnCode() { 8402 if (mObserver != null) { 8403 try { 8404 mObserver.onGetStatsCompleted(mStats, mSuccess); 8405 } catch (RemoteException e) { 8406 Slog.i(TAG, "Observer no longer exists."); 8407 } 8408 } 8409 } 8410 8411 @Override 8412 void handleServiceError() { 8413 Slog.e(TAG, "Could not measure application " + mStats.packageName 8414 + " external storage"); 8415 } 8416 } 8417 8418 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8419 throws RemoteException { 8420 long result = 0; 8421 for (File path : paths) { 8422 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8423 } 8424 return result; 8425 } 8426 8427 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8428 for (File path : paths) { 8429 try { 8430 mcs.clearDirectory(path.getAbsolutePath()); 8431 } catch (RemoteException e) { 8432 } 8433 } 8434 } 8435 8436 class InstallParams extends HandlerParams { 8437 /** 8438 * Location where install is coming from, before it has been 8439 * copied/renamed into place. This could be a single monolithic APK 8440 * file, or a cluster directory. This location may be untrusted. 8441 */ 8442 final File originFile; 8443 8444 /** 8445 * Flag indicating that {@link #originFile} lives in a trusted location, 8446 * meaning downstream users don't need to defensively copy the contents. 8447 */ 8448 boolean originTrusted; 8449 8450 final IPackageInstallObserver observer; 8451 final IPackageInstallObserver2 observer2; 8452 int flags; 8453 final String installerPackageName; 8454 final VerificationParams verificationParams; 8455 private InstallArgs mArgs; 8456 private int mRet; 8457 final String packageAbiOverride; 8458 final String packageInstructionSetOverride; 8459 8460 InstallParams(File originFile, IPackageInstallObserver observer, 8461 IPackageInstallObserver2 observer2, int flags, String installerPackageName, 8462 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 8463 super(user); 8464 this.originFile = Preconditions.checkNotNull(originFile); 8465 this.originTrusted = false; 8466 this.observer = observer; 8467 this.observer2 = observer2; 8468 this.flags = flags; 8469 this.installerPackageName = installerPackageName; 8470 this.verificationParams = verificationParams; 8471 this.packageAbiOverride = packageAbiOverride; 8472 this.packageInstructionSetOverride = (packageAbiOverride == null) ? 8473 packageAbiOverride : VMRuntime.getInstructionSet(packageAbiOverride); 8474 } 8475 8476 @Override 8477 public String toString() { 8478 return "InstallParams{" 8479 + Integer.toHexString(System.identityHashCode(this)) 8480 + " " + originFile + "}"; 8481 } 8482 8483 public ManifestDigest getManifestDigest() { 8484 if (verificationParams == null) { 8485 return null; 8486 } 8487 return verificationParams.getManifestDigest(); 8488 } 8489 8490 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8491 String packageName = pkgLite.packageName; 8492 int installLocation = pkgLite.installLocation; 8493 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8494 // reader 8495 synchronized (mPackages) { 8496 PackageParser.Package pkg = mPackages.get(packageName); 8497 if (pkg != null) { 8498 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8499 // Check for downgrading. 8500 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8501 if (pkgLite.versionCode < pkg.mVersionCode) { 8502 Slog.w(TAG, "Can't install update of " + packageName 8503 + " update version " + pkgLite.versionCode 8504 + " is older than installed version " 8505 + pkg.mVersionCode); 8506 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8507 } 8508 } 8509 // Check for updated system application. 8510 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8511 if (onSd) { 8512 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8513 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8514 } 8515 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8516 } else { 8517 if (onSd) { 8518 // Install flag overrides everything. 8519 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8520 } 8521 // If current upgrade specifies particular preference 8522 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8523 // Application explicitly specified internal. 8524 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8525 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8526 // App explictly prefers external. Let policy decide 8527 } else { 8528 // Prefer previous location 8529 if (isExternal(pkg)) { 8530 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8531 } 8532 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8533 } 8534 } 8535 } else { 8536 // Invalid install. Return error code 8537 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8538 } 8539 } 8540 } 8541 // All the special cases have been taken care of. 8542 // Return result based on recommended install location. 8543 if (onSd) { 8544 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8545 } 8546 return pkgLite.recommendedInstallLocation; 8547 } 8548 8549 private long getMemoryLowThreshold() { 8550 final DeviceStorageMonitorInternal 8551 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8552 if (dsm == null) { 8553 return 0L; 8554 } 8555 return dsm.getMemoryLowThreshold(); 8556 } 8557 8558 /* 8559 * Invoke remote method to get package information and install 8560 * location values. Override install location based on default 8561 * policy if needed and then create install arguments based 8562 * on the install location. 8563 */ 8564 public void handleStartCopy() throws RemoteException { 8565 int ret = PackageManager.INSTALL_SUCCEEDED; 8566 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8567 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8568 PackageInfoLite pkgLite = null; 8569 8570 if (onInt && onSd) { 8571 // Check if both bits are set. 8572 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8573 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8574 } else { 8575 final long lowThreshold = getMemoryLowThreshold(); 8576 if (lowThreshold == 0L) { 8577 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8578 } 8579 8580 // Remote call to find out default install location 8581 final String originPath = originFile.getAbsolutePath(); 8582 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold, 8583 packageAbiOverride); 8584 8585 /* 8586 * If we have too little free space, try to free cache 8587 * before giving up. 8588 */ 8589 if (pkgLite.recommendedInstallLocation 8590 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8591 final long size = mContainerService.calculateInstalledSize( 8592 originPath, isForwardLocked(), packageAbiOverride); 8593 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8594 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, 8595 lowThreshold, packageAbiOverride); 8596 } 8597 /* 8598 * The cache free must have deleted the file we 8599 * downloaded to install. 8600 * 8601 * TODO: fix the "freeCache" call to not delete 8602 * the file we care about. 8603 */ 8604 if (pkgLite.recommendedInstallLocation 8605 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8606 pkgLite.recommendedInstallLocation 8607 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8608 } 8609 } 8610 } 8611 8612 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8613 int loc = pkgLite.recommendedInstallLocation; 8614 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8615 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8616 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8617 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8618 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8619 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8620 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8621 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8622 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8623 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8624 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8625 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8626 } else { 8627 // Override with defaults if needed. 8628 loc = installLocationPolicy(pkgLite, flags); 8629 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8630 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8631 } else if (!onSd && !onInt) { 8632 // Override install location with flags 8633 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8634 // Set the flag to install on external media. 8635 flags |= PackageManager.INSTALL_EXTERNAL; 8636 flags &= ~PackageManager.INSTALL_INTERNAL; 8637 } else { 8638 // Make sure the flag for installing on external 8639 // media is unset 8640 flags |= PackageManager.INSTALL_INTERNAL; 8641 flags &= ~PackageManager.INSTALL_EXTERNAL; 8642 } 8643 } 8644 } 8645 } 8646 8647 final InstallArgs args = createInstallArgs(this); 8648 mArgs = args; 8649 8650 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8651 /* 8652 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8653 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8654 */ 8655 int userIdentifier = getUser().getIdentifier(); 8656 if (userIdentifier == UserHandle.USER_ALL 8657 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8658 userIdentifier = UserHandle.USER_OWNER; 8659 } 8660 8661 /* 8662 * Determine if we have any installed package verifiers. If we 8663 * do, then we'll defer to them to verify the packages. 8664 */ 8665 final int requiredUid = mRequiredVerifierPackage == null ? -1 8666 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8667 if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) { 8668 // TODO: send verifier the install session instead of uri 8669 final Intent verification = new Intent( 8670 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8671 verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE); 8672 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8673 8674 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8675 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8676 0 /* TODO: Which userId? */); 8677 8678 if (DEBUG_VERIFY) { 8679 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8680 + verification.toString() + " with " + pkgLite.verifiers.length 8681 + " optional verifiers"); 8682 } 8683 8684 final int verificationId = mPendingVerificationToken++; 8685 8686 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8687 8688 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8689 installerPackageName); 8690 8691 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8692 8693 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8694 pkgLite.packageName); 8695 8696 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8697 pkgLite.versionCode); 8698 8699 if (verificationParams != null) { 8700 if (verificationParams.getVerificationURI() != null) { 8701 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8702 verificationParams.getVerificationURI()); 8703 } 8704 if (verificationParams.getOriginatingURI() != null) { 8705 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8706 verificationParams.getOriginatingURI()); 8707 } 8708 if (verificationParams.getReferrer() != null) { 8709 verification.putExtra(Intent.EXTRA_REFERRER, 8710 verificationParams.getReferrer()); 8711 } 8712 if (verificationParams.getOriginatingUid() >= 0) { 8713 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8714 verificationParams.getOriginatingUid()); 8715 } 8716 if (verificationParams.getInstallerUid() >= 0) { 8717 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8718 verificationParams.getInstallerUid()); 8719 } 8720 } 8721 8722 final PackageVerificationState verificationState = new PackageVerificationState( 8723 requiredUid, args); 8724 8725 mPendingVerification.append(verificationId, verificationState); 8726 8727 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8728 receivers, verificationState); 8729 8730 /* 8731 * If any sufficient verifiers were listed in the package 8732 * manifest, attempt to ask them. 8733 */ 8734 if (sufficientVerifiers != null) { 8735 final int N = sufficientVerifiers.size(); 8736 if (N == 0) { 8737 Slog.i(TAG, "Additional verifiers required, but none installed."); 8738 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8739 } else { 8740 for (int i = 0; i < N; i++) { 8741 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8742 8743 final Intent sufficientIntent = new Intent(verification); 8744 sufficientIntent.setComponent(verifierComponent); 8745 8746 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8747 } 8748 } 8749 } 8750 8751 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8752 mRequiredVerifierPackage, receivers); 8753 if (ret == PackageManager.INSTALL_SUCCEEDED 8754 && mRequiredVerifierPackage != null) { 8755 /* 8756 * Send the intent to the required verification agent, 8757 * but only start the verification timeout after the 8758 * target BroadcastReceivers have run. 8759 */ 8760 verification.setComponent(requiredVerifierComponent); 8761 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8762 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8763 new BroadcastReceiver() { 8764 @Override 8765 public void onReceive(Context context, Intent intent) { 8766 final Message msg = mHandler 8767 .obtainMessage(CHECK_PENDING_VERIFICATION); 8768 msg.arg1 = verificationId; 8769 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8770 } 8771 }, null, 0, null, null); 8772 8773 /* 8774 * We don't want the copy to proceed until verification 8775 * succeeds, so null out this field. 8776 */ 8777 mArgs = null; 8778 } 8779 } else { 8780 /* 8781 * No package verification is enabled, so immediately start 8782 * the remote call to initiate copy using temporary file. 8783 */ 8784 ret = args.copyApk(mContainerService, true); 8785 } 8786 } 8787 8788 mRet = ret; 8789 } 8790 8791 @Override 8792 void handleReturnCode() { 8793 // If mArgs is null, then MCS couldn't be reached. When it 8794 // reconnects, it will try again to install. At that point, this 8795 // will succeed. 8796 if (mArgs != null) { 8797 processPendingInstall(mArgs, mRet); 8798 } 8799 } 8800 8801 @Override 8802 void handleServiceError() { 8803 mArgs = createInstallArgs(this); 8804 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8805 } 8806 8807 public boolean isForwardLocked() { 8808 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8809 } 8810 } 8811 8812 /* 8813 * Utility class used in movePackage api. 8814 * srcArgs and targetArgs are not set for invalid flags and make 8815 * sure to do null checks when invoking methods on them. 8816 * We probably want to return ErrorPrams for both failed installs 8817 * and moves. 8818 */ 8819 class MoveParams extends HandlerParams { 8820 final IPackageMoveObserver observer; 8821 final int flags; 8822 final String packageName; 8823 final InstallArgs srcArgs; 8824 final InstallArgs targetArgs; 8825 int uid; 8826 int mRet; 8827 8828 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8829 String packageName, String instructionSet, int uid, UserHandle user) { 8830 super(user); 8831 this.srcArgs = srcArgs; 8832 this.observer = observer; 8833 this.flags = flags; 8834 this.packageName = packageName; 8835 this.uid = uid; 8836 if (srcArgs != null) { 8837 final String codePath = srcArgs.getCodePath(); 8838 targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, 8839 instructionSet); 8840 } else { 8841 targetArgs = null; 8842 } 8843 } 8844 8845 @Override 8846 public String toString() { 8847 return "MoveParams{" 8848 + Integer.toHexString(System.identityHashCode(this)) 8849 + " " + packageName + "}"; 8850 } 8851 8852 public void handleStartCopy() throws RemoteException { 8853 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8854 // Check for storage space on target medium 8855 if (!targetArgs.checkFreeStorage(mContainerService)) { 8856 Log.w(TAG, "Insufficient storage to install"); 8857 return; 8858 } 8859 8860 mRet = srcArgs.doPreCopy(); 8861 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8862 return; 8863 } 8864 8865 mRet = targetArgs.copyApk(mContainerService, false); 8866 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8867 srcArgs.doPostCopy(uid); 8868 return; 8869 } 8870 8871 mRet = srcArgs.doPostCopy(uid); 8872 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8873 return; 8874 } 8875 8876 mRet = targetArgs.doPreInstall(mRet); 8877 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8878 return; 8879 } 8880 8881 if (DEBUG_SD_INSTALL) { 8882 StringBuilder builder = new StringBuilder(); 8883 if (srcArgs != null) { 8884 builder.append("src: "); 8885 builder.append(srcArgs.getCodePath()); 8886 } 8887 if (targetArgs != null) { 8888 builder.append(" target : "); 8889 builder.append(targetArgs.getCodePath()); 8890 } 8891 Log.i(TAG, builder.toString()); 8892 } 8893 } 8894 8895 @Override 8896 void handleReturnCode() { 8897 targetArgs.doPostInstall(mRet, uid); 8898 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8899 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8900 currentStatus = PackageManager.MOVE_SUCCEEDED; 8901 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8902 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8903 } 8904 processPendingMove(this, currentStatus); 8905 } 8906 8907 @Override 8908 void handleServiceError() { 8909 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8910 } 8911 } 8912 8913 /** 8914 * Used during creation of InstallArgs 8915 * 8916 * @param flags package installation flags 8917 * @return true if should be installed on external storage 8918 */ 8919 private static boolean installOnSd(int flags) { 8920 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8921 return false; 8922 } 8923 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8924 return true; 8925 } 8926 return false; 8927 } 8928 8929 /** 8930 * Used during creation of InstallArgs 8931 * 8932 * @param flags package installation flags 8933 * @return true if should be installed as forward locked 8934 */ 8935 private static boolean installForwardLocked(int flags) { 8936 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8937 } 8938 8939 private InstallArgs createInstallArgs(InstallParams params) { 8940 // TODO: extend to support incoming zero-copy locations 8941 8942 if (installOnSd(params.flags) || params.isForwardLocked()) { 8943 return new AsecInstallArgs(params); 8944 } else { 8945 return new FileInstallArgs(params); 8946 } 8947 } 8948 8949 /** 8950 * Create args that describe an existing installed package. Typically used 8951 * when cleaning up old installs, or used as a move source. 8952 */ 8953 private InstallArgs createInstallArgsForExisting(int flags, String codePath, 8954 String resourcePath, String nativeLibraryPath, String instructionSet) { 8955 final boolean isInAsec; 8956 if (installOnSd(flags)) { 8957 /* Apps on SD card are always in ASEC containers. */ 8958 isInAsec = true; 8959 } else if (installForwardLocked(flags) 8960 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8961 /* 8962 * Forward-locked apps are only in ASEC containers if they're the 8963 * new style 8964 */ 8965 isInAsec = true; 8966 } else { 8967 isInAsec = false; 8968 } 8969 8970 if (isInAsec) { 8971 return new AsecInstallArgs(codePath, resourcePath, nativeLibraryPath, 8972 instructionSet, installOnSd(flags), installForwardLocked(flags)); 8973 } else { 8974 return new FileInstallArgs(codePath, resourcePath, nativeLibraryPath, instructionSet); 8975 } 8976 } 8977 8978 private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName, 8979 String instructionSet) { 8980 final File codeFile = new File(codePath); 8981 if (installOnSd(flags) || installForwardLocked(flags)) { 8982 String cid = getNextCodePath(codePath, pkgName, "/" 8983 + AsecInstallArgs.RES_FILE_NAME); 8984 return new AsecInstallArgs(codeFile, cid, instructionSet, installOnSd(flags), 8985 installForwardLocked(flags)); 8986 } else { 8987 return new FileInstallArgs(codeFile, instructionSet); 8988 } 8989 } 8990 8991 static abstract class InstallArgs { 8992 /** @see InstallParams#originFile */ 8993 final File originFile; 8994 /** @see InstallParams#originTrusted */ 8995 final boolean originTrusted; 8996 8997 // TODO: define inherit location 8998 8999 final IPackageInstallObserver observer; 9000 final IPackageInstallObserver2 observer2; 9001 // Always refers to PackageManager flags only 9002 final int flags; 9003 final String installerPackageName; 9004 final ManifestDigest manifestDigest; 9005 final UserHandle user; 9006 final String instructionSet; 9007 final String abiOverride; 9008 9009 InstallArgs(File originFile, boolean originTrusted, IPackageInstallObserver observer, 9010 IPackageInstallObserver2 observer2, int flags, String installerPackageName, 9011 ManifestDigest manifestDigest, UserHandle user, String instructionSet, 9012 String abiOverride) { 9013 this.originFile = originFile; 9014 this.originTrusted = originTrusted; 9015 this.flags = flags; 9016 this.observer = observer; 9017 this.observer2 = observer2; 9018 this.installerPackageName = installerPackageName; 9019 this.manifestDigest = manifestDigest; 9020 this.user = user; 9021 this.instructionSet = instructionSet; 9022 this.abiOverride = abiOverride; 9023 } 9024 9025 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9026 abstract int doPreInstall(int status); 9027 9028 /** 9029 * Rename package into final resting place. All paths on the given 9030 * scanned package should be updated to reflect the rename. 9031 */ 9032 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9033 abstract int doPostInstall(int status, int uid); 9034 9035 /** @see PackageSettingBase#codePathString */ 9036 abstract String getCodePath(); 9037 /** @see PackageSettingBase#resourcePathString */ 9038 abstract String getResourcePath(); 9039 /** @see PackageSettingBase#nativeLibraryPathString */ 9040 abstract String getNativeLibraryPath(); 9041 9042 // Need installer lock especially for dex file removal. 9043 abstract void cleanUpResourcesLI(); 9044 abstract boolean doPostDeleteLI(boolean delete); 9045 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9046 9047 /** 9048 * Called before the source arguments are copied. This is used mostly 9049 * for MoveParams when it needs to read the source file to put it in the 9050 * destination. 9051 */ 9052 int doPreCopy() { 9053 return PackageManager.INSTALL_SUCCEEDED; 9054 } 9055 9056 /** 9057 * Called after the source arguments are copied. This is used mostly for 9058 * MoveParams when it needs to read the source file to put it in the 9059 * destination. 9060 * 9061 * @return 9062 */ 9063 int doPostCopy(int uid) { 9064 return PackageManager.INSTALL_SUCCEEDED; 9065 } 9066 9067 protected boolean isFwdLocked() { 9068 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9069 } 9070 9071 UserHandle getUser() { 9072 return user; 9073 } 9074 } 9075 9076 /** 9077 * Logic to handle installation of non-ASEC applications, including copying 9078 * and renaming logic. 9079 */ 9080 class FileInstallArgs extends InstallArgs { 9081 private File codeFile; 9082 private File resourceFile; 9083 private File nativeLibraryFile; 9084 9085 // Example topology: 9086 // /data/app/com.example/base.apk 9087 // /data/app/com.example/split_foo.apk 9088 // /data/app/com.example/native/arm/libfoo.so 9089 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9090 9091 /** New install */ 9092 FileInstallArgs(InstallParams params) { 9093 super(params.originFile, params.originTrusted, params.observer, params.observer2, 9094 params.flags, params.installerPackageName, params.getManifestDigest(), 9095 params.getUser(), params.packageInstructionSetOverride, 9096 params.packageAbiOverride); 9097 if (isFwdLocked()) { 9098 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9099 } 9100 } 9101 9102 /** Existing install */ 9103 FileInstallArgs(String codePath, String resourcePath, String nativeLibraryPath, 9104 String instructionSet) { 9105 super(null, false, null, null, 0, null, null, null, instructionSet, null); 9106 this.codeFile = (codePath != null) ? new File(codePath) : null; 9107 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9108 this.nativeLibraryFile = (nativeLibraryPath != null) ? new File(nativeLibraryPath) : null; 9109 } 9110 9111 /** New install from existing */ 9112 FileInstallArgs(File originFile, String instructionSet) { 9113 super(originFile, true, null, null, 0, null, null, null, instructionSet, null); 9114 } 9115 9116 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9117 final long lowThreshold; 9118 9119 final DeviceStorageMonitorInternal 9120 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9121 if (dsm == null) { 9122 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9123 lowThreshold = 0L; 9124 } else { 9125 if (dsm.isMemoryLow()) { 9126 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9127 return false; 9128 } 9129 9130 lowThreshold = dsm.getMemoryLowThreshold(); 9131 } 9132 9133 return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9134 lowThreshold); 9135 } 9136 9137 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9138 try { 9139 final File tempDir = createTempPackageDir(mAppInstallDir); 9140 codeFile = tempDir; 9141 resourceFile = tempDir; 9142 } catch (IOException e) { 9143 Slog.w(TAG, "Failed to create copy file: " + e); 9144 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9145 } 9146 9147 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9148 @Override 9149 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9150 if (!FileUtils.isValidExtFilename(name)) { 9151 throw new IllegalArgumentException("Invalid filename: " + name); 9152 } 9153 try { 9154 final File file = new File(codeFile, name); 9155 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9156 O_RDWR | O_CREAT, 0644); 9157 Os.chmod(file.getAbsolutePath(), 0644); 9158 return new ParcelFileDescriptor(fd); 9159 } catch (ErrnoException e) { 9160 throw new RemoteException("Failed to open: " + e.getMessage()); 9161 } 9162 } 9163 }; 9164 9165 int ret = imcs.copyPackage(originFile.getAbsolutePath(), target); 9166 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9167 Slog.e(TAG, "Failed to copy package"); 9168 return ret; 9169 } 9170 9171 String[] abiList = (abiOverride != null) ? 9172 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 9173 NativeLibraryHelper.Handle handle = null; 9174 try { 9175 handle = NativeLibraryHelper.Handle.create(codeFile); 9176 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && 9177 abiOverride == null && 9178 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9179 abiList = Build.SUPPORTED_32_BIT_ABIS; 9180 } 9181 9182 // TODO: refactor to avoid double findSupportedAbi() 9183 final int abiIndex = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9184 if (abiIndex < 0 && abiIndex != PackageManager.NO_NATIVE_LIBRARIES) { 9185 return abiIndex; 9186 } else if (abiIndex >= 0) { 9187 final File baseLibFile = new File(codeFile, LIB_DIR_NAME); 9188 baseLibFile.mkdir(); 9189 Os.chmod(baseLibFile.getAbsolutePath(), 0755); 9190 9191 final String abi = Build.SUPPORTED_ABIS[abiIndex]; 9192 final String instructionSet = VMRuntime.getInstructionSet(abi); 9193 nativeLibraryFile = new File(baseLibFile, instructionSet); 9194 nativeLibraryFile.mkdir(); 9195 Os.chmod(nativeLibraryFile.getAbsolutePath(), 0755); 9196 9197 copyNativeLibrariesForInternalApp(handle, nativeLibraryFile, abiList); 9198 } 9199 } catch (IOException | ErrnoException e) { 9200 Slog.e(TAG, "Copying native libraries failed", e); 9201 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9202 } finally { 9203 IoUtils.closeQuietly(handle); 9204 } 9205 9206 return ret; 9207 } 9208 9209 int doPreInstall(int status) { 9210 if (status != PackageManager.INSTALL_SUCCEEDED) { 9211 cleanUp(); 9212 } 9213 return status; 9214 } 9215 9216 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9217 if (status != PackageManager.INSTALL_SUCCEEDED) { 9218 cleanUp(); 9219 return false; 9220 } else { 9221 final File beforeCodeFile = codeFile; 9222 final File afterCodeFile = new File(mAppInstallDir, 9223 getNextCodePath(oldCodePath, pkg.packageName, null)); 9224 9225 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9226 if (!beforeCodeFile.renameTo(afterCodeFile)) { 9227 return false; 9228 } 9229 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9230 return false; 9231 } 9232 9233 // Reflect the rename internally 9234 codeFile = afterCodeFile; 9235 resourceFile = afterCodeFile; 9236 nativeLibraryFile = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9237 nativeLibraryFile); 9238 9239 // Reflect the rename in scanned details 9240 pkg.codePath = afterCodeFile.getAbsolutePath(); 9241 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9242 pkg.baseCodePath); 9243 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9244 pkg.splitCodePaths); 9245 9246 // Reflect the rename in app info 9247 pkg.applicationInfo.setCodePath(pkg.codePath); 9248 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9249 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9250 pkg.applicationInfo.setResourcePath(pkg.codePath); 9251 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9252 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9253 pkg.applicationInfo.nativeLibraryDir = getNativeLibraryPath(); 9254 9255 return true; 9256 } 9257 } 9258 9259 int doPostInstall(int status, int uid) { 9260 if (status != PackageManager.INSTALL_SUCCEEDED) { 9261 cleanUp(); 9262 } 9263 return status; 9264 } 9265 9266 @Override 9267 String getCodePath() { 9268 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9269 } 9270 9271 @Override 9272 String getResourcePath() { 9273 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9274 } 9275 9276 @Override 9277 String getNativeLibraryPath() { 9278 return (nativeLibraryFile != null) ? nativeLibraryFile.getAbsolutePath() : null; 9279 } 9280 9281 private boolean cleanUp() { 9282 if (codeFile == null || !codeFile.exists()) { 9283 return false; 9284 } 9285 9286 if (codeFile.isDirectory()) { 9287 FileUtils.deleteContents(codeFile); 9288 } 9289 codeFile.delete(); 9290 9291 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9292 resourceFile.delete(); 9293 } 9294 9295 if (nativeLibraryFile != null && !FileUtils.contains(codeFile, nativeLibraryFile)) { 9296 FileUtils.deleteContents(nativeLibraryFile); 9297 nativeLibraryFile.delete(); 9298 } 9299 9300 return true; 9301 } 9302 9303 void cleanUpResourcesLI() { 9304 // Try enumerating all code paths before deleting 9305 List<String> allCodePaths = Collections.EMPTY_LIST; 9306 if (codeFile != null && codeFile.exists()) { 9307 try { 9308 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9309 allCodePaths = pkg.getAllCodePaths(); 9310 } catch (PackageParserException e) { 9311 // Ignored; we tried our best 9312 } 9313 } 9314 9315 cleanUp(); 9316 9317 if (!allCodePaths.isEmpty()) { 9318 if (instructionSet == null) { 9319 throw new IllegalStateException("instructionSet == null"); 9320 } 9321 9322 for (String codePath : allCodePaths) { 9323 int retCode = mInstaller.rmdex(codePath, instructionSet); 9324 if (retCode < 0) { 9325 Slog.w(TAG, "Couldn't remove dex file for package: " 9326 + " at location " + codePath + ", retcode=" + retCode); 9327 // we don't consider this to be a failure of the core package deletion 9328 } 9329 } 9330 } 9331 } 9332 9333 boolean doPostDeleteLI(boolean delete) { 9334 // XXX err, shouldn't we respect the delete flag? 9335 cleanUpResourcesLI(); 9336 return true; 9337 } 9338 } 9339 9340 private boolean isAsecExternal(String cid) { 9341 final String asecPath = PackageHelper.getSdFilesystem(cid); 9342 return !asecPath.startsWith(mAsecInternalPath); 9343 } 9344 9345 /** 9346 * Extract the MountService "container ID" from the full code path of an 9347 * .apk. 9348 */ 9349 static String cidFromCodePath(String fullCodePath) { 9350 int eidx = fullCodePath.lastIndexOf("/"); 9351 String subStr1 = fullCodePath.substring(0, eidx); 9352 int sidx = subStr1.lastIndexOf("/"); 9353 return subStr1.substring(sidx+1, eidx); 9354 } 9355 9356 /** 9357 * Logic to handle installation of ASEC applications, including copying and 9358 * renaming logic. 9359 */ 9360 class AsecInstallArgs extends InstallArgs { 9361 // TODO: teach about handling cluster directories 9362 9363 static final String RES_FILE_NAME = "pkg.apk"; 9364 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9365 9366 String cid; 9367 String packagePath; 9368 String resourcePath; 9369 String libraryPath; 9370 9371 /** New install */ 9372 AsecInstallArgs(InstallParams params) { 9373 super(params.originFile, params.originTrusted, params.observer, params.observer2, 9374 params.flags, params.installerPackageName, params.getManifestDigest(), 9375 params.getUser(), params.packageInstructionSetOverride, 9376 params.packageAbiOverride); 9377 } 9378 9379 /** Existing install */ 9380 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 9381 String instructionSet, boolean isExternal, boolean isForwardLocked) { 9382 super(null, false, null, null, (isExternal ? INSTALL_EXTERNAL : 0) 9383 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9384 instructionSet, null); 9385 // Extract cid from fullCodePath 9386 int eidx = fullCodePath.lastIndexOf("/"); 9387 String subStr1 = fullCodePath.substring(0, eidx); 9388 int sidx = subStr1.lastIndexOf("/"); 9389 cid = subStr1.substring(sidx+1, eidx); 9390 setCachePath(subStr1); 9391 } 9392 9393 AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) { 9394 super(null, false, null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9395 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9396 instructionSet, null); 9397 this.cid = cid; 9398 setCachePath(PackageHelper.getSdDir(cid)); 9399 } 9400 9401 /** New install from existing */ 9402 AsecInstallArgs(File originPackageFile, String cid, String instructionSet, 9403 boolean isExternal, boolean isForwardLocked) { 9404 super(originPackageFile, true, null, null, (isExternal ? INSTALL_EXTERNAL : 0) 9405 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9406 instructionSet, null); 9407 this.cid = cid; 9408 } 9409 9410 void createCopyFile() { 9411 cid = getTempContainerId(); 9412 } 9413 9414 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9415 return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9416 abiOverride); 9417 } 9418 9419 private final boolean isExternal() { 9420 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9421 } 9422 9423 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9424 if (temp) { 9425 createCopyFile(); 9426 } else { 9427 /* 9428 * Pre-emptively destroy the container since it's destroyed if 9429 * copying fails due to it existing anyway. 9430 */ 9431 PackageHelper.destroySdDir(cid); 9432 } 9433 9434 final String newCachePath = imcs.copyPackageToContainer( 9435 originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9436 isFwdLocked(), abiOverride); 9437 9438 if (newCachePath != null) { 9439 setCachePath(newCachePath); 9440 return PackageManager.INSTALL_SUCCEEDED; 9441 } else { 9442 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9443 } 9444 } 9445 9446 @Override 9447 String getCodePath() { 9448 return packagePath; 9449 } 9450 9451 @Override 9452 String getResourcePath() { 9453 return resourcePath; 9454 } 9455 9456 @Override 9457 String getNativeLibraryPath() { 9458 return libraryPath; 9459 } 9460 9461 int doPreInstall(int status) { 9462 if (status != PackageManager.INSTALL_SUCCEEDED) { 9463 // Destroy container 9464 PackageHelper.destroySdDir(cid); 9465 } else { 9466 boolean mounted = PackageHelper.isContainerMounted(cid); 9467 if (!mounted) { 9468 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9469 Process.SYSTEM_UID); 9470 if (newCachePath != null) { 9471 setCachePath(newCachePath); 9472 } else { 9473 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9474 } 9475 } 9476 } 9477 return status; 9478 } 9479 9480 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9481 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9482 String newCachePath = null; 9483 if (PackageHelper.isContainerMounted(cid)) { 9484 // Unmount the container 9485 if (!PackageHelper.unMountSdDir(cid)) { 9486 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9487 return false; 9488 } 9489 } 9490 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9491 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9492 " which might be stale. Will try to clean up."); 9493 // Clean up the stale container and proceed to recreate. 9494 if (!PackageHelper.destroySdDir(newCacheId)) { 9495 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9496 return false; 9497 } 9498 // Successfully cleaned up stale container. Try to rename again. 9499 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9500 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9501 + " inspite of cleaning it up."); 9502 return false; 9503 } 9504 } 9505 if (!PackageHelper.isContainerMounted(newCacheId)) { 9506 Slog.w(TAG, "Mounting container " + newCacheId); 9507 newCachePath = PackageHelper.mountSdDir(newCacheId, 9508 getEncryptKey(), Process.SYSTEM_UID); 9509 } else { 9510 newCachePath = PackageHelper.getSdDir(newCacheId); 9511 } 9512 if (newCachePath == null) { 9513 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9514 return false; 9515 } 9516 Log.i(TAG, "Succesfully renamed " + cid + 9517 " to " + newCacheId + 9518 " at new path: " + newCachePath); 9519 cid = newCacheId; 9520 setCachePath(newCachePath); 9521 9522 // TODO: extend to support split APKs 9523 pkg.codePath = getCodePath(); 9524 pkg.baseCodePath = getCodePath(); 9525 pkg.splitCodePaths = null; 9526 9527 pkg.applicationInfo.setCodePath(getCodePath()); 9528 pkg.applicationInfo.setBaseCodePath(getCodePath()); 9529 pkg.applicationInfo.setSplitCodePaths(null); 9530 pkg.applicationInfo.setResourcePath(getResourcePath()); 9531 pkg.applicationInfo.setBaseResourcePath(getResourcePath()); 9532 pkg.applicationInfo.setSplitResourcePaths(null); 9533 pkg.applicationInfo.nativeLibraryDir = getNativeLibraryPath(); 9534 9535 return true; 9536 } 9537 9538 private void setCachePath(String newCachePath) { 9539 File cachePath = new File(newCachePath); 9540 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath(); 9541 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9542 9543 if (isFwdLocked()) { 9544 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9545 } else { 9546 resourcePath = packagePath; 9547 } 9548 } 9549 9550 int doPostInstall(int status, int uid) { 9551 if (status != PackageManager.INSTALL_SUCCEEDED) { 9552 cleanUp(); 9553 } else { 9554 final int groupOwner; 9555 final String protectedFile; 9556 if (isFwdLocked()) { 9557 groupOwner = UserHandle.getSharedAppGid(uid); 9558 protectedFile = RES_FILE_NAME; 9559 } else { 9560 groupOwner = -1; 9561 protectedFile = null; 9562 } 9563 9564 if (uid < Process.FIRST_APPLICATION_UID 9565 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9566 Slog.e(TAG, "Failed to finalize " + cid); 9567 PackageHelper.destroySdDir(cid); 9568 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9569 } 9570 9571 boolean mounted = PackageHelper.isContainerMounted(cid); 9572 if (!mounted) { 9573 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9574 } 9575 } 9576 return status; 9577 } 9578 9579 private void cleanUp() { 9580 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9581 9582 // Destroy secure container 9583 PackageHelper.destroySdDir(cid); 9584 } 9585 9586 void cleanUpResourcesLI() { 9587 String sourceFile = getCodePath(); 9588 // Remove dex file 9589 if (instructionSet == null) { 9590 throw new IllegalStateException("instructionSet == null"); 9591 } 9592 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9593 if (retCode < 0) { 9594 Slog.w(TAG, "Couldn't remove dex file for package: " 9595 + " at location " 9596 + sourceFile.toString() + ", retcode=" + retCode); 9597 // we don't consider this to be a failure of the core package deletion 9598 } 9599 cleanUp(); 9600 } 9601 9602 boolean matchContainer(String app) { 9603 if (cid.startsWith(app)) { 9604 return true; 9605 } 9606 return false; 9607 } 9608 9609 String getPackageName() { 9610 return getAsecPackageName(cid); 9611 } 9612 9613 boolean doPostDeleteLI(boolean delete) { 9614 boolean ret = false; 9615 boolean mounted = PackageHelper.isContainerMounted(cid); 9616 if (mounted) { 9617 // Unmount first 9618 ret = PackageHelper.unMountSdDir(cid); 9619 } 9620 if (ret && delete) { 9621 cleanUpResourcesLI(); 9622 } 9623 return ret; 9624 } 9625 9626 @Override 9627 int doPreCopy() { 9628 if (isFwdLocked()) { 9629 if (!PackageHelper.fixSdPermissions(cid, 9630 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9631 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9632 } 9633 } 9634 9635 return PackageManager.INSTALL_SUCCEEDED; 9636 } 9637 9638 @Override 9639 int doPostCopy(int uid) { 9640 if (isFwdLocked()) { 9641 if (uid < Process.FIRST_APPLICATION_UID 9642 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9643 RES_FILE_NAME)) { 9644 Slog.e(TAG, "Failed to finalize " + cid); 9645 PackageHelper.destroySdDir(cid); 9646 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9647 } 9648 } 9649 9650 return PackageManager.INSTALL_SUCCEEDED; 9651 } 9652 } 9653 9654 static String getAsecPackageName(String packageCid) { 9655 int idx = packageCid.lastIndexOf("-"); 9656 if (idx == -1) { 9657 return packageCid; 9658 } 9659 return packageCid.substring(0, idx); 9660 } 9661 9662 // Utility method used to create code paths based on package name and available index. 9663 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9664 String idxStr = ""; 9665 int idx = 1; 9666 // Fall back to default value of idx=1 if prefix is not 9667 // part of oldCodePath 9668 if (oldCodePath != null) { 9669 String subStr = oldCodePath; 9670 // Drop the suffix right away 9671 if (suffix != null && subStr.endsWith(suffix)) { 9672 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9673 } 9674 // If oldCodePath already contains prefix find out the 9675 // ending index to either increment or decrement. 9676 int sidx = subStr.lastIndexOf(prefix); 9677 if (sidx != -1) { 9678 subStr = subStr.substring(sidx + prefix.length()); 9679 if (subStr != null) { 9680 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9681 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9682 } 9683 try { 9684 idx = Integer.parseInt(subStr); 9685 if (idx <= 1) { 9686 idx++; 9687 } else { 9688 idx--; 9689 } 9690 } catch(NumberFormatException e) { 9691 } 9692 } 9693 } 9694 } 9695 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9696 return prefix + idxStr; 9697 } 9698 9699 // Utility method used to ignore ADD/REMOVE events 9700 // by directory observer. 9701 private static boolean ignoreCodePath(String fullPathStr) { 9702 String apkName = deriveCodePathName(fullPathStr); 9703 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9704 if (idx != -1 && ((idx+1) < apkName.length())) { 9705 // Make sure the package ends with a numeral 9706 String version = apkName.substring(idx+1); 9707 try { 9708 Integer.parseInt(version); 9709 return true; 9710 } catch (NumberFormatException e) {} 9711 } 9712 return false; 9713 } 9714 9715 // Utility method that returns the relative package path with respect 9716 // to the installation directory. Like say for /data/data/com.test-1.apk 9717 // string com.test-1 is returned. 9718 static String deriveCodePathName(String codePath) { 9719 if (codePath == null) { 9720 return null; 9721 } 9722 final File codeFile = new File(codePath); 9723 final String name = codeFile.getName(); 9724 if (codeFile.isDirectory()) { 9725 return name; 9726 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9727 final int lastDot = name.lastIndexOf('.'); 9728 return name.substring(0, lastDot); 9729 } else { 9730 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9731 return null; 9732 } 9733 } 9734 9735 class PackageInstalledInfo { 9736 String name; 9737 int uid; 9738 // The set of users that originally had this package installed. 9739 int[] origUsers; 9740 // The set of users that now have this package installed. 9741 int[] newUsers; 9742 PackageParser.Package pkg; 9743 int returnCode; 9744 PackageRemovedInfo removedInfo; 9745 9746 // In some error cases we want to convey more info back to the observer 9747 String origPackage; 9748 String origPermission; 9749 } 9750 9751 /* 9752 * Install a non-existing package. 9753 */ 9754 private void installNewPackageLI(PackageParser.Package pkg, 9755 int parseFlags, int scanMode, UserHandle user, 9756 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9757 // Remember this for later, in case we need to rollback this install 9758 String pkgName = pkg.packageName; 9759 9760 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9761 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9762 synchronized(mPackages) { 9763 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9764 // A package with the same name is already installed, though 9765 // it has been renamed to an older name. The package we 9766 // are trying to install should be installed as an update to 9767 // the existing one, but that has not been requested, so bail. 9768 Slog.w(TAG, "Attempt to re-install " + pkgName 9769 + " without first uninstalling package running as " 9770 + mSettings.mRenamedPackages.get(pkgName)); 9771 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9772 return; 9773 } 9774 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9775 // Don't allow installation over an existing package with the same name. 9776 Slog.w(TAG, "Attempt to re-install " + pkgName 9777 + " without first uninstalling."); 9778 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9779 return; 9780 } 9781 } 9782 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9783 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9784 System.currentTimeMillis(), user, abiOverride); 9785 if (newPackage == null) { 9786 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 9787 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9788 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9789 } 9790 } else { 9791 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9792 // delete the partially installed application. the data directory will have to be 9793 // restored if it was already existing 9794 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9795 // remove package from internal structures. Note that we want deletePackageX to 9796 // delete the package data and cache directories that it created in 9797 // scanPackageLocked, unless those directories existed before we even tried to 9798 // install. 9799 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9800 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9801 res.removedInfo, true); 9802 } 9803 } 9804 } 9805 9806 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9807 // Upgrade keysets are being used. Determine if new package has a superset of the 9808 // required keys. 9809 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9810 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9811 Set<Long> newSigningKeyIds = new ArraySet<Long>(); 9812 for (PublicKey pk : newPkg.mSigningKeys) { 9813 newSigningKeyIds.add(ksms.getIdForPublicKey(pk)); 9814 } 9815 //remove PUBLIC_KEY_NOT_FOUND, although not necessary 9816 newSigningKeyIds.remove(ksms.PUBLIC_KEY_NOT_FOUND); 9817 for (int i = 0; i < upgradeKeySets.length; i++) { 9818 if (newSigningKeyIds.containsAll(ksms.mKeySetMapping.get(upgradeKeySets[i]))) { 9819 return true; 9820 } 9821 } 9822 return false; 9823 } 9824 9825 private void replacePackageLI(PackageParser.Package pkg, 9826 int parseFlags, int scanMode, UserHandle user, 9827 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9828 PackageParser.Package oldPackage; 9829 String pkgName = pkg.packageName; 9830 int[] allUsers; 9831 boolean[] perUserInstalled; 9832 9833 // First find the old package info and check signatures 9834 synchronized(mPackages) { 9835 oldPackage = mPackages.get(pkgName); 9836 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9837 PackageSetting ps = mSettings.mPackages.get(pkgName); 9838 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9839 // default to original signature matching 9840 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9841 != PackageManager.SIGNATURE_MATCH) { 9842 Slog.w(TAG, "New package has a different signature: " + pkgName); 9843 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9844 return; 9845 } 9846 } else { 9847 if(!checkUpgradeKeySetLP(ps, pkg)) { 9848 Slog.w(TAG, "New package not signed by keys specified by upgrade-keysets: " 9849 + pkgName); 9850 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9851 return; 9852 } 9853 } 9854 9855 // In case of rollback, remember per-user/profile install state 9856 allUsers = sUserManager.getUserIds(); 9857 perUserInstalled = new boolean[allUsers.length]; 9858 for (int i = 0; i < allUsers.length; i++) { 9859 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9860 } 9861 } 9862 boolean sysPkg = (isSystemApp(oldPackage)); 9863 if (sysPkg) { 9864 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9865 user, allUsers, perUserInstalled, installerPackageName, res, 9866 abiOverride); 9867 } else { 9868 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9869 user, allUsers, perUserInstalled, installerPackageName, res, 9870 abiOverride); 9871 } 9872 } 9873 9874 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9875 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9876 int[] allUsers, boolean[] perUserInstalled, 9877 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9878 PackageParser.Package newPackage = null; 9879 String pkgName = deletedPackage.packageName; 9880 boolean deletedPkg = true; 9881 boolean updatedSettings = false; 9882 9883 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9884 + deletedPackage); 9885 long origUpdateTime; 9886 if (pkg.mExtras != null) { 9887 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9888 } else { 9889 origUpdateTime = 0; 9890 } 9891 9892 // First delete the existing package while retaining the data directory 9893 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9894 res.removedInfo, true)) { 9895 // If the existing package wasn't successfully deleted 9896 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9897 deletedPkg = false; 9898 } else { 9899 // Successfully deleted the old package. Now proceed with re-installation 9900 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9901 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 9902 System.currentTimeMillis(), user, abiOverride); 9903 if (newPackage == null) { 9904 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 9905 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9906 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9907 } 9908 } else { 9909 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9910 updatedSettings = true; 9911 } 9912 } 9913 9914 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9915 // remove package from internal structures. Note that we want deletePackageX to 9916 // delete the package data and cache directories that it created in 9917 // scanPackageLocked, unless those directories existed before we even tried to 9918 // install. 9919 if(updatedSettings) { 9920 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9921 deletePackageLI( 9922 pkgName, null, true, allUsers, perUserInstalled, 9923 PackageManager.DELETE_KEEP_DATA, 9924 res.removedInfo, true); 9925 } 9926 // Since we failed to install the new package we need to restore the old 9927 // package that we deleted. 9928 if (deletedPkg) { 9929 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 9930 File restoreFile = new File(deletedPackage.codePath); 9931 // Parse old package 9932 boolean oldOnSd = isExternal(deletedPackage); 9933 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 9934 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 9935 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 9936 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 9937 | SCAN_UPDATE_TIME; 9938 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 9939 origUpdateTime, null, null) == null) { 9940 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 9941 return; 9942 } 9943 // Restore of old package succeeded. Update permissions. 9944 // writer 9945 synchronized (mPackages) { 9946 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 9947 UPDATE_PERMISSIONS_ALL); 9948 // can downgrade to reader 9949 mSettings.writeLPr(); 9950 } 9951 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 9952 } 9953 } 9954 } 9955 9956 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 9957 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9958 int[] allUsers, boolean[] perUserInstalled, 9959 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9960 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 9961 + ", old=" + deletedPackage); 9962 PackageParser.Package newPackage = null; 9963 boolean updatedSettings = false; 9964 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 9965 PackageParser.PARSE_IS_SYSTEM; 9966 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 9967 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9968 } 9969 String packageName = deletedPackage.packageName; 9970 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9971 if (packageName == null) { 9972 Slog.w(TAG, "Attempt to delete null packageName."); 9973 return; 9974 } 9975 PackageParser.Package oldPkg; 9976 PackageSetting oldPkgSetting; 9977 // reader 9978 synchronized (mPackages) { 9979 oldPkg = mPackages.get(packageName); 9980 oldPkgSetting = mSettings.mPackages.get(packageName); 9981 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 9982 (oldPkgSetting == null)) { 9983 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 9984 return; 9985 } 9986 } 9987 9988 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 9989 9990 res.removedInfo.uid = oldPkg.applicationInfo.uid; 9991 res.removedInfo.removedPackage = packageName; 9992 // Remove existing system package 9993 removePackageLI(oldPkgSetting, true); 9994 // writer 9995 synchronized (mPackages) { 9996 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 9997 // We didn't need to disable the .apk as a current system package, 9998 // which means we are replacing another update that is already 9999 // installed. We need to make sure to delete the older one's .apk. 10000 res.removedInfo.args = createInstallArgsForExisting(0, 10001 deletedPackage.applicationInfo.getCodePath(), 10002 deletedPackage.applicationInfo.getResourcePath(), 10003 deletedPackage.applicationInfo.nativeLibraryDir, 10004 getAppInstructionSet(deletedPackage.applicationInfo)); 10005 } else { 10006 res.removedInfo.args = null; 10007 } 10008 } 10009 10010 // Successfully disabled the old package. Now proceed with re-installation 10011 res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED; 10012 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10013 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride); 10014 if (newPackage == null) { 10015 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 10016 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 10017 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 10018 } 10019 } else { 10020 if (newPackage.mExtras != null) { 10021 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 10022 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10023 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10024 10025 // is the update attempting to change shared user? that isn't going to work... 10026 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10027 Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser 10028 + " to " + newPkgSetting.sharedUser); 10029 res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 10030 updatedSettings = true; 10031 } 10032 } 10033 10034 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10035 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10036 updatedSettings = true; 10037 } 10038 } 10039 10040 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10041 // Re installation failed. Restore old information 10042 // Remove new pkg information 10043 if (newPackage != null) { 10044 removeInstalledPackageLI(newPackage, true); 10045 } 10046 // Add back the old system package 10047 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null); 10048 // Restore the old system information in Settings 10049 synchronized(mPackages) { 10050 if (updatedSettings) { 10051 mSettings.enableSystemPackageLPw(packageName); 10052 mSettings.setInstallerPackageName(packageName, 10053 oldPkgSetting.installerPackageName); 10054 } 10055 mSettings.writeLPr(); 10056 } 10057 } 10058 } 10059 10060 // Utility method used to move dex files during install. 10061 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10062 // TODO: extend to move split APK dex files 10063 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10064 final String instructionSet = getAppInstructionSet(newPackage.applicationInfo); 10065 int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath, 10066 instructionSet); 10067 if (retCode != 0) { 10068 /* 10069 * Programs may be lazily run through dexopt, so the 10070 * source may not exist. However, something seems to 10071 * have gone wrong, so note that dexopt needs to be 10072 * run again and remove the source file. In addition, 10073 * remove the target to make sure there isn't a stale 10074 * file from a previous version of the package. 10075 */ 10076 newPackage.mDexOptNeeded = true; 10077 mInstaller.rmdex(oldCodePath, instructionSet); 10078 mInstaller.rmdex(newPackage.baseCodePath, instructionSet); 10079 } 10080 } 10081 return PackageManager.INSTALL_SUCCEEDED; 10082 } 10083 10084 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10085 int[] allUsers, boolean[] perUserInstalled, 10086 PackageInstalledInfo res) { 10087 String pkgName = newPackage.packageName; 10088 synchronized (mPackages) { 10089 //write settings. the installStatus will be incomplete at this stage. 10090 //note that the new package setting would have already been 10091 //added to mPackages. It hasn't been persisted yet. 10092 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10093 mSettings.writeLPr(); 10094 } 10095 10096 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10097 10098 synchronized (mPackages) { 10099 updatePermissionsLPw(newPackage.packageName, newPackage, 10100 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10101 ? UPDATE_PERMISSIONS_ALL : 0)); 10102 // For system-bundled packages, we assume that installing an upgraded version 10103 // of the package implies that the user actually wants to run that new code, 10104 // so we enable the package. 10105 if (isSystemApp(newPackage)) { 10106 // NB: implicit assumption that system package upgrades apply to all users 10107 if (DEBUG_INSTALL) { 10108 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10109 } 10110 PackageSetting ps = mSettings.mPackages.get(pkgName); 10111 if (ps != null) { 10112 if (res.origUsers != null) { 10113 for (int userHandle : res.origUsers) { 10114 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10115 userHandle, installerPackageName); 10116 } 10117 } 10118 // Also convey the prior install/uninstall state 10119 if (allUsers != null && perUserInstalled != null) { 10120 for (int i = 0; i < allUsers.length; i++) { 10121 if (DEBUG_INSTALL) { 10122 Slog.d(TAG, " user " + allUsers[i] 10123 + " => " + perUserInstalled[i]); 10124 } 10125 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10126 } 10127 // these install state changes will be persisted in the 10128 // upcoming call to mSettings.writeLPr(). 10129 } 10130 } 10131 } 10132 res.name = pkgName; 10133 res.uid = newPackage.applicationInfo.uid; 10134 res.pkg = newPackage; 10135 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10136 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10137 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10138 //to update install status 10139 mSettings.writeLPr(); 10140 } 10141 } 10142 10143 private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) { 10144 int pFlags = args.flags; 10145 String installerPackageName = args.installerPackageName; 10146 File tmpPackageFile = new File(args.getCodePath()); 10147 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10148 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10149 boolean replace = false; 10150 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10151 | (newInstall ? SCAN_NEW_INSTALL : 0); 10152 // Result object to be returned 10153 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10154 10155 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10156 // Retrieve PackageSettings and parse package 10157 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10158 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10159 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10160 PackageParser pp = new PackageParser(); 10161 pp.setSeparateProcesses(mSeparateProcesses); 10162 pp.setDisplayMetrics(mMetrics); 10163 10164 final PackageParser.Package pkg; 10165 try { 10166 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10167 } catch (PackageParserException e) { 10168 res.returnCode = e.error; 10169 return; 10170 } 10171 10172 String pkgName = res.name = pkg.packageName; 10173 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10174 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10175 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 10176 return; 10177 } 10178 } 10179 10180 try { 10181 pp.collectCertificates(pkg, parseFlags); 10182 pp.collectManifestDigest(pkg); 10183 } catch (PackageParserException e) { 10184 res.returnCode = e.error; 10185 return; 10186 } 10187 10188 /* If the installer passed in a manifest digest, compare it now. */ 10189 if (args.manifestDigest != null) { 10190 if (DEBUG_INSTALL) { 10191 final String parsedManifest = pkg.manifestDigest == null ? "null" 10192 : pkg.manifestDigest.toString(); 10193 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10194 + parsedManifest); 10195 } 10196 10197 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10198 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 10199 return; 10200 } 10201 } else if (DEBUG_INSTALL) { 10202 final String parsedManifest = pkg.manifestDigest == null 10203 ? "null" : pkg.manifestDigest.toString(); 10204 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10205 } 10206 10207 // Get rid of all references to package scan path via parser. 10208 pp = null; 10209 String oldCodePath = null; 10210 boolean systemApp = false; 10211 synchronized (mPackages) { 10212 // Check whether the newly-scanned package wants to define an already-defined perm 10213 int N = pkg.permissions.size(); 10214 for (int i = N-1; i >= 0; i--) { 10215 PackageParser.Permission perm = pkg.permissions.get(i); 10216 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10217 if (bp != null) { 10218 // If the defining package is signed with our cert, it's okay. This 10219 // also includes the "updating the same package" case, of course. 10220 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10221 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10222 // If the owning package is the system itself, we log but allow 10223 // install to proceed; we fail the install on all other permission 10224 // redefinitions. 10225 if (!bp.sourcePackage.equals("android")) { 10226 Slog.w(TAG, "Package " + pkg.packageName 10227 + " attempting to redeclare permission " + perm.info.name 10228 + " already owned by " + bp.sourcePackage); 10229 res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 10230 res.origPermission = perm.info.name; 10231 res.origPackage = bp.sourcePackage; 10232 return; 10233 } else { 10234 Slog.w(TAG, "Package " + pkg.packageName 10235 + " attempting to redeclare system permission " 10236 + perm.info.name + "; ignoring new declaration"); 10237 pkg.permissions.remove(i); 10238 } 10239 } 10240 } 10241 } 10242 10243 // Check if installing already existing package 10244 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10245 String oldName = mSettings.mRenamedPackages.get(pkgName); 10246 if (pkg.mOriginalPackages != null 10247 && pkg.mOriginalPackages.contains(oldName) 10248 && mPackages.containsKey(oldName)) { 10249 // This package is derived from an original package, 10250 // and this device has been updating from that original 10251 // name. We must continue using the original name, so 10252 // rename the new package here. 10253 pkg.setPackageName(oldName); 10254 pkgName = pkg.packageName; 10255 replace = true; 10256 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10257 + oldName + " pkgName=" + pkgName); 10258 } else if (mPackages.containsKey(pkgName)) { 10259 // This package, under its official name, already exists 10260 // on the device; we should replace it. 10261 replace = true; 10262 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10263 } 10264 } 10265 PackageSetting ps = mSettings.mPackages.get(pkgName); 10266 if (ps != null) { 10267 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10268 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10269 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10270 systemApp = (ps.pkg.applicationInfo.flags & 10271 ApplicationInfo.FLAG_SYSTEM) != 0; 10272 } 10273 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10274 } 10275 } 10276 10277 if (systemApp && onSd) { 10278 // Disable updates to system apps on sdcard 10279 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 10280 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10281 return; 10282 } 10283 10284 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10285 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10286 return; 10287 } 10288 10289 if (replace) { 10290 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10291 installerPackageName, res, args.abiOverride); 10292 } else { 10293 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10294 installerPackageName, res, args.abiOverride); 10295 } 10296 synchronized (mPackages) { 10297 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10298 if (ps != null) { 10299 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10300 } 10301 } 10302 } 10303 10304 private static boolean isForwardLocked(PackageParser.Package pkg) { 10305 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10306 } 10307 10308 10309 private boolean isForwardLocked(PackageSetting ps) { 10310 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10311 } 10312 10313 private static boolean isExternal(PackageParser.Package pkg) { 10314 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10315 } 10316 10317 private static boolean isExternal(PackageSetting ps) { 10318 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10319 } 10320 10321 private static boolean isSystemApp(PackageParser.Package pkg) { 10322 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10323 } 10324 10325 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10326 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10327 } 10328 10329 private static boolean isSystemApp(ApplicationInfo info) { 10330 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10331 } 10332 10333 private static boolean isSystemApp(PackageSetting ps) { 10334 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10335 } 10336 10337 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10338 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10339 } 10340 10341 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10342 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10343 } 10344 10345 private int packageFlagsToInstallFlags(PackageSetting ps) { 10346 int installFlags = 0; 10347 if (isExternal(ps)) { 10348 installFlags |= PackageManager.INSTALL_EXTERNAL; 10349 } 10350 if (isForwardLocked(ps)) { 10351 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10352 } 10353 return installFlags; 10354 } 10355 10356 private void deleteTempPackageFiles() { 10357 final FilenameFilter filter = new FilenameFilter() { 10358 public boolean accept(File dir, String name) { 10359 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10360 } 10361 }; 10362 deleteTempPackageFilesInDirectory(mAppInstallDir, filter); 10363 deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter); 10364 } 10365 10366 private static final void deleteTempPackageFilesInDirectory(File directory, 10367 FilenameFilter filter) { 10368 final File[] files = directory.listFiles(filter); 10369 if (!ArrayUtils.isEmpty(files)) { 10370 for (File file : files) { 10371 if (file.isDirectory()) { 10372 FileUtils.deleteContents(file); 10373 file.delete(); 10374 } else if (file.isFile()) { 10375 file.delete(); 10376 } 10377 } 10378 } 10379 } 10380 10381 private File createTempPackageDir(File installDir) throws IOException { 10382 int n = 0; 10383 while (n++ < 32) { 10384 final File file = new File(installDir, "vmdl" + mTempFileRandom.nextInt() + ".tmp"); 10385 try { 10386 Os.mkdir(file.getAbsolutePath(), 0755); 10387 Os.chmod(file.getAbsolutePath(), 0755); 10388 if (!SELinux.restorecon(file)) { 10389 throw new IOException("Failed to restorecon"); 10390 } 10391 return file; 10392 } catch (ErrnoException e) { 10393 if (e.errno == EEXIST) continue; 10394 throw e.rethrowAsIOException(); 10395 } 10396 } 10397 throw new IOException("Failed to create temp directory"); 10398 } 10399 10400 private File createTempPackageFile(File installDir) throws IOException { 10401 int n = 0; 10402 while (n++ < 32) { 10403 final File file = new File(installDir, "vmdl" + mTempFileRandom.nextInt() + ".tmp"); 10404 try { 10405 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10406 O_RDWR | O_CREAT | O_EXCL, 0644); 10407 IoUtils.closeQuietly(fd); 10408 Os.chmod(file.getAbsolutePath(), 0644); 10409 if (!SELinux.restorecon(file)) { 10410 throw new IOException("Failed to restorecon"); 10411 } 10412 return file; 10413 } catch (ErrnoException e) { 10414 if (e.errno == EEXIST) continue; 10415 throw e.rethrowAsIOException(); 10416 } 10417 } 10418 throw new IOException("Failed to create temp file"); 10419 } 10420 10421 @Override 10422 public void deletePackageAsUser(final String packageName, 10423 final IPackageDeleteObserver observer, 10424 final int userId, final int flags) { 10425 mContext.enforceCallingOrSelfPermission( 10426 android.Manifest.permission.DELETE_PACKAGES, null); 10427 final int uid = Binder.getCallingUid(); 10428 if (UserHandle.getUserId(uid) != userId) { 10429 mContext.enforceCallingPermission( 10430 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10431 "deletePackage for user " + userId); 10432 } 10433 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10434 try { 10435 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 10436 } catch (RemoteException re) { 10437 } 10438 return; 10439 } 10440 10441 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10442 // Queue up an async operation since the package deletion may take a little while. 10443 mHandler.post(new Runnable() { 10444 public void run() { 10445 mHandler.removeCallbacks(this); 10446 final int returnCode = deletePackageX(packageName, userId, flags); 10447 if (observer != null) { 10448 try { 10449 observer.packageDeleted(packageName, returnCode); 10450 } catch (RemoteException e) { 10451 Log.i(TAG, "Observer no longer exists."); 10452 } //end catch 10453 } //end if 10454 } //end run 10455 }); 10456 } 10457 10458 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10459 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10460 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10461 try { 10462 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10463 || dpm.isDeviceOwner(packageName))) { 10464 return true; 10465 } 10466 } catch (RemoteException e) { 10467 } 10468 return false; 10469 } 10470 10471 /** 10472 * This method is an internal method that could be get invoked either 10473 * to delete an installed package or to clean up a failed installation. 10474 * After deleting an installed package, a broadcast is sent to notify any 10475 * listeners that the package has been installed. For cleaning up a failed 10476 * installation, the broadcast is not necessary since the package's 10477 * installation wouldn't have sent the initial broadcast either 10478 * The key steps in deleting a package are 10479 * deleting the package information in internal structures like mPackages, 10480 * deleting the packages base directories through installd 10481 * updating mSettings to reflect current status 10482 * persisting settings for later use 10483 * sending a broadcast if necessary 10484 */ 10485 private int deletePackageX(String packageName, int userId, int flags) { 10486 final PackageRemovedInfo info = new PackageRemovedInfo(); 10487 final boolean res; 10488 10489 if (isPackageDeviceAdmin(packageName, userId)) { 10490 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10491 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10492 } 10493 10494 boolean removedForAllUsers = false; 10495 boolean systemUpdate = false; 10496 10497 // for the uninstall-updates case and restricted profiles, remember the per- 10498 // userhandle installed state 10499 int[] allUsers; 10500 boolean[] perUserInstalled; 10501 synchronized (mPackages) { 10502 PackageSetting ps = mSettings.mPackages.get(packageName); 10503 allUsers = sUserManager.getUserIds(); 10504 perUserInstalled = new boolean[allUsers.length]; 10505 for (int i = 0; i < allUsers.length; i++) { 10506 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10507 } 10508 } 10509 10510 synchronized (mInstallLock) { 10511 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10512 res = deletePackageLI(packageName, 10513 (flags & PackageManager.DELETE_ALL_USERS) != 0 10514 ? UserHandle.ALL : new UserHandle(userId), 10515 true, allUsers, perUserInstalled, 10516 flags | REMOVE_CHATTY, info, true); 10517 systemUpdate = info.isRemovedPackageSystemUpdate; 10518 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10519 removedForAllUsers = true; 10520 } 10521 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10522 + " removedForAllUsers=" + removedForAllUsers); 10523 } 10524 10525 if (res) { 10526 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10527 10528 // If the removed package was a system update, the old system package 10529 // was re-enabled; we need to broadcast this information 10530 if (systemUpdate) { 10531 Bundle extras = new Bundle(1); 10532 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10533 ? info.removedAppId : info.uid); 10534 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10535 10536 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10537 extras, null, null, null); 10538 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10539 extras, null, null, null); 10540 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10541 null, packageName, null, null); 10542 } 10543 } 10544 // Force a gc here. 10545 Runtime.getRuntime().gc(); 10546 // Delete the resources here after sending the broadcast to let 10547 // other processes clean up before deleting resources. 10548 if (info.args != null) { 10549 synchronized (mInstallLock) { 10550 info.args.doPostDeleteLI(true); 10551 } 10552 } 10553 10554 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10555 } 10556 10557 static class PackageRemovedInfo { 10558 String removedPackage; 10559 int uid = -1; 10560 int removedAppId = -1; 10561 int[] removedUsers = null; 10562 boolean isRemovedPackageSystemUpdate = false; 10563 // Clean up resources deleted packages. 10564 InstallArgs args = null; 10565 10566 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10567 Bundle extras = new Bundle(1); 10568 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10569 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10570 if (replacing) { 10571 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10572 } 10573 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10574 if (removedPackage != null) { 10575 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10576 extras, null, null, removedUsers); 10577 if (fullRemove && !replacing) { 10578 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10579 extras, null, null, removedUsers); 10580 } 10581 } 10582 if (removedAppId >= 0) { 10583 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10584 removedUsers); 10585 } 10586 } 10587 } 10588 10589 /* 10590 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10591 * flag is not set, the data directory is removed as well. 10592 * make sure this flag is set for partially installed apps. If not its meaningless to 10593 * delete a partially installed application. 10594 */ 10595 private void removePackageDataLI(PackageSetting ps, 10596 int[] allUserHandles, boolean[] perUserInstalled, 10597 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10598 String packageName = ps.name; 10599 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10600 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10601 // Retrieve object to delete permissions for shared user later on 10602 final PackageSetting deletedPs; 10603 // reader 10604 synchronized (mPackages) { 10605 deletedPs = mSettings.mPackages.get(packageName); 10606 if (outInfo != null) { 10607 outInfo.removedPackage = packageName; 10608 outInfo.removedUsers = deletedPs != null 10609 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10610 : null; 10611 } 10612 } 10613 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10614 removeDataDirsLI(packageName); 10615 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10616 } 10617 // writer 10618 synchronized (mPackages) { 10619 if (deletedPs != null) { 10620 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10621 if (outInfo != null) { 10622 mSettings.mKeySetManagerService.removeAppKeySetData(packageName); 10623 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10624 } 10625 if (deletedPs != null) { 10626 updatePermissionsLPw(deletedPs.name, null, 0); 10627 if (deletedPs.sharedUser != null) { 10628 // remove permissions associated with package 10629 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10630 } 10631 } 10632 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10633 } 10634 // make sure to preserve per-user disabled state if this removal was just 10635 // a downgrade of a system app to the factory package 10636 if (allUserHandles != null && perUserInstalled != null) { 10637 if (DEBUG_REMOVE) { 10638 Slog.d(TAG, "Propagating install state across downgrade"); 10639 } 10640 for (int i = 0; i < allUserHandles.length; i++) { 10641 if (DEBUG_REMOVE) { 10642 Slog.d(TAG, " user " + allUserHandles[i] 10643 + " => " + perUserInstalled[i]); 10644 } 10645 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10646 } 10647 } 10648 } 10649 // can downgrade to reader 10650 if (writeSettings) { 10651 // Save settings now 10652 mSettings.writeLPr(); 10653 } 10654 } 10655 if (outInfo != null) { 10656 // A user ID was deleted here. Go through all users and remove it 10657 // from KeyStore. 10658 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10659 } 10660 } 10661 10662 static boolean locationIsPrivileged(File path) { 10663 try { 10664 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10665 .getCanonicalPath(); 10666 return path.getCanonicalPath().startsWith(privilegedAppDir); 10667 } catch (IOException e) { 10668 Slog.e(TAG, "Unable to access code path " + path); 10669 } 10670 return false; 10671 } 10672 10673 /* 10674 * Tries to delete system package. 10675 */ 10676 private boolean deleteSystemPackageLI(PackageSetting newPs, 10677 int[] allUserHandles, boolean[] perUserInstalled, 10678 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10679 final boolean applyUserRestrictions 10680 = (allUserHandles != null) && (perUserInstalled != null); 10681 PackageSetting disabledPs = null; 10682 // Confirm if the system package has been updated 10683 // An updated system app can be deleted. This will also have to restore 10684 // the system pkg from system partition 10685 // reader 10686 synchronized (mPackages) { 10687 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10688 } 10689 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10690 + " disabledPs=" + disabledPs); 10691 if (disabledPs == null) { 10692 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10693 return false; 10694 } else if (DEBUG_REMOVE) { 10695 Slog.d(TAG, "Deleting system pkg from data partition"); 10696 } 10697 if (DEBUG_REMOVE) { 10698 if (applyUserRestrictions) { 10699 Slog.d(TAG, "Remembering install states:"); 10700 for (int i = 0; i < allUserHandles.length; i++) { 10701 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10702 } 10703 } 10704 } 10705 // Delete the updated package 10706 outInfo.isRemovedPackageSystemUpdate = true; 10707 if (disabledPs.versionCode < newPs.versionCode) { 10708 // Delete data for downgrades 10709 flags &= ~PackageManager.DELETE_KEEP_DATA; 10710 } else { 10711 // Preserve data by setting flag 10712 flags |= PackageManager.DELETE_KEEP_DATA; 10713 } 10714 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10715 allUserHandles, perUserInstalled, outInfo, writeSettings); 10716 if (!ret) { 10717 return false; 10718 } 10719 // writer 10720 synchronized (mPackages) { 10721 // Reinstate the old system package 10722 mSettings.enableSystemPackageLPw(newPs.name); 10723 // Remove any native libraries from the upgraded package. 10724 NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString); 10725 } 10726 // Install the system package 10727 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10728 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10729 if (locationIsPrivileged(disabledPs.codePath)) { 10730 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10731 } 10732 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath, 10733 parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null); 10734 10735 if (newPkg == null) { 10736 Slog.w(TAG, "Failed to restore system package:" + newPs.name 10737 + " with error:" + mLastScanError); 10738 return false; 10739 } 10740 // writer 10741 synchronized (mPackages) { 10742 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10743 setInternalAppNativeLibraryPath(newPkg, ps); 10744 updatePermissionsLPw(newPkg.packageName, newPkg, 10745 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10746 if (applyUserRestrictions) { 10747 if (DEBUG_REMOVE) { 10748 Slog.d(TAG, "Propagating install state across reinstall"); 10749 } 10750 for (int i = 0; i < allUserHandles.length; i++) { 10751 if (DEBUG_REMOVE) { 10752 Slog.d(TAG, " user " + allUserHandles[i] 10753 + " => " + perUserInstalled[i]); 10754 } 10755 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10756 } 10757 // Regardless of writeSettings we need to ensure that this restriction 10758 // state propagation is persisted 10759 mSettings.writeAllUsersPackageRestrictionsLPr(); 10760 } 10761 // can downgrade to reader here 10762 if (writeSettings) { 10763 mSettings.writeLPr(); 10764 } 10765 } 10766 return true; 10767 } 10768 10769 private boolean deleteInstalledPackageLI(PackageSetting ps, 10770 boolean deleteCodeAndResources, int flags, 10771 int[] allUserHandles, boolean[] perUserInstalled, 10772 PackageRemovedInfo outInfo, boolean writeSettings) { 10773 if (outInfo != null) { 10774 outInfo.uid = ps.appId; 10775 } 10776 10777 // Delete package data from internal structures and also remove data if flag is set 10778 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10779 10780 // Delete application code and resources 10781 if (deleteCodeAndResources && (outInfo != null)) { 10782 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10783 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 10784 getAppInstructionSetFromSettings(ps)); 10785 } 10786 return true; 10787 } 10788 10789 @Override 10790 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10791 int userId) { 10792 mContext.enforceCallingOrSelfPermission( 10793 android.Manifest.permission.DELETE_PACKAGES, null); 10794 synchronized (mPackages) { 10795 PackageSetting ps = mSettings.mPackages.get(packageName); 10796 if (ps == null) { 10797 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10798 return false; 10799 } 10800 if (!ps.getInstalled(userId)) { 10801 // Can't block uninstall for an app that is not installed or enabled. 10802 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10803 return false; 10804 } 10805 ps.setBlockUninstall(blockUninstall, userId); 10806 mSettings.writePackageRestrictionsLPr(userId); 10807 } 10808 return true; 10809 } 10810 10811 @Override 10812 public boolean getBlockUninstallForUser(String packageName, int userId) { 10813 synchronized (mPackages) { 10814 PackageSetting ps = mSettings.mPackages.get(packageName); 10815 if (ps == null) { 10816 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10817 return false; 10818 } 10819 return ps.getBlockUninstall(userId); 10820 } 10821 } 10822 10823 /* 10824 * This method handles package deletion in general 10825 */ 10826 private boolean deletePackageLI(String packageName, UserHandle user, 10827 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10828 int flags, PackageRemovedInfo outInfo, 10829 boolean writeSettings) { 10830 if (packageName == null) { 10831 Slog.w(TAG, "Attempt to delete null packageName."); 10832 return false; 10833 } 10834 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10835 PackageSetting ps; 10836 boolean dataOnly = false; 10837 int removeUser = -1; 10838 int appId = -1; 10839 synchronized (mPackages) { 10840 ps = mSettings.mPackages.get(packageName); 10841 if (ps == null) { 10842 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10843 return false; 10844 } 10845 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10846 && user.getIdentifier() != UserHandle.USER_ALL) { 10847 // The caller is asking that the package only be deleted for a single 10848 // user. To do this, we just mark its uninstalled state and delete 10849 // its data. If this is a system app, we only allow this to happen if 10850 // they have set the special DELETE_SYSTEM_APP which requests different 10851 // semantics than normal for uninstalling system apps. 10852 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10853 ps.setUserState(user.getIdentifier(), 10854 COMPONENT_ENABLED_STATE_DEFAULT, 10855 false, //installed 10856 true, //stopped 10857 true, //notLaunched 10858 false, //blocked 10859 null, null, null, 10860 false // blockUninstall 10861 ); 10862 if (!isSystemApp(ps)) { 10863 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10864 // Other user still have this package installed, so all 10865 // we need to do is clear this user's data and save that 10866 // it is uninstalled. 10867 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10868 removeUser = user.getIdentifier(); 10869 appId = ps.appId; 10870 mSettings.writePackageRestrictionsLPr(removeUser); 10871 } else { 10872 // We need to set it back to 'installed' so the uninstall 10873 // broadcasts will be sent correctly. 10874 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10875 ps.setInstalled(true, user.getIdentifier()); 10876 } 10877 } else { 10878 // This is a system app, so we assume that the 10879 // other users still have this package installed, so all 10880 // we need to do is clear this user's data and save that 10881 // it is uninstalled. 10882 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10883 removeUser = user.getIdentifier(); 10884 appId = ps.appId; 10885 mSettings.writePackageRestrictionsLPr(removeUser); 10886 } 10887 } 10888 } 10889 10890 if (removeUser >= 0) { 10891 // From above, we determined that we are deleting this only 10892 // for a single user. Continue the work here. 10893 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10894 if (outInfo != null) { 10895 outInfo.removedPackage = packageName; 10896 outInfo.removedAppId = appId; 10897 outInfo.removedUsers = new int[] {removeUser}; 10898 } 10899 mInstaller.clearUserData(packageName, removeUser); 10900 removeKeystoreDataIfNeeded(removeUser, appId); 10901 schedulePackageCleaning(packageName, removeUser, false); 10902 return true; 10903 } 10904 10905 if (dataOnly) { 10906 // Delete application data first 10907 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10908 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10909 return true; 10910 } 10911 10912 boolean ret = false; 10913 if (isSystemApp(ps)) { 10914 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10915 // When an updated system application is deleted we delete the existing resources as well and 10916 // fall back to existing code in system partition 10917 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10918 flags, outInfo, writeSettings); 10919 } else { 10920 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10921 // Kill application pre-emptively especially for apps on sd. 10922 killApplication(packageName, ps.appId, "uninstall pkg"); 10923 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10924 allUserHandles, perUserInstalled, 10925 outInfo, writeSettings); 10926 } 10927 10928 return ret; 10929 } 10930 10931 private final class ClearStorageConnection implements ServiceConnection { 10932 IMediaContainerService mContainerService; 10933 10934 @Override 10935 public void onServiceConnected(ComponentName name, IBinder service) { 10936 synchronized (this) { 10937 mContainerService = IMediaContainerService.Stub.asInterface(service); 10938 notifyAll(); 10939 } 10940 } 10941 10942 @Override 10943 public void onServiceDisconnected(ComponentName name) { 10944 } 10945 } 10946 10947 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10948 final boolean mounted; 10949 if (Environment.isExternalStorageEmulated()) { 10950 mounted = true; 10951 } else { 10952 final String status = Environment.getExternalStorageState(); 10953 10954 mounted = status.equals(Environment.MEDIA_MOUNTED) 10955 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 10956 } 10957 10958 if (!mounted) { 10959 return; 10960 } 10961 10962 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 10963 int[] users; 10964 if (userId == UserHandle.USER_ALL) { 10965 users = sUserManager.getUserIds(); 10966 } else { 10967 users = new int[] { userId }; 10968 } 10969 final ClearStorageConnection conn = new ClearStorageConnection(); 10970 if (mContext.bindServiceAsUser( 10971 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 10972 try { 10973 for (int curUser : users) { 10974 long timeout = SystemClock.uptimeMillis() + 5000; 10975 synchronized (conn) { 10976 long now = SystemClock.uptimeMillis(); 10977 while (conn.mContainerService == null && now < timeout) { 10978 try { 10979 conn.wait(timeout - now); 10980 } catch (InterruptedException e) { 10981 } 10982 } 10983 } 10984 if (conn.mContainerService == null) { 10985 return; 10986 } 10987 10988 final UserEnvironment userEnv = new UserEnvironment(curUser); 10989 clearDirectory(conn.mContainerService, 10990 userEnv.buildExternalStorageAppCacheDirs(packageName)); 10991 if (allData) { 10992 clearDirectory(conn.mContainerService, 10993 userEnv.buildExternalStorageAppDataDirs(packageName)); 10994 clearDirectory(conn.mContainerService, 10995 userEnv.buildExternalStorageAppMediaDirs(packageName)); 10996 } 10997 } 10998 } finally { 10999 mContext.unbindService(conn); 11000 } 11001 } 11002 } 11003 11004 @Override 11005 public void clearApplicationUserData(final String packageName, 11006 final IPackageDataObserver observer, final int userId) { 11007 mContext.enforceCallingOrSelfPermission( 11008 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11009 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11010 // Queue up an async operation since the package deletion may take a little while. 11011 mHandler.post(new Runnable() { 11012 public void run() { 11013 mHandler.removeCallbacks(this); 11014 final boolean succeeded; 11015 synchronized (mInstallLock) { 11016 succeeded = clearApplicationUserDataLI(packageName, userId); 11017 } 11018 clearExternalStorageDataSync(packageName, userId, true); 11019 if (succeeded) { 11020 // invoke DeviceStorageMonitor's update method to clear any notifications 11021 DeviceStorageMonitorInternal 11022 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11023 if (dsm != null) { 11024 dsm.checkMemory(); 11025 } 11026 } 11027 if(observer != null) { 11028 try { 11029 observer.onRemoveCompleted(packageName, succeeded); 11030 } catch (RemoteException e) { 11031 Log.i(TAG, "Observer no longer exists."); 11032 } 11033 } //end if observer 11034 } //end run 11035 }); 11036 } 11037 11038 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11039 if (packageName == null) { 11040 Slog.w(TAG, "Attempt to delete null packageName."); 11041 return false; 11042 } 11043 PackageParser.Package p; 11044 boolean dataOnly = false; 11045 final int appId; 11046 synchronized (mPackages) { 11047 p = mPackages.get(packageName); 11048 if (p == null) { 11049 dataOnly = true; 11050 PackageSetting ps = mSettings.mPackages.get(packageName); 11051 if ((ps == null) || (ps.pkg == null)) { 11052 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11053 return false; 11054 } 11055 p = ps.pkg; 11056 } 11057 if (!dataOnly) { 11058 // need to check this only for fully installed applications 11059 if (p == null) { 11060 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11061 return false; 11062 } 11063 final ApplicationInfo applicationInfo = p.applicationInfo; 11064 if (applicationInfo == null) { 11065 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11066 return false; 11067 } 11068 } 11069 if (p != null && p.applicationInfo != null) { 11070 appId = p.applicationInfo.uid; 11071 } else { 11072 appId = -1; 11073 } 11074 } 11075 int retCode = mInstaller.clearUserData(packageName, userId); 11076 if (retCode < 0) { 11077 Slog.w(TAG, "Couldn't remove cache files for package: " 11078 + packageName); 11079 return false; 11080 } 11081 removeKeystoreDataIfNeeded(userId, appId); 11082 return true; 11083 } 11084 11085 /** 11086 * Remove entries from the keystore daemon. Will only remove it if the 11087 * {@code appId} is valid. 11088 */ 11089 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11090 if (appId < 0) { 11091 return; 11092 } 11093 11094 final KeyStore keyStore = KeyStore.getInstance(); 11095 if (keyStore != null) { 11096 if (userId == UserHandle.USER_ALL) { 11097 for (final int individual : sUserManager.getUserIds()) { 11098 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11099 } 11100 } else { 11101 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11102 } 11103 } else { 11104 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11105 } 11106 } 11107 11108 @Override 11109 public void deleteApplicationCacheFiles(final String packageName, 11110 final IPackageDataObserver observer) { 11111 mContext.enforceCallingOrSelfPermission( 11112 android.Manifest.permission.DELETE_CACHE_FILES, null); 11113 // Queue up an async operation since the package deletion may take a little while. 11114 final int userId = UserHandle.getCallingUserId(); 11115 mHandler.post(new Runnable() { 11116 public void run() { 11117 mHandler.removeCallbacks(this); 11118 final boolean succeded; 11119 synchronized (mInstallLock) { 11120 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11121 } 11122 clearExternalStorageDataSync(packageName, userId, false); 11123 if(observer != null) { 11124 try { 11125 observer.onRemoveCompleted(packageName, succeded); 11126 } catch (RemoteException e) { 11127 Log.i(TAG, "Observer no longer exists."); 11128 } 11129 } //end if observer 11130 } //end run 11131 }); 11132 } 11133 11134 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11135 if (packageName == null) { 11136 Slog.w(TAG, "Attempt to delete null packageName."); 11137 return false; 11138 } 11139 PackageParser.Package p; 11140 synchronized (mPackages) { 11141 p = mPackages.get(packageName); 11142 } 11143 if (p == null) { 11144 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11145 return false; 11146 } 11147 final ApplicationInfo applicationInfo = p.applicationInfo; 11148 if (applicationInfo == null) { 11149 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11150 return false; 11151 } 11152 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11153 if (retCode < 0) { 11154 Slog.w(TAG, "Couldn't remove cache files for package: " 11155 + packageName + " u" + userId); 11156 return false; 11157 } 11158 return true; 11159 } 11160 11161 @Override 11162 public void getPackageSizeInfo(final String packageName, int userHandle, 11163 final IPackageStatsObserver observer) { 11164 mContext.enforceCallingOrSelfPermission( 11165 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11166 if (packageName == null) { 11167 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11168 } 11169 11170 PackageStats stats = new PackageStats(packageName, userHandle); 11171 11172 /* 11173 * Queue up an async operation since the package measurement may take a 11174 * little while. 11175 */ 11176 Message msg = mHandler.obtainMessage(INIT_COPY); 11177 msg.obj = new MeasureParams(stats, observer); 11178 mHandler.sendMessage(msg); 11179 } 11180 11181 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11182 PackageStats pStats) { 11183 if (packageName == null) { 11184 Slog.w(TAG, "Attempt to get size of null packageName."); 11185 return false; 11186 } 11187 PackageParser.Package p; 11188 boolean dataOnly = false; 11189 String libDirPath = null; 11190 String asecPath = null; 11191 PackageSetting ps = null; 11192 synchronized (mPackages) { 11193 p = mPackages.get(packageName); 11194 ps = mSettings.mPackages.get(packageName); 11195 if(p == null) { 11196 dataOnly = true; 11197 if((ps == null) || (ps.pkg == null)) { 11198 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11199 return false; 11200 } 11201 p = ps.pkg; 11202 } 11203 if (ps != null) { 11204 libDirPath = ps.nativeLibraryPathString; 11205 } 11206 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11207 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11208 if (secureContainerId != null) { 11209 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11210 } 11211 } 11212 } 11213 String publicSrcDir = null; 11214 if(!dataOnly) { 11215 final ApplicationInfo applicationInfo = p.applicationInfo; 11216 if (applicationInfo == null) { 11217 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11218 return false; 11219 } 11220 if (isForwardLocked(p)) { 11221 publicSrcDir = applicationInfo.getBaseResourcePath(); 11222 } 11223 } 11224 // TODO: extend to measure size of split APKs 11225 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirPath, 11226 publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps), 11227 pStats); 11228 if (res < 0) { 11229 return false; 11230 } 11231 11232 // Fix-up for forward-locked applications in ASEC containers. 11233 if (!isExternal(p)) { 11234 pStats.codeSize += pStats.externalCodeSize; 11235 pStats.externalCodeSize = 0L; 11236 } 11237 11238 return true; 11239 } 11240 11241 11242 @Override 11243 public void addPackageToPreferred(String packageName) { 11244 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11245 } 11246 11247 @Override 11248 public void removePackageFromPreferred(String packageName) { 11249 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11250 } 11251 11252 @Override 11253 public List<PackageInfo> getPreferredPackages(int flags) { 11254 return new ArrayList<PackageInfo>(); 11255 } 11256 11257 private int getUidTargetSdkVersionLockedLPr(int uid) { 11258 Object obj = mSettings.getUserIdLPr(uid); 11259 if (obj instanceof SharedUserSetting) { 11260 final SharedUserSetting sus = (SharedUserSetting) obj; 11261 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11262 final Iterator<PackageSetting> it = sus.packages.iterator(); 11263 while (it.hasNext()) { 11264 final PackageSetting ps = it.next(); 11265 if (ps.pkg != null) { 11266 int v = ps.pkg.applicationInfo.targetSdkVersion; 11267 if (v < vers) vers = v; 11268 } 11269 } 11270 return vers; 11271 } else if (obj instanceof PackageSetting) { 11272 final PackageSetting ps = (PackageSetting) obj; 11273 if (ps.pkg != null) { 11274 return ps.pkg.applicationInfo.targetSdkVersion; 11275 } 11276 } 11277 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11278 } 11279 11280 @Override 11281 public void addPreferredActivity(IntentFilter filter, int match, 11282 ComponentName[] set, ComponentName activity, int userId) { 11283 addPreferredActivityInternal(filter, match, set, activity, true, userId); 11284 } 11285 11286 private void addPreferredActivityInternal(IntentFilter filter, int match, 11287 ComponentName[] set, ComponentName activity, boolean always, int userId) { 11288 // writer 11289 int callingUid = Binder.getCallingUid(); 11290 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11291 if (filter.countActions() == 0) { 11292 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11293 return; 11294 } 11295 synchronized (mPackages) { 11296 if (mContext.checkCallingOrSelfPermission( 11297 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11298 != PackageManager.PERMISSION_GRANTED) { 11299 if (getUidTargetSdkVersionLockedLPr(callingUid) 11300 < Build.VERSION_CODES.FROYO) { 11301 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11302 + callingUid); 11303 return; 11304 } 11305 mContext.enforceCallingOrSelfPermission( 11306 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11307 } 11308 11309 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 11310 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11311 mSettings.editPreferredActivitiesLPw(userId).addFilter( 11312 new PreferredActivity(filter, match, set, activity, always)); 11313 mSettings.writePackageRestrictionsLPr(userId); 11314 } 11315 } 11316 11317 @Override 11318 public void replacePreferredActivity(IntentFilter filter, int match, 11319 ComponentName[] set, ComponentName activity) { 11320 if (filter.countActions() != 1) { 11321 throw new IllegalArgumentException( 11322 "replacePreferredActivity expects filter to have only 1 action."); 11323 } 11324 if (filter.countDataAuthorities() != 0 11325 || filter.countDataPaths() != 0 11326 || filter.countDataSchemes() > 1 11327 || filter.countDataTypes() != 0) { 11328 throw new IllegalArgumentException( 11329 "replacePreferredActivity expects filter to have no data authorities, " + 11330 "paths, or types; and at most one scheme."); 11331 } 11332 synchronized (mPackages) { 11333 if (mContext.checkCallingOrSelfPermission( 11334 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11335 != PackageManager.PERMISSION_GRANTED) { 11336 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11337 < Build.VERSION_CODES.FROYO) { 11338 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11339 + Binder.getCallingUid()); 11340 return; 11341 } 11342 mContext.enforceCallingOrSelfPermission( 11343 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11344 } 11345 11346 final int callingUserId = UserHandle.getCallingUserId(); 11347 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 11348 if (pir != null) { 11349 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 11350 if (filter.countDataSchemes() == 1) { 11351 Uri.Builder builder = new Uri.Builder(); 11352 builder.scheme(filter.getDataScheme(0)); 11353 intent.setData(builder.build()); 11354 } 11355 List<PreferredActivity> matches = pir.queryIntent( 11356 intent, null, true, callingUserId); 11357 if (DEBUG_PREFERRED) { 11358 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 11359 } 11360 for (int i = 0; i < matches.size(); i++) { 11361 PreferredActivity pa = matches.get(i); 11362 if (DEBUG_PREFERRED) { 11363 Slog.i(TAG, "Removing preferred activity " 11364 + pa.mPref.mComponent + ":"); 11365 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11366 } 11367 pir.removeFilter(pa); 11368 } 11369 } 11370 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 11371 } 11372 } 11373 11374 @Override 11375 public void clearPackagePreferredActivities(String packageName) { 11376 final int uid = Binder.getCallingUid(); 11377 // writer 11378 synchronized (mPackages) { 11379 PackageParser.Package pkg = mPackages.get(packageName); 11380 if (pkg == null || pkg.applicationInfo.uid != uid) { 11381 if (mContext.checkCallingOrSelfPermission( 11382 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11383 != PackageManager.PERMISSION_GRANTED) { 11384 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11385 < Build.VERSION_CODES.FROYO) { 11386 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11387 + Binder.getCallingUid()); 11388 return; 11389 } 11390 mContext.enforceCallingOrSelfPermission( 11391 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11392 } 11393 } 11394 11395 int user = UserHandle.getCallingUserId(); 11396 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11397 mSettings.writePackageRestrictionsLPr(user); 11398 scheduleWriteSettingsLocked(); 11399 } 11400 } 11401 } 11402 11403 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11404 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11405 ArrayList<PreferredActivity> removed = null; 11406 boolean changed = false; 11407 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11408 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11409 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11410 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11411 continue; 11412 } 11413 Iterator<PreferredActivity> it = pir.filterIterator(); 11414 while (it.hasNext()) { 11415 PreferredActivity pa = it.next(); 11416 // Mark entry for removal only if it matches the package name 11417 // and the entry is of type "always". 11418 if (packageName == null || 11419 (pa.mPref.mComponent.getPackageName().equals(packageName) 11420 && pa.mPref.mAlways)) { 11421 if (removed == null) { 11422 removed = new ArrayList<PreferredActivity>(); 11423 } 11424 removed.add(pa); 11425 } 11426 } 11427 if (removed != null) { 11428 for (int j=0; j<removed.size(); j++) { 11429 PreferredActivity pa = removed.get(j); 11430 pir.removeFilter(pa); 11431 } 11432 changed = true; 11433 } 11434 } 11435 return changed; 11436 } 11437 11438 @Override 11439 public void resetPreferredActivities(int userId) { 11440 mContext.enforceCallingOrSelfPermission( 11441 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11442 // writer 11443 synchronized (mPackages) { 11444 int user = UserHandle.getCallingUserId(); 11445 clearPackagePreferredActivitiesLPw(null, user); 11446 mSettings.readDefaultPreferredAppsLPw(this, user); 11447 mSettings.writePackageRestrictionsLPr(user); 11448 scheduleWriteSettingsLocked(); 11449 } 11450 } 11451 11452 @Override 11453 public int getPreferredActivities(List<IntentFilter> outFilters, 11454 List<ComponentName> outActivities, String packageName) { 11455 11456 int num = 0; 11457 final int userId = UserHandle.getCallingUserId(); 11458 // reader 11459 synchronized (mPackages) { 11460 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11461 if (pir != null) { 11462 final Iterator<PreferredActivity> it = pir.filterIterator(); 11463 while (it.hasNext()) { 11464 final PreferredActivity pa = it.next(); 11465 if (packageName == null 11466 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11467 && pa.mPref.mAlways)) { 11468 if (outFilters != null) { 11469 outFilters.add(new IntentFilter(pa)); 11470 } 11471 if (outActivities != null) { 11472 outActivities.add(pa.mPref.mComponent); 11473 } 11474 } 11475 } 11476 } 11477 } 11478 11479 return num; 11480 } 11481 11482 @Override 11483 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11484 int userId) { 11485 int callingUid = Binder.getCallingUid(); 11486 if (callingUid != Process.SYSTEM_UID) { 11487 throw new SecurityException( 11488 "addPersistentPreferredActivity can only be run by the system"); 11489 } 11490 if (filter.countActions() == 0) { 11491 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11492 return; 11493 } 11494 synchronized (mPackages) { 11495 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11496 " :"); 11497 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11498 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11499 new PersistentPreferredActivity(filter, activity)); 11500 mSettings.writePackageRestrictionsLPr(userId); 11501 } 11502 } 11503 11504 @Override 11505 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11506 int callingUid = Binder.getCallingUid(); 11507 if (callingUid != Process.SYSTEM_UID) { 11508 throw new SecurityException( 11509 "clearPackagePersistentPreferredActivities can only be run by the system"); 11510 } 11511 ArrayList<PersistentPreferredActivity> removed = null; 11512 boolean changed = false; 11513 synchronized (mPackages) { 11514 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11515 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11516 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11517 .valueAt(i); 11518 if (userId != thisUserId) { 11519 continue; 11520 } 11521 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11522 while (it.hasNext()) { 11523 PersistentPreferredActivity ppa = it.next(); 11524 // Mark entry for removal only if it matches the package name. 11525 if (ppa.mComponent.getPackageName().equals(packageName)) { 11526 if (removed == null) { 11527 removed = new ArrayList<PersistentPreferredActivity>(); 11528 } 11529 removed.add(ppa); 11530 } 11531 } 11532 if (removed != null) { 11533 for (int j=0; j<removed.size(); j++) { 11534 PersistentPreferredActivity ppa = removed.get(j); 11535 ppir.removeFilter(ppa); 11536 } 11537 changed = true; 11538 } 11539 } 11540 11541 if (changed) { 11542 mSettings.writePackageRestrictionsLPr(userId); 11543 } 11544 } 11545 } 11546 11547 @Override 11548 public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId, 11549 int targetUserId, int flags) { 11550 mContext.enforceCallingOrSelfPermission( 11551 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11552 if (intentFilter.countActions() == 0) { 11553 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11554 return; 11555 } 11556 synchronized (mPackages) { 11557 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11558 targetUserId, flags); 11559 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11560 mSettings.writePackageRestrictionsLPr(sourceUserId); 11561 } 11562 } 11563 11564 public void addCrossProfileIntentsForPackage(String packageName, 11565 int sourceUserId, int targetUserId) { 11566 mContext.enforceCallingOrSelfPermission( 11567 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11568 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11569 mSettings.writePackageRestrictionsLPr(sourceUserId); 11570 } 11571 11572 public void removeCrossProfileIntentsForPackage(String packageName, 11573 int sourceUserId, int targetUserId) { 11574 mContext.enforceCallingOrSelfPermission( 11575 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11576 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11577 mSettings.writePackageRestrictionsLPr(sourceUserId); 11578 } 11579 11580 @Override 11581 public void clearCrossProfileIntentFilters(int sourceUserId) { 11582 mContext.enforceCallingOrSelfPermission( 11583 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11584 synchronized (mPackages) { 11585 CrossProfileIntentResolver resolver = 11586 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11587 HashSet<CrossProfileIntentFilter> set = 11588 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11589 for (CrossProfileIntentFilter filter : set) { 11590 if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) { 11591 resolver.removeFilter(filter); 11592 } 11593 } 11594 mSettings.writePackageRestrictionsLPr(sourceUserId); 11595 } 11596 } 11597 11598 @Override 11599 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11600 Intent intent = new Intent(Intent.ACTION_MAIN); 11601 intent.addCategory(Intent.CATEGORY_HOME); 11602 11603 final int callingUserId = UserHandle.getCallingUserId(); 11604 List<ResolveInfo> list = queryIntentActivities(intent, null, 11605 PackageManager.GET_META_DATA, callingUserId); 11606 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11607 true, false, false, callingUserId); 11608 11609 allHomeCandidates.clear(); 11610 if (list != null) { 11611 for (ResolveInfo ri : list) { 11612 allHomeCandidates.add(ri); 11613 } 11614 } 11615 return (preferred == null || preferred.activityInfo == null) 11616 ? null 11617 : new ComponentName(preferred.activityInfo.packageName, 11618 preferred.activityInfo.name); 11619 } 11620 11621 @Override 11622 public void setApplicationEnabledSetting(String appPackageName, 11623 int newState, int flags, int userId, String callingPackage) { 11624 if (!sUserManager.exists(userId)) return; 11625 if (callingPackage == null) { 11626 callingPackage = Integer.toString(Binder.getCallingUid()); 11627 } 11628 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11629 } 11630 11631 @Override 11632 public void setComponentEnabledSetting(ComponentName componentName, 11633 int newState, int flags, int userId) { 11634 if (!sUserManager.exists(userId)) return; 11635 setEnabledSetting(componentName.getPackageName(), 11636 componentName.getClassName(), newState, flags, userId, null); 11637 } 11638 11639 private void setEnabledSetting(final String packageName, String className, int newState, 11640 final int flags, int userId, String callingPackage) { 11641 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11642 || newState == COMPONENT_ENABLED_STATE_ENABLED 11643 || newState == COMPONENT_ENABLED_STATE_DISABLED 11644 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11645 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11646 throw new IllegalArgumentException("Invalid new component state: " 11647 + newState); 11648 } 11649 PackageSetting pkgSetting; 11650 final int uid = Binder.getCallingUid(); 11651 final int permission = mContext.checkCallingOrSelfPermission( 11652 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11653 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11654 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11655 boolean sendNow = false; 11656 boolean isApp = (className == null); 11657 String componentName = isApp ? packageName : className; 11658 int packageUid = -1; 11659 ArrayList<String> components; 11660 11661 // writer 11662 synchronized (mPackages) { 11663 pkgSetting = mSettings.mPackages.get(packageName); 11664 if (pkgSetting == null) { 11665 if (className == null) { 11666 throw new IllegalArgumentException( 11667 "Unknown package: " + packageName); 11668 } 11669 throw new IllegalArgumentException( 11670 "Unknown component: " + packageName 11671 + "/" + className); 11672 } 11673 // Allow root and verify that userId is not being specified by a different user 11674 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11675 throw new SecurityException( 11676 "Permission Denial: attempt to change component state from pid=" 11677 + Binder.getCallingPid() 11678 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11679 } 11680 if (className == null) { 11681 // We're dealing with an application/package level state change 11682 if (pkgSetting.getEnabled(userId) == newState) { 11683 // Nothing to do 11684 return; 11685 } 11686 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11687 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11688 // Don't care about who enables an app. 11689 callingPackage = null; 11690 } 11691 pkgSetting.setEnabled(newState, userId, callingPackage); 11692 // pkgSetting.pkg.mSetEnabled = newState; 11693 } else { 11694 // We're dealing with a component level state change 11695 // First, verify that this is a valid class name. 11696 PackageParser.Package pkg = pkgSetting.pkg; 11697 if (pkg == null || !pkg.hasComponentClassName(className)) { 11698 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11699 throw new IllegalArgumentException("Component class " + className 11700 + " does not exist in " + packageName); 11701 } else { 11702 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11703 + className + " does not exist in " + packageName); 11704 } 11705 } 11706 switch (newState) { 11707 case COMPONENT_ENABLED_STATE_ENABLED: 11708 if (!pkgSetting.enableComponentLPw(className, userId)) { 11709 return; 11710 } 11711 break; 11712 case COMPONENT_ENABLED_STATE_DISABLED: 11713 if (!pkgSetting.disableComponentLPw(className, userId)) { 11714 return; 11715 } 11716 break; 11717 case COMPONENT_ENABLED_STATE_DEFAULT: 11718 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11719 return; 11720 } 11721 break; 11722 default: 11723 Slog.e(TAG, "Invalid new component state: " + newState); 11724 return; 11725 } 11726 } 11727 mSettings.writePackageRestrictionsLPr(userId); 11728 components = mPendingBroadcasts.get(userId, packageName); 11729 final boolean newPackage = components == null; 11730 if (newPackage) { 11731 components = new ArrayList<String>(); 11732 } 11733 if (!components.contains(componentName)) { 11734 components.add(componentName); 11735 } 11736 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11737 sendNow = true; 11738 // Purge entry from pending broadcast list if another one exists already 11739 // since we are sending one right away. 11740 mPendingBroadcasts.remove(userId, packageName); 11741 } else { 11742 if (newPackage) { 11743 mPendingBroadcasts.put(userId, packageName, components); 11744 } 11745 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11746 // Schedule a message 11747 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11748 } 11749 } 11750 } 11751 11752 long callingId = Binder.clearCallingIdentity(); 11753 try { 11754 if (sendNow) { 11755 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11756 sendPackageChangedBroadcast(packageName, 11757 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11758 } 11759 } finally { 11760 Binder.restoreCallingIdentity(callingId); 11761 } 11762 } 11763 11764 private void sendPackageChangedBroadcast(String packageName, 11765 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11766 if (DEBUG_INSTALL) 11767 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11768 + componentNames); 11769 Bundle extras = new Bundle(4); 11770 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11771 String nameList[] = new String[componentNames.size()]; 11772 componentNames.toArray(nameList); 11773 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11774 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11775 extras.putInt(Intent.EXTRA_UID, packageUid); 11776 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11777 new int[] {UserHandle.getUserId(packageUid)}); 11778 } 11779 11780 @Override 11781 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11782 if (!sUserManager.exists(userId)) return; 11783 final int uid = Binder.getCallingUid(); 11784 final int permission = mContext.checkCallingOrSelfPermission( 11785 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11786 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11787 enforceCrossUserPermission(uid, userId, true, "stop package"); 11788 // writer 11789 synchronized (mPackages) { 11790 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11791 uid, userId)) { 11792 scheduleWritePackageRestrictionsLocked(userId); 11793 } 11794 } 11795 } 11796 11797 @Override 11798 public String getInstallerPackageName(String packageName) { 11799 // reader 11800 synchronized (mPackages) { 11801 return mSettings.getInstallerPackageNameLPr(packageName); 11802 } 11803 } 11804 11805 @Override 11806 public int getApplicationEnabledSetting(String packageName, int userId) { 11807 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11808 int uid = Binder.getCallingUid(); 11809 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11810 // reader 11811 synchronized (mPackages) { 11812 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11813 } 11814 } 11815 11816 @Override 11817 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11818 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11819 int uid = Binder.getCallingUid(); 11820 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11821 // reader 11822 synchronized (mPackages) { 11823 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11824 } 11825 } 11826 11827 @Override 11828 public void enterSafeMode() { 11829 enforceSystemOrRoot("Only the system can request entering safe mode"); 11830 11831 if (!mSystemReady) { 11832 mSafeMode = true; 11833 } 11834 } 11835 11836 @Override 11837 public void systemReady() { 11838 mSystemReady = true; 11839 11840 // Read the compatibilty setting when the system is ready. 11841 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11842 mContext.getContentResolver(), 11843 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11844 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11845 if (DEBUG_SETTINGS) { 11846 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11847 } 11848 11849 synchronized (mPackages) { 11850 // Verify that all of the preferred activity components actually 11851 // exist. It is possible for applications to be updated and at 11852 // that point remove a previously declared activity component that 11853 // had been set as a preferred activity. We try to clean this up 11854 // the next time we encounter that preferred activity, but it is 11855 // possible for the user flow to never be able to return to that 11856 // situation so here we do a sanity check to make sure we haven't 11857 // left any junk around. 11858 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11859 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11860 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11861 removed.clear(); 11862 for (PreferredActivity pa : pir.filterSet()) { 11863 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11864 removed.add(pa); 11865 } 11866 } 11867 if (removed.size() > 0) { 11868 for (int r=0; r<removed.size(); r++) { 11869 PreferredActivity pa = removed.get(r); 11870 Slog.w(TAG, "Removing dangling preferred activity: " 11871 + pa.mPref.mComponent); 11872 pir.removeFilter(pa); 11873 } 11874 mSettings.writePackageRestrictionsLPr( 11875 mSettings.mPreferredActivities.keyAt(i)); 11876 } 11877 } 11878 } 11879 sUserManager.systemReady(); 11880 } 11881 11882 @Override 11883 public boolean isSafeMode() { 11884 return mSafeMode; 11885 } 11886 11887 @Override 11888 public boolean hasSystemUidErrors() { 11889 return mHasSystemUidErrors; 11890 } 11891 11892 static String arrayToString(int[] array) { 11893 StringBuffer buf = new StringBuffer(128); 11894 buf.append('['); 11895 if (array != null) { 11896 for (int i=0; i<array.length; i++) { 11897 if (i > 0) buf.append(", "); 11898 buf.append(array[i]); 11899 } 11900 } 11901 buf.append(']'); 11902 return buf.toString(); 11903 } 11904 11905 static class DumpState { 11906 public static final int DUMP_LIBS = 1 << 0; 11907 11908 public static final int DUMP_FEATURES = 1 << 1; 11909 11910 public static final int DUMP_RESOLVERS = 1 << 2; 11911 11912 public static final int DUMP_PERMISSIONS = 1 << 3; 11913 11914 public static final int DUMP_PACKAGES = 1 << 4; 11915 11916 public static final int DUMP_SHARED_USERS = 1 << 5; 11917 11918 public static final int DUMP_MESSAGES = 1 << 6; 11919 11920 public static final int DUMP_PROVIDERS = 1 << 7; 11921 11922 public static final int DUMP_VERIFIERS = 1 << 8; 11923 11924 public static final int DUMP_PREFERRED = 1 << 9; 11925 11926 public static final int DUMP_PREFERRED_XML = 1 << 10; 11927 11928 public static final int DUMP_KEYSETS = 1 << 11; 11929 11930 public static final int DUMP_VERSION = 1 << 12; 11931 11932 public static final int OPTION_SHOW_FILTERS = 1 << 0; 11933 11934 private int mTypes; 11935 11936 private int mOptions; 11937 11938 private boolean mTitlePrinted; 11939 11940 private SharedUserSetting mSharedUser; 11941 11942 public boolean isDumping(int type) { 11943 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 11944 return true; 11945 } 11946 11947 return (mTypes & type) != 0; 11948 } 11949 11950 public void setDump(int type) { 11951 mTypes |= type; 11952 } 11953 11954 public boolean isOptionEnabled(int option) { 11955 return (mOptions & option) != 0; 11956 } 11957 11958 public void setOptionEnabled(int option) { 11959 mOptions |= option; 11960 } 11961 11962 public boolean onTitlePrinted() { 11963 final boolean printed = mTitlePrinted; 11964 mTitlePrinted = true; 11965 return printed; 11966 } 11967 11968 public boolean getTitlePrinted() { 11969 return mTitlePrinted; 11970 } 11971 11972 public void setTitlePrinted(boolean enabled) { 11973 mTitlePrinted = enabled; 11974 } 11975 11976 public SharedUserSetting getSharedUser() { 11977 return mSharedUser; 11978 } 11979 11980 public void setSharedUser(SharedUserSetting user) { 11981 mSharedUser = user; 11982 } 11983 } 11984 11985 @Override 11986 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 11987 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 11988 != PackageManager.PERMISSION_GRANTED) { 11989 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 11990 + Binder.getCallingPid() 11991 + ", uid=" + Binder.getCallingUid() 11992 + " without permission " 11993 + android.Manifest.permission.DUMP); 11994 return; 11995 } 11996 11997 DumpState dumpState = new DumpState(); 11998 boolean fullPreferred = false; 11999 boolean checkin = false; 12000 12001 String packageName = null; 12002 12003 int opti = 0; 12004 while (opti < args.length) { 12005 String opt = args[opti]; 12006 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12007 break; 12008 } 12009 opti++; 12010 if ("-a".equals(opt)) { 12011 // Right now we only know how to print all. 12012 } else if ("-h".equals(opt)) { 12013 pw.println("Package manager dump options:"); 12014 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12015 pw.println(" --checkin: dump for a checkin"); 12016 pw.println(" -f: print details of intent filters"); 12017 pw.println(" -h: print this help"); 12018 pw.println(" cmd may be one of:"); 12019 pw.println(" l[ibraries]: list known shared libraries"); 12020 pw.println(" f[ibraries]: list device features"); 12021 pw.println(" k[eysets]: print known keysets"); 12022 pw.println(" r[esolvers]: dump intent resolvers"); 12023 pw.println(" perm[issions]: dump permissions"); 12024 pw.println(" pref[erred]: print preferred package settings"); 12025 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12026 pw.println(" prov[iders]: dump content providers"); 12027 pw.println(" p[ackages]: dump installed packages"); 12028 pw.println(" s[hared-users]: dump shared user IDs"); 12029 pw.println(" m[essages]: print collected runtime messages"); 12030 pw.println(" v[erifiers]: print package verifier info"); 12031 pw.println(" version: print database version info"); 12032 pw.println(" write: write current settings now"); 12033 pw.println(" <package.name>: info about given package"); 12034 return; 12035 } else if ("--checkin".equals(opt)) { 12036 checkin = true; 12037 } else if ("-f".equals(opt)) { 12038 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12039 } else { 12040 pw.println("Unknown argument: " + opt + "; use -h for help"); 12041 } 12042 } 12043 12044 // Is the caller requesting to dump a particular piece of data? 12045 if (opti < args.length) { 12046 String cmd = args[opti]; 12047 opti++; 12048 // Is this a package name? 12049 if ("android".equals(cmd) || cmd.contains(".")) { 12050 packageName = cmd; 12051 // When dumping a single package, we always dump all of its 12052 // filter information since the amount of data will be reasonable. 12053 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12054 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12055 dumpState.setDump(DumpState.DUMP_LIBS); 12056 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12057 dumpState.setDump(DumpState.DUMP_FEATURES); 12058 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12059 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12060 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12061 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12062 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12063 dumpState.setDump(DumpState.DUMP_PREFERRED); 12064 } else if ("preferred-xml".equals(cmd)) { 12065 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12066 if (opti < args.length && "--full".equals(args[opti])) { 12067 fullPreferred = true; 12068 opti++; 12069 } 12070 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12071 dumpState.setDump(DumpState.DUMP_PACKAGES); 12072 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12073 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12074 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12075 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12076 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12077 dumpState.setDump(DumpState.DUMP_MESSAGES); 12078 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12079 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12080 } else if ("version".equals(cmd)) { 12081 dumpState.setDump(DumpState.DUMP_VERSION); 12082 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12083 dumpState.setDump(DumpState.DUMP_KEYSETS); 12084 } else if ("write".equals(cmd)) { 12085 synchronized (mPackages) { 12086 mSettings.writeLPr(); 12087 pw.println("Settings written."); 12088 return; 12089 } 12090 } 12091 } 12092 12093 if (checkin) { 12094 pw.println("vers,1"); 12095 } 12096 12097 // reader 12098 synchronized (mPackages) { 12099 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12100 if (!checkin) { 12101 if (dumpState.onTitlePrinted()) 12102 pw.println(); 12103 pw.println("Database versions:"); 12104 pw.print(" SDK Version:"); 12105 pw.print(" internal="); 12106 pw.print(mSettings.mInternalSdkPlatform); 12107 pw.print(" external="); 12108 pw.println(mSettings.mExternalSdkPlatform); 12109 pw.print(" DB Version:"); 12110 pw.print(" internal="); 12111 pw.print(mSettings.mInternalDatabaseVersion); 12112 pw.print(" external="); 12113 pw.println(mSettings.mExternalDatabaseVersion); 12114 } 12115 } 12116 12117 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12118 if (!checkin) { 12119 if (dumpState.onTitlePrinted()) 12120 pw.println(); 12121 pw.println("Verifiers:"); 12122 pw.print(" Required: "); 12123 pw.print(mRequiredVerifierPackage); 12124 pw.print(" (uid="); 12125 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12126 pw.println(")"); 12127 } else if (mRequiredVerifierPackage != null) { 12128 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12129 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12130 } 12131 } 12132 12133 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12134 boolean printedHeader = false; 12135 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12136 while (it.hasNext()) { 12137 String name = it.next(); 12138 SharedLibraryEntry ent = mSharedLibraries.get(name); 12139 if (!checkin) { 12140 if (!printedHeader) { 12141 if (dumpState.onTitlePrinted()) 12142 pw.println(); 12143 pw.println("Libraries:"); 12144 printedHeader = true; 12145 } 12146 pw.print(" "); 12147 } else { 12148 pw.print("lib,"); 12149 } 12150 pw.print(name); 12151 if (!checkin) { 12152 pw.print(" -> "); 12153 } 12154 if (ent.path != null) { 12155 if (!checkin) { 12156 pw.print("(jar) "); 12157 pw.print(ent.path); 12158 } else { 12159 pw.print(",jar,"); 12160 pw.print(ent.path); 12161 } 12162 } else { 12163 if (!checkin) { 12164 pw.print("(apk) "); 12165 pw.print(ent.apk); 12166 } else { 12167 pw.print(",apk,"); 12168 pw.print(ent.apk); 12169 } 12170 } 12171 pw.println(); 12172 } 12173 } 12174 12175 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12176 if (dumpState.onTitlePrinted()) 12177 pw.println(); 12178 if (!checkin) { 12179 pw.println("Features:"); 12180 } 12181 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12182 while (it.hasNext()) { 12183 String name = it.next(); 12184 if (!checkin) { 12185 pw.print(" "); 12186 } else { 12187 pw.print("feat,"); 12188 } 12189 pw.println(name); 12190 } 12191 } 12192 12193 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12194 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12195 : "Activity Resolver Table:", " ", packageName, 12196 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12197 dumpState.setTitlePrinted(true); 12198 } 12199 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12200 : "Receiver Resolver Table:", " ", packageName, 12201 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12202 dumpState.setTitlePrinted(true); 12203 } 12204 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12205 : "Service Resolver Table:", " ", packageName, 12206 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12207 dumpState.setTitlePrinted(true); 12208 } 12209 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12210 : "Provider Resolver Table:", " ", packageName, 12211 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12212 dumpState.setTitlePrinted(true); 12213 } 12214 } 12215 12216 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12217 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12218 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12219 int user = mSettings.mPreferredActivities.keyAt(i); 12220 if (pir.dump(pw, 12221 dumpState.getTitlePrinted() 12222 ? "\nPreferred Activities User " + user + ":" 12223 : "Preferred Activities User " + user + ":", " ", 12224 packageName, true)) { 12225 dumpState.setTitlePrinted(true); 12226 } 12227 } 12228 } 12229 12230 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12231 pw.flush(); 12232 FileOutputStream fout = new FileOutputStream(fd); 12233 BufferedOutputStream str = new BufferedOutputStream(fout); 12234 XmlSerializer serializer = new FastXmlSerializer(); 12235 try { 12236 serializer.setOutput(str, "utf-8"); 12237 serializer.startDocument(null, true); 12238 serializer.setFeature( 12239 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12240 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12241 serializer.endDocument(); 12242 serializer.flush(); 12243 } catch (IllegalArgumentException e) { 12244 pw.println("Failed writing: " + e); 12245 } catch (IllegalStateException e) { 12246 pw.println("Failed writing: " + e); 12247 } catch (IOException e) { 12248 pw.println("Failed writing: " + e); 12249 } 12250 } 12251 12252 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12253 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12254 } 12255 12256 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12257 boolean printedSomething = false; 12258 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12259 if (packageName != null && !packageName.equals(p.info.packageName)) { 12260 continue; 12261 } 12262 if (!printedSomething) { 12263 if (dumpState.onTitlePrinted()) 12264 pw.println(); 12265 pw.println("Registered ContentProviders:"); 12266 printedSomething = true; 12267 } 12268 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12269 pw.print(" "); pw.println(p.toString()); 12270 } 12271 printedSomething = false; 12272 for (Map.Entry<String, PackageParser.Provider> entry : 12273 mProvidersByAuthority.entrySet()) { 12274 PackageParser.Provider p = entry.getValue(); 12275 if (packageName != null && !packageName.equals(p.info.packageName)) { 12276 continue; 12277 } 12278 if (!printedSomething) { 12279 if (dumpState.onTitlePrinted()) 12280 pw.println(); 12281 pw.println("ContentProvider Authorities:"); 12282 printedSomething = true; 12283 } 12284 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12285 pw.print(" "); pw.println(p.toString()); 12286 if (p.info != null && p.info.applicationInfo != null) { 12287 final String appInfo = p.info.applicationInfo.toString(); 12288 pw.print(" applicationInfo="); pw.println(appInfo); 12289 } 12290 } 12291 } 12292 12293 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12294 mSettings.mKeySetManagerService.dump(pw, packageName, dumpState); 12295 } 12296 12297 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12298 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12299 } 12300 12301 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12302 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12303 } 12304 12305 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12306 if (dumpState.onTitlePrinted()) 12307 pw.println(); 12308 mSettings.dumpReadMessagesLPr(pw, dumpState); 12309 12310 pw.println(); 12311 pw.println("Package warning messages:"); 12312 final File fname = getSettingsProblemFile(); 12313 FileInputStream in = null; 12314 try { 12315 in = new FileInputStream(fname); 12316 final int avail = in.available(); 12317 final byte[] data = new byte[avail]; 12318 in.read(data); 12319 pw.print(new String(data)); 12320 } catch (FileNotFoundException e) { 12321 } catch (IOException e) { 12322 } finally { 12323 if (in != null) { 12324 try { 12325 in.close(); 12326 } catch (IOException e) { 12327 } 12328 } 12329 } 12330 } 12331 } 12332 } 12333 12334 // ------- apps on sdcard specific code ------- 12335 static final boolean DEBUG_SD_INSTALL = false; 12336 12337 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12338 12339 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12340 12341 private boolean mMediaMounted = false; 12342 12343 private String getEncryptKey() { 12344 try { 12345 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12346 SD_ENCRYPTION_KEYSTORE_NAME); 12347 if (sdEncKey == null) { 12348 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12349 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12350 if (sdEncKey == null) { 12351 Slog.e(TAG, "Failed to create encryption keys"); 12352 return null; 12353 } 12354 } 12355 return sdEncKey; 12356 } catch (NoSuchAlgorithmException nsae) { 12357 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12358 return null; 12359 } catch (IOException ioe) { 12360 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12361 return null; 12362 } 12363 12364 } 12365 12366 /* package */static String getTempContainerId() { 12367 int tmpIdx = 1; 12368 String list[] = PackageHelper.getSecureContainerList(); 12369 if (list != null) { 12370 for (final String name : list) { 12371 // Ignore null and non-temporary container entries 12372 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12373 continue; 12374 } 12375 12376 String subStr = name.substring(mTempContainerPrefix.length()); 12377 try { 12378 int cid = Integer.parseInt(subStr); 12379 if (cid >= tmpIdx) { 12380 tmpIdx = cid + 1; 12381 } 12382 } catch (NumberFormatException e) { 12383 } 12384 } 12385 } 12386 return mTempContainerPrefix + tmpIdx; 12387 } 12388 12389 /* 12390 * Update media status on PackageManager. 12391 */ 12392 @Override 12393 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12394 int callingUid = Binder.getCallingUid(); 12395 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12396 throw new SecurityException("Media status can only be updated by the system"); 12397 } 12398 // reader; this apparently protects mMediaMounted, but should probably 12399 // be a different lock in that case. 12400 synchronized (mPackages) { 12401 Log.i(TAG, "Updating external media status from " 12402 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12403 + (mediaStatus ? "mounted" : "unmounted")); 12404 if (DEBUG_SD_INSTALL) 12405 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12406 + ", mMediaMounted=" + mMediaMounted); 12407 if (mediaStatus == mMediaMounted) { 12408 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12409 : 0, -1); 12410 mHandler.sendMessage(msg); 12411 return; 12412 } 12413 mMediaMounted = mediaStatus; 12414 } 12415 // Queue up an async operation since the package installation may take a 12416 // little while. 12417 mHandler.post(new Runnable() { 12418 public void run() { 12419 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12420 } 12421 }); 12422 } 12423 12424 /** 12425 * Called by MountService when the initial ASECs to scan are available. 12426 * Should block until all the ASEC containers are finished being scanned. 12427 */ 12428 public void scanAvailableAsecs() { 12429 updateExternalMediaStatusInner(true, false, false); 12430 if (mShouldRestoreconData) { 12431 SELinuxMMAC.setRestoreconDone(); 12432 mShouldRestoreconData = false; 12433 } 12434 } 12435 12436 /* 12437 * Collect information of applications on external media, map them against 12438 * existing containers and update information based on current mount status. 12439 * Please note that we always have to report status if reportStatus has been 12440 * set to true especially when unloading packages. 12441 */ 12442 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12443 boolean externalStorage) { 12444 // Collection of uids 12445 int uidArr[] = null; 12446 // Collection of stale containers 12447 HashSet<String> removeCids = new HashSet<String>(); 12448 // Collection of packages on external media with valid containers. 12449 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12450 // Get list of secure containers. 12451 final String list[] = PackageHelper.getSecureContainerList(); 12452 if (list == null || list.length == 0) { 12453 Log.i(TAG, "No secure containers on sdcard"); 12454 } else { 12455 // Process list of secure containers and categorize them 12456 // as active or stale based on their package internal state. 12457 int uidList[] = new int[list.length]; 12458 int num = 0; 12459 // reader 12460 synchronized (mPackages) { 12461 for (String cid : list) { 12462 if (DEBUG_SD_INSTALL) 12463 Log.i(TAG, "Processing container " + cid); 12464 String pkgName = getAsecPackageName(cid); 12465 if (pkgName == null) { 12466 if (DEBUG_SD_INSTALL) 12467 Log.i(TAG, "Container : " + cid + " stale"); 12468 removeCids.add(cid); 12469 continue; 12470 } 12471 if (DEBUG_SD_INSTALL) 12472 Log.i(TAG, "Looking for pkg : " + pkgName); 12473 12474 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12475 if (ps == null) { 12476 Log.i(TAG, "Deleting container with no matching settings " + cid); 12477 removeCids.add(cid); 12478 continue; 12479 } 12480 12481 /* 12482 * Skip packages that are not external if we're unmounting 12483 * external storage. 12484 */ 12485 if (externalStorage && !isMounted && !isExternal(ps)) { 12486 continue; 12487 } 12488 12489 final AsecInstallArgs args = new AsecInstallArgs(cid, 12490 getAppInstructionSetFromSettings(ps), 12491 isForwardLocked(ps)); 12492 // The package status is changed only if the code path 12493 // matches between settings and the container id. 12494 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12495 if (DEBUG_SD_INSTALL) { 12496 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12497 + " at code path: " + ps.codePathString); 12498 } 12499 12500 // We do have a valid package installed on sdcard 12501 processCids.put(args, ps.codePathString); 12502 final int uid = ps.appId; 12503 if (uid != -1) { 12504 uidList[num++] = uid; 12505 } 12506 } else { 12507 Log.i(TAG, "Deleting stale container for " + cid); 12508 removeCids.add(cid); 12509 } 12510 } 12511 } 12512 12513 if (num > 0) { 12514 // Sort uid list 12515 Arrays.sort(uidList, 0, num); 12516 // Throw away duplicates 12517 uidArr = new int[num]; 12518 uidArr[0] = uidList[0]; 12519 int di = 0; 12520 for (int i = 1; i < num; i++) { 12521 if (uidList[i - 1] != uidList[i]) { 12522 uidArr[di++] = uidList[i]; 12523 } 12524 } 12525 } 12526 } 12527 // Process packages with valid entries. 12528 if (isMounted) { 12529 if (DEBUG_SD_INSTALL) 12530 Log.i(TAG, "Loading packages"); 12531 loadMediaPackages(processCids, uidArr, removeCids); 12532 startCleaningPackages(); 12533 } else { 12534 if (DEBUG_SD_INSTALL) 12535 Log.i(TAG, "Unloading packages"); 12536 unloadMediaPackages(processCids, uidArr, reportStatus); 12537 } 12538 } 12539 12540 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12541 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12542 int size = pkgList.size(); 12543 if (size > 0) { 12544 // Send broadcasts here 12545 Bundle extras = new Bundle(); 12546 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12547 .toArray(new String[size])); 12548 if (uidArr != null) { 12549 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12550 } 12551 if (replacing) { 12552 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12553 } 12554 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12555 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12556 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12557 } 12558 } 12559 12560 /* 12561 * Look at potentially valid container ids from processCids If package 12562 * information doesn't match the one on record or package scanning fails, 12563 * the cid is added to list of removeCids. We currently don't delete stale 12564 * containers. 12565 */ 12566 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12567 HashSet<String> removeCids) { 12568 ArrayList<String> pkgList = new ArrayList<String>(); 12569 Set<AsecInstallArgs> keys = processCids.keySet(); 12570 boolean doGc = false; 12571 for (AsecInstallArgs args : keys) { 12572 String codePath = processCids.get(args); 12573 if (DEBUG_SD_INSTALL) 12574 Log.i(TAG, "Loading container : " + args.cid); 12575 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12576 try { 12577 // Make sure there are no container errors first. 12578 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12579 Slog.e(TAG, "Failed to mount cid : " + args.cid 12580 + " when installing from sdcard"); 12581 continue; 12582 } 12583 // Check code path here. 12584 if (codePath == null || !codePath.equals(args.getCodePath())) { 12585 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12586 + " does not match one in settings " + codePath); 12587 continue; 12588 } 12589 // Parse package 12590 int parseFlags = mDefParseFlags; 12591 if (args.isExternal()) { 12592 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12593 } 12594 if (args.isFwdLocked()) { 12595 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12596 } 12597 12598 doGc = true; 12599 synchronized (mInstallLock) { 12600 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 12601 0, 0, null, null); 12602 // Scan the package 12603 if (pkg != null) { 12604 /* 12605 * TODO why is the lock being held? doPostInstall is 12606 * called in other places without the lock. This needs 12607 * to be straightened out. 12608 */ 12609 // writer 12610 synchronized (mPackages) { 12611 retCode = PackageManager.INSTALL_SUCCEEDED; 12612 pkgList.add(pkg.packageName); 12613 // Post process args 12614 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12615 pkg.applicationInfo.uid); 12616 } 12617 } else { 12618 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12619 } 12620 } 12621 12622 } finally { 12623 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12624 // Don't destroy container here. Wait till gc clears things 12625 // up. 12626 removeCids.add(args.cid); 12627 } 12628 } 12629 } 12630 // writer 12631 synchronized (mPackages) { 12632 // If the platform SDK has changed since the last time we booted, 12633 // we need to re-grant app permission to catch any new ones that 12634 // appear. This is really a hack, and means that apps can in some 12635 // cases get permissions that the user didn't initially explicitly 12636 // allow... it would be nice to have some better way to handle 12637 // this situation. 12638 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12639 if (regrantPermissions) 12640 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12641 + mSdkVersion + "; regranting permissions for external storage"); 12642 mSettings.mExternalSdkPlatform = mSdkVersion; 12643 12644 // Make sure group IDs have been assigned, and any permission 12645 // changes in other apps are accounted for 12646 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12647 | (regrantPermissions 12648 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12649 : 0)); 12650 12651 mSettings.updateExternalDatabaseVersion(); 12652 12653 // can downgrade to reader 12654 // Persist settings 12655 mSettings.writeLPr(); 12656 } 12657 // Send a broadcast to let everyone know we are done processing 12658 if (pkgList.size() > 0) { 12659 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12660 } 12661 // Force gc to avoid any stale parser references that we might have. 12662 if (doGc) { 12663 Runtime.getRuntime().gc(); 12664 } 12665 // List stale containers and destroy stale temporary containers. 12666 if (removeCids != null) { 12667 for (String cid : removeCids) { 12668 if (cid.startsWith(mTempContainerPrefix)) { 12669 Log.i(TAG, "Destroying stale temporary container " + cid); 12670 PackageHelper.destroySdDir(cid); 12671 } else { 12672 Log.w(TAG, "Container " + cid + " is stale"); 12673 } 12674 } 12675 } 12676 } 12677 12678 /* 12679 * Utility method to unload a list of specified containers 12680 */ 12681 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12682 // Just unmount all valid containers. 12683 for (AsecInstallArgs arg : cidArgs) { 12684 synchronized (mInstallLock) { 12685 arg.doPostDeleteLI(false); 12686 } 12687 } 12688 } 12689 12690 /* 12691 * Unload packages mounted on external media. This involves deleting package 12692 * data from internal structures, sending broadcasts about diabled packages, 12693 * gc'ing to free up references, unmounting all secure containers 12694 * corresponding to packages on external media, and posting a 12695 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12696 * that we always have to post this message if status has been requested no 12697 * matter what. 12698 */ 12699 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12700 final boolean reportStatus) { 12701 if (DEBUG_SD_INSTALL) 12702 Log.i(TAG, "unloading media packages"); 12703 ArrayList<String> pkgList = new ArrayList<String>(); 12704 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12705 final Set<AsecInstallArgs> keys = processCids.keySet(); 12706 for (AsecInstallArgs args : keys) { 12707 String pkgName = args.getPackageName(); 12708 if (DEBUG_SD_INSTALL) 12709 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12710 // Delete package internally 12711 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12712 synchronized (mInstallLock) { 12713 boolean res = deletePackageLI(pkgName, null, false, null, null, 12714 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12715 if (res) { 12716 pkgList.add(pkgName); 12717 } else { 12718 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12719 failedList.add(args); 12720 } 12721 } 12722 } 12723 12724 // reader 12725 synchronized (mPackages) { 12726 // We didn't update the settings after removing each package; 12727 // write them now for all packages. 12728 mSettings.writeLPr(); 12729 } 12730 12731 // We have to absolutely send UPDATED_MEDIA_STATUS only 12732 // after confirming that all the receivers processed the ordered 12733 // broadcast when packages get disabled, force a gc to clean things up. 12734 // and unload all the containers. 12735 if (pkgList.size() > 0) { 12736 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12737 new IIntentReceiver.Stub() { 12738 public void performReceive(Intent intent, int resultCode, String data, 12739 Bundle extras, boolean ordered, boolean sticky, 12740 int sendingUser) throws RemoteException { 12741 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12742 reportStatus ? 1 : 0, 1, keys); 12743 mHandler.sendMessage(msg); 12744 } 12745 }); 12746 } else { 12747 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12748 keys); 12749 mHandler.sendMessage(msg); 12750 } 12751 } 12752 12753 /** Binder call */ 12754 @Override 12755 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12756 final int flags) { 12757 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12758 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12759 int returnCode = PackageManager.MOVE_SUCCEEDED; 12760 int currFlags = 0; 12761 int newFlags = 0; 12762 // reader 12763 synchronized (mPackages) { 12764 PackageParser.Package pkg = mPackages.get(packageName); 12765 if (pkg == null) { 12766 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12767 } else { 12768 // Disable moving fwd locked apps and system packages 12769 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12770 Slog.w(TAG, "Cannot move system application"); 12771 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12772 } else if (pkg.mOperationPending) { 12773 Slog.w(TAG, "Attempt to move package which has pending operations"); 12774 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12775 } else { 12776 // Find install location first 12777 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12778 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12779 Slog.w(TAG, "Ambigous flags specified for move location."); 12780 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12781 } else { 12782 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12783 : PackageManager.INSTALL_INTERNAL; 12784 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12785 : PackageManager.INSTALL_INTERNAL; 12786 12787 if (newFlags == currFlags) { 12788 Slog.w(TAG, "No move required. Trying to move to same location"); 12789 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12790 } else { 12791 if (isForwardLocked(pkg)) { 12792 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12793 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12794 } 12795 } 12796 } 12797 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12798 pkg.mOperationPending = true; 12799 } 12800 } 12801 } 12802 12803 /* 12804 * TODO this next block probably shouldn't be inside the lock. We 12805 * can't guarantee these won't change after this is fired off 12806 * anyway. 12807 */ 12808 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12809 processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user), 12810 returnCode); 12811 } else { 12812 Message msg = mHandler.obtainMessage(INIT_COPY); 12813 final String instructionSet = getAppInstructionSet(pkg.applicationInfo); 12814 InstallArgs srcArgs = createInstallArgsForExisting(currFlags, 12815 pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(), 12816 pkg.applicationInfo.nativeLibraryDir, instructionSet); 12817 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 12818 instructionSet, pkg.applicationInfo.uid, user); 12819 msg.obj = mp; 12820 mHandler.sendMessage(msg); 12821 } 12822 } 12823 } 12824 12825 private void processPendingMove(final MoveParams mp, final int currentStatus) { 12826 // Queue up an async operation since the package deletion may take a 12827 // little while. 12828 mHandler.post(new Runnable() { 12829 public void run() { 12830 // TODO fix this; this does nothing. 12831 mHandler.removeCallbacks(this); 12832 int returnCode = currentStatus; 12833 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 12834 int uidArr[] = null; 12835 ArrayList<String> pkgList = null; 12836 synchronized (mPackages) { 12837 PackageParser.Package pkg = mPackages.get(mp.packageName); 12838 if (pkg == null) { 12839 Slog.w(TAG, " Package " + mp.packageName 12840 + " doesn't exist. Aborting move"); 12841 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12842 } else if (!mp.srcArgs.getCodePath().equals( 12843 pkg.applicationInfo.getCodePath())) { 12844 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 12845 + mp.srcArgs.getCodePath() + " to " 12846 + pkg.applicationInfo.getCodePath() 12847 + " Aborting move and returning error"); 12848 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12849 } else { 12850 uidArr = new int[] { 12851 pkg.applicationInfo.uid 12852 }; 12853 pkgList = new ArrayList<String>(); 12854 pkgList.add(mp.packageName); 12855 } 12856 } 12857 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12858 // Send resources unavailable broadcast 12859 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 12860 // Update package code and resource paths 12861 synchronized (mInstallLock) { 12862 synchronized (mPackages) { 12863 PackageParser.Package pkg = mPackages.get(mp.packageName); 12864 // Recheck for package again. 12865 if (pkg == null) { 12866 Slog.w(TAG, " Package " + mp.packageName 12867 + " doesn't exist. Aborting move"); 12868 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12869 } else if (!mp.srcArgs.getCodePath().equals( 12870 pkg.applicationInfo.getCodePath())) { 12871 Slog.w(TAG, "Package " + mp.packageName 12872 + " code path changed from " + mp.srcArgs.getCodePath() 12873 + " to " + pkg.applicationInfo.getCodePath() 12874 + " Aborting move and returning error"); 12875 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12876 } else { 12877 final String oldCodePath = pkg.codePath; 12878 final String newCodePath = mp.targetArgs.getCodePath(); 12879 final String newResPath = mp.targetArgs.getResourcePath(); 12880 final String newNativePath = mp.targetArgs 12881 .getNativeLibraryPath(); 12882 12883 final File newNativeDir = new File(newNativePath); 12884 12885 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 12886 NativeLibraryHelper.Handle handle = null; 12887 try { 12888 handle = NativeLibraryHelper.Handle.create( 12889 new File(newCodePath)); 12890 final int abi = NativeLibraryHelper.findSupportedAbi( 12891 handle, Build.SUPPORTED_ABIS); 12892 if (abi >= 0) { 12893 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 12894 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 12895 } 12896 } catch (IOException ioe) { 12897 Slog.w(TAG, "Unable to extract native libs for package :" 12898 + mp.packageName, ioe); 12899 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12900 } finally { 12901 IoUtils.closeQuietly(handle); 12902 } 12903 } 12904 final int[] users = sUserManager.getUserIds(); 12905 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12906 for (int user : users) { 12907 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 12908 newNativePath, user) < 0) { 12909 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12910 } 12911 } 12912 } 12913 12914 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12915 pkg.codePath = newCodePath; 12916 pkg.baseCodePath = newCodePath; 12917 // Move dex files around 12918 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 12919 // Moving of dex files failed. Set 12920 // error code and abort move. 12921 pkg.codePath = oldCodePath; 12922 pkg.baseCodePath = oldCodePath; 12923 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12924 } 12925 } 12926 12927 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12928 pkg.applicationInfo.setCodePath(newCodePath); 12929 pkg.applicationInfo.setBaseCodePath(newCodePath); 12930 pkg.applicationInfo.setSplitCodePaths(null); 12931 pkg.applicationInfo.setResourcePath(newResPath); 12932 pkg.applicationInfo.setBaseResourcePath(newResPath); 12933 pkg.applicationInfo.setSplitResourcePaths(null); 12934 pkg.applicationInfo.nativeLibraryDir = newNativePath; 12935 12936 PackageSetting ps = (PackageSetting) pkg.mExtras; 12937 ps.codePath = new File(pkg.applicationInfo.getCodePath()); 12938 ps.codePathString = ps.codePath.getPath(); 12939 ps.resourcePath = new File( 12940 pkg.applicationInfo.getResourcePath()); 12941 ps.resourcePathString = ps.resourcePath.getPath(); 12942 ps.nativeLibraryPathString = newNativePath; 12943 // Set the application info flag 12944 // correctly. 12945 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 12946 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12947 } else { 12948 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12949 } 12950 ps.setFlags(pkg.applicationInfo.flags); 12951 mAppDirs.remove(oldCodePath); 12952 mAppDirs.put(newCodePath, pkg); 12953 // Persist settings 12954 mSettings.writeLPr(); 12955 } 12956 } 12957 } 12958 } 12959 // Send resources available broadcast 12960 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12961 } 12962 } 12963 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12964 // Clean up failed installation 12965 if (mp.targetArgs != null) { 12966 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 12967 -1); 12968 } 12969 } else { 12970 // Force a gc to clear things up. 12971 Runtime.getRuntime().gc(); 12972 // Delete older code 12973 synchronized (mInstallLock) { 12974 mp.srcArgs.doPostDeleteLI(true); 12975 } 12976 } 12977 12978 // Allow more operations on this file if we didn't fail because 12979 // an operation was already pending for this package. 12980 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 12981 synchronized (mPackages) { 12982 PackageParser.Package pkg = mPackages.get(mp.packageName); 12983 if (pkg != null) { 12984 pkg.mOperationPending = false; 12985 } 12986 } 12987 } 12988 12989 IPackageMoveObserver observer = mp.observer; 12990 if (observer != null) { 12991 try { 12992 observer.packageMoved(mp.packageName, returnCode); 12993 } catch (RemoteException e) { 12994 Log.i(TAG, "Observer no longer exists."); 12995 } 12996 } 12997 } 12998 }); 12999 } 13000 13001 @Override 13002 public boolean setInstallLocation(int loc) { 13003 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13004 null); 13005 if (getInstallLocation() == loc) { 13006 return true; 13007 } 13008 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13009 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13010 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13011 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13012 return true; 13013 } 13014 return false; 13015 } 13016 13017 @Override 13018 public int getInstallLocation() { 13019 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13020 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13021 PackageHelper.APP_INSTALL_AUTO); 13022 } 13023 13024 /** Called by UserManagerService */ 13025 void cleanUpUserLILPw(int userHandle) { 13026 mDirtyUsers.remove(userHandle); 13027 mSettings.removeUserLPr(userHandle); 13028 mPendingBroadcasts.remove(userHandle); 13029 if (mInstaller != null) { 13030 // Technically, we shouldn't be doing this with the package lock 13031 // held. However, this is very rare, and there is already so much 13032 // other disk I/O going on, that we'll let it slide for now. 13033 mInstaller.removeUserDataDirs(userHandle); 13034 } 13035 mUserNeedsBadging.delete(userHandle); 13036 } 13037 13038 /** Called by UserManagerService */ 13039 void createNewUserLILPw(int userHandle, File path) { 13040 if (mInstaller != null) { 13041 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13042 } 13043 } 13044 13045 @Override 13046 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13047 mContext.enforceCallingOrSelfPermission( 13048 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13049 "Only package verification agents can read the verifier device identity"); 13050 13051 synchronized (mPackages) { 13052 return mSettings.getVerifierDeviceIdentityLPw(); 13053 } 13054 } 13055 13056 @Override 13057 public void setPermissionEnforced(String permission, boolean enforced) { 13058 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13059 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13060 synchronized (mPackages) { 13061 if (mSettings.mReadExternalStorageEnforced == null 13062 || mSettings.mReadExternalStorageEnforced != enforced) { 13063 mSettings.mReadExternalStorageEnforced = enforced; 13064 mSettings.writeLPr(); 13065 } 13066 } 13067 // kill any non-foreground processes so we restart them and 13068 // grant/revoke the GID. 13069 final IActivityManager am = ActivityManagerNative.getDefault(); 13070 if (am != null) { 13071 final long token = Binder.clearCallingIdentity(); 13072 try { 13073 am.killProcessesBelowForeground("setPermissionEnforcement"); 13074 } catch (RemoteException e) { 13075 } finally { 13076 Binder.restoreCallingIdentity(token); 13077 } 13078 } 13079 } else { 13080 throw new IllegalArgumentException("No selective enforcement for " + permission); 13081 } 13082 } 13083 13084 @Override 13085 @Deprecated 13086 public boolean isPermissionEnforced(String permission) { 13087 return true; 13088 } 13089 13090 @Override 13091 public boolean isStorageLow() { 13092 final long token = Binder.clearCallingIdentity(); 13093 try { 13094 final DeviceStorageMonitorInternal 13095 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13096 if (dsm != null) { 13097 return dsm.isMemoryLow(); 13098 } else { 13099 return false; 13100 } 13101 } finally { 13102 Binder.restoreCallingIdentity(token); 13103 } 13104 } 13105 13106 @Override 13107 public IPackageInstaller getPackageInstaller() { 13108 return mInstallerService; 13109 } 13110 13111 private boolean userNeedsBadging(int userId) { 13112 int index = mUserNeedsBadging.indexOfKey(userId); 13113 if (index < 0) { 13114 final UserInfo userInfo; 13115 final long token = Binder.clearCallingIdentity(); 13116 try { 13117 userInfo = sUserManager.getUserInfo(userId); 13118 } finally { 13119 Binder.restoreCallingIdentity(token); 13120 } 13121 final boolean b; 13122 if (userInfo != null && userInfo.isManagedProfile()) { 13123 b = true; 13124 } else { 13125 b = false; 13126 } 13127 mUserNeedsBadging.put(userId, b); 13128 return b; 13129 } 13130 return mUserNeedsBadging.valueAt(index); 13131 } 13132} 13133