PackageManagerService.java revision dbbf07a5c7f514f2168f236e1df3b2ca70d4ab2f
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_FAILED_USER_RESTRICTED; 29import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 30import static android.content.pm.PackageParser.isApkFile; 31import static android.os.Process.PACKAGE_INFO_GID; 32import static android.os.Process.SYSTEM_UID; 33import static android.system.OsConstants.O_CREAT; 34import static android.system.OsConstants.EEXIST; 35import static android.system.OsConstants.O_EXCL; 36import static android.system.OsConstants.O_RDWR; 37import static android.system.OsConstants.O_WRONLY; 38import static android.system.OsConstants.S_IRGRP; 39import static android.system.OsConstants.S_IROTH; 40import static android.system.OsConstants.S_IRWXU; 41import static android.system.OsConstants.S_IXGRP; 42import static android.system.OsConstants.S_IXOTH; 43import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 44import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 45import static com.android.internal.util.ArrayUtils.appendInt; 46import static com.android.internal.util.ArrayUtils.removeInt; 47 48import android.util.ArrayMap; 49 50import com.android.internal.R; 51import com.android.internal.app.IMediaContainerService; 52import com.android.internal.app.ResolverActivity; 53import com.android.internal.content.NativeLibraryHelper; 54import com.android.internal.content.PackageHelper; 55import com.android.internal.os.IParcelFileDescriptorFactory; 56import com.android.internal.util.ArrayUtils; 57import com.android.internal.util.FastPrintWriter; 58import com.android.internal.util.FastXmlSerializer; 59import com.android.internal.util.Preconditions; 60import com.android.internal.util.XmlUtils; 61import com.android.server.EventLogTags; 62import com.android.server.IntentResolver; 63import com.android.server.LocalServices; 64import com.android.server.ServiceThread; 65import com.android.server.SystemConfig; 66import com.android.server.Watchdog; 67import com.android.server.pm.Settings.DatabaseVersion; 68import com.android.server.storage.DeviceStorageMonitorInternal; 69 70import org.xmlpull.v1.XmlPullParser; 71import org.xmlpull.v1.XmlPullParserException; 72import org.xmlpull.v1.XmlSerializer; 73 74import android.app.ActivityManager; 75import android.app.ActivityManagerNative; 76import android.app.IActivityManager; 77import android.app.PackageInstallObserver; 78import android.app.admin.IDevicePolicyManager; 79import android.app.backup.IBackupManager; 80import android.content.BroadcastReceiver; 81import android.content.ComponentName; 82import android.content.Context; 83import android.content.IIntentReceiver; 84import android.content.Intent; 85import android.content.IntentFilter; 86import android.content.IntentSender; 87import android.content.IntentSender.SendIntentException; 88import android.content.ServiceConnection; 89import android.content.pm.ActivityInfo; 90import android.content.pm.ApplicationInfo; 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 Bundle extras = extrasForInstallResult(res); 1097 args.observer.packageInstalled(res.name, extras, res.returnCode); 1098 } catch (RemoteException e) { 1099 Slog.i(TAG, "Observer no longer exists."); 1100 } 1101 } 1102 } else { 1103 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1104 } 1105 } break; 1106 case UPDATED_MEDIA_STATUS: { 1107 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1108 boolean reportStatus = msg.arg1 == 1; 1109 boolean doGc = msg.arg2 == 1; 1110 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1111 if (doGc) { 1112 // Force a gc to clear up stale containers. 1113 Runtime.getRuntime().gc(); 1114 } 1115 if (msg.obj != null) { 1116 @SuppressWarnings("unchecked") 1117 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1118 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1119 // Unload containers 1120 unloadAllContainers(args); 1121 } 1122 if (reportStatus) { 1123 try { 1124 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1125 PackageHelper.getMountService().finishMediaUpdate(); 1126 } catch (RemoteException e) { 1127 Log.e(TAG, "MountService not running?"); 1128 } 1129 } 1130 } break; 1131 case WRITE_SETTINGS: { 1132 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1133 synchronized (mPackages) { 1134 removeMessages(WRITE_SETTINGS); 1135 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1136 mSettings.writeLPr(); 1137 mDirtyUsers.clear(); 1138 } 1139 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1140 } break; 1141 case WRITE_PACKAGE_RESTRICTIONS: { 1142 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1143 synchronized (mPackages) { 1144 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1145 for (int userId : mDirtyUsers) { 1146 mSettings.writePackageRestrictionsLPr(userId); 1147 } 1148 mDirtyUsers.clear(); 1149 } 1150 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1151 } break; 1152 case CHECK_PENDING_VERIFICATION: { 1153 final int verificationId = msg.arg1; 1154 final PackageVerificationState state = mPendingVerification.get(verificationId); 1155 1156 if ((state != null) && !state.timeoutExtended()) { 1157 final InstallArgs args = state.getInstallArgs(); 1158 final Uri originUri = Uri.fromFile(args.originFile); 1159 1160 Slog.i(TAG, "Verification timed out for " + originUri); 1161 mPendingVerification.remove(verificationId); 1162 1163 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1164 1165 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1166 Slog.i(TAG, "Continuing with installation of " + originUri); 1167 state.setVerifierResponse(Binder.getCallingUid(), 1168 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1169 broadcastPackageVerified(verificationId, originUri, 1170 PackageManager.VERIFICATION_ALLOW, 1171 state.getInstallArgs().getUser()); 1172 try { 1173 ret = args.copyApk(mContainerService, true); 1174 } catch (RemoteException e) { 1175 Slog.e(TAG, "Could not contact the ContainerService"); 1176 } 1177 } else { 1178 broadcastPackageVerified(verificationId, originUri, 1179 PackageManager.VERIFICATION_REJECT, 1180 state.getInstallArgs().getUser()); 1181 } 1182 1183 processPendingInstall(args, ret); 1184 mHandler.sendEmptyMessage(MCS_UNBIND); 1185 } 1186 break; 1187 } 1188 case PACKAGE_VERIFIED: { 1189 final int verificationId = msg.arg1; 1190 1191 final PackageVerificationState state = mPendingVerification.get(verificationId); 1192 if (state == null) { 1193 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1194 break; 1195 } 1196 1197 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1198 1199 state.setVerifierResponse(response.callerUid, response.code); 1200 1201 if (state.isVerificationComplete()) { 1202 mPendingVerification.remove(verificationId); 1203 1204 final InstallArgs args = state.getInstallArgs(); 1205 final Uri originUri = Uri.fromFile(args.originFile); 1206 1207 int ret; 1208 if (state.isInstallAllowed()) { 1209 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1210 broadcastPackageVerified(verificationId, originUri, 1211 response.code, state.getInstallArgs().getUser()); 1212 try { 1213 ret = args.copyApk(mContainerService, true); 1214 } catch (RemoteException e) { 1215 Slog.e(TAG, "Could not contact the ContainerService"); 1216 } 1217 } else { 1218 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1219 } 1220 1221 processPendingInstall(args, ret); 1222 1223 mHandler.sendEmptyMessage(MCS_UNBIND); 1224 } 1225 1226 break; 1227 } 1228 } 1229 } 1230 } 1231 1232 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1233 Bundle extras = null; 1234 switch (res.returnCode) { 1235 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1236 extras = new Bundle(); 1237 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1238 res.origPermission); 1239 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1240 res.origPackage); 1241 break; 1242 } 1243 } 1244 return extras; 1245 } 1246 1247 void scheduleWriteSettingsLocked() { 1248 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1249 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1250 } 1251 } 1252 1253 void scheduleWritePackageRestrictionsLocked(int userId) { 1254 if (!sUserManager.exists(userId)) return; 1255 mDirtyUsers.add(userId); 1256 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1257 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1258 } 1259 } 1260 1261 public static final PackageManagerService main(Context context, Installer installer, 1262 boolean factoryTest, boolean onlyCore) { 1263 PackageManagerService m = new PackageManagerService(context, installer, 1264 factoryTest, onlyCore); 1265 ServiceManager.addService("package", m); 1266 return m; 1267 } 1268 1269 static String[] splitString(String str, char sep) { 1270 int count = 1; 1271 int i = 0; 1272 while ((i=str.indexOf(sep, i)) >= 0) { 1273 count++; 1274 i++; 1275 } 1276 1277 String[] res = new String[count]; 1278 i=0; 1279 count = 0; 1280 int lastI=0; 1281 while ((i=str.indexOf(sep, i)) >= 0) { 1282 res[count] = str.substring(lastI, i); 1283 count++; 1284 i++; 1285 lastI = i; 1286 } 1287 res[count] = str.substring(lastI, str.length()); 1288 return res; 1289 } 1290 1291 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1292 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1293 Context.DISPLAY_SERVICE); 1294 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1295 } 1296 1297 public PackageManagerService(Context context, Installer installer, 1298 boolean factoryTest, boolean onlyCore) { 1299 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1300 SystemClock.uptimeMillis()); 1301 1302 if (mSdkVersion <= 0) { 1303 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1304 } 1305 1306 mContext = context; 1307 mFactoryTest = factoryTest; 1308 mOnlyCore = onlyCore; 1309 mMetrics = new DisplayMetrics(); 1310 mSettings = new Settings(context); 1311 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1312 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1313 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1314 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1315 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1316 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1317 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1318 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1319 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1320 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1321 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1322 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1323 1324 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1325 if (separateProcesses != null && separateProcesses.length() > 0) { 1326 if ("*".equals(separateProcesses)) { 1327 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1328 mSeparateProcesses = null; 1329 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1330 } else { 1331 mDefParseFlags = 0; 1332 mSeparateProcesses = separateProcesses.split(","); 1333 Slog.w(TAG, "Running with debug.separate_processes: " 1334 + separateProcesses); 1335 } 1336 } else { 1337 mDefParseFlags = 0; 1338 mSeparateProcesses = null; 1339 } 1340 1341 mInstaller = installer; 1342 1343 getDefaultDisplayMetrics(context, mMetrics); 1344 1345 SystemConfig systemConfig = SystemConfig.getInstance(); 1346 mGlobalGids = systemConfig.getGlobalGids(); 1347 mSystemPermissions = systemConfig.getSystemPermissions(); 1348 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1349 1350 synchronized (mInstallLock) { 1351 // writer 1352 synchronized (mPackages) { 1353 mHandlerThread = new ServiceThread(TAG, 1354 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1355 mHandlerThread.start(); 1356 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1357 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1358 1359 File dataDir = Environment.getDataDirectory(); 1360 mAppDataDir = new File(dataDir, "data"); 1361 mAppInstallDir = new File(dataDir, "app"); 1362 mAppLibInstallDir = new File(dataDir, "app-lib"); 1363 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1364 mUserAppDataDir = new File(dataDir, "user"); 1365 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1366 mAppStagingDir = new File(dataDir, "app-staging"); 1367 1368 sUserManager = new UserManagerService(context, this, 1369 mInstallLock, mPackages); 1370 1371 // Propagate permission configuration in to package manager. 1372 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1373 = systemConfig.getPermissions(); 1374 for (int i=0; i<permConfig.size(); i++) { 1375 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1376 BasePermission bp = mSettings.mPermissions.get(perm.name); 1377 if (bp == null) { 1378 bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN); 1379 mSettings.mPermissions.put(perm.name, bp); 1380 } 1381 if (perm.gids != null) { 1382 bp.gids = appendInts(bp.gids, perm.gids); 1383 } 1384 } 1385 1386 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1387 for (int i=0; i<libConfig.size(); i++) { 1388 mSharedLibraries.put(libConfig.keyAt(i), 1389 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1390 } 1391 1392 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1393 1394 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1395 mSdkVersion, mOnlyCore); 1396 1397 String customResolverActivity = Resources.getSystem().getString( 1398 R.string.config_customResolverActivity); 1399 if (TextUtils.isEmpty(customResolverActivity)) { 1400 customResolverActivity = null; 1401 } else { 1402 mCustomResolverComponentName = ComponentName.unflattenFromString( 1403 customResolverActivity); 1404 } 1405 1406 long startTime = SystemClock.uptimeMillis(); 1407 1408 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1409 startTime); 1410 1411 // Set flag to monitor and not change apk file paths when 1412 // scanning install directories. 1413 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1414 1415 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1416 1417 /** 1418 * Add everything in the in the boot class path to the 1419 * list of process files because dexopt will have been run 1420 * if necessary during zygote startup. 1421 */ 1422 String bootClassPath = System.getProperty("java.boot.class.path"); 1423 if (bootClassPath != null) { 1424 String[] paths = splitString(bootClassPath, ':'); 1425 for (int i=0; i<paths.length; i++) { 1426 alreadyDexOpted.add(paths[i]); 1427 } 1428 } else { 1429 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1430 } 1431 1432 boolean didDexOptLibraryOrTool = false; 1433 1434 final List<String> instructionSets = getAllInstructionSets(); 1435 1436 /** 1437 * Ensure all external libraries have had dexopt run on them. 1438 */ 1439 if (mSharedLibraries.size() > 0) { 1440 // NOTE: For now, we're compiling these system "shared libraries" 1441 // (and framework jars) into all available architectures. It's possible 1442 // to compile them only when we come across an app that uses them (there's 1443 // already logic for that in scanPackageLI) but that adds some complexity. 1444 for (String instructionSet : instructionSets) { 1445 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1446 final String lib = libEntry.path; 1447 if (lib == null) { 1448 continue; 1449 } 1450 1451 try { 1452 if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) { 1453 alreadyDexOpted.add(lib); 1454 1455 // The list of "shared libraries" we have at this point is 1456 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet); 1457 didDexOptLibraryOrTool = true; 1458 } 1459 } catch (FileNotFoundException e) { 1460 Slog.w(TAG, "Library not found: " + lib); 1461 } catch (IOException e) { 1462 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1463 + e.getMessage()); 1464 } 1465 } 1466 } 1467 } 1468 1469 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1470 1471 // Gross hack for now: we know this file doesn't contain any 1472 // code, so don't dexopt it to avoid the resulting log spew. 1473 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1474 1475 // Gross hack for now: we know this file is only part of 1476 // the boot class path for art, so don't dexopt it to 1477 // avoid the resulting log spew. 1478 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1479 1480 /** 1481 * And there are a number of commands implemented in Java, which 1482 * we currently need to do the dexopt on so that they can be 1483 * run from a non-root shell. 1484 */ 1485 String[] frameworkFiles = frameworkDir.list(); 1486 if (frameworkFiles != null) { 1487 // TODO: We could compile these only for the most preferred ABI. We should 1488 // first double check that the dex files for these commands are not referenced 1489 // by other system apps. 1490 for (String instructionSet : instructionSets) { 1491 for (int i=0; i<frameworkFiles.length; i++) { 1492 File libPath = new File(frameworkDir, frameworkFiles[i]); 1493 String path = libPath.getPath(); 1494 // Skip the file if we already did it. 1495 if (alreadyDexOpted.contains(path)) { 1496 continue; 1497 } 1498 // Skip the file if it is not a type we want to dexopt. 1499 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1500 continue; 1501 } 1502 try { 1503 if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) { 1504 mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet); 1505 didDexOptLibraryOrTool = true; 1506 } 1507 } catch (FileNotFoundException e) { 1508 Slog.w(TAG, "Jar not found: " + path); 1509 } catch (IOException e) { 1510 Slog.w(TAG, "Exception reading jar: " + path, e); 1511 } 1512 } 1513 } 1514 } 1515 1516 if (didDexOptLibraryOrTool) { 1517 // If we dexopted a library or tool, then something on the system has 1518 // changed. Consider this significant, and wipe away all other 1519 // existing dexopt files to ensure we don't leave any dangling around. 1520 // 1521 // TODO: This should be revisited because it isn't as good an indicator 1522 // as it used to be. It used to include the boot classpath but at some point 1523 // DexFile.isDexOptNeeded started returning false for the boot 1524 // class path files in all cases. It is very possible in a 1525 // small maintenance release update that the library and tool 1526 // jars may be unchanged but APK could be removed resulting in 1527 // unused dalvik-cache files. 1528 for (String instructionSet : instructionSets) { 1529 mInstaller.pruneDexCache(instructionSet); 1530 } 1531 1532 // Additionally, delete all dex files from the root directory 1533 // since there shouldn't be any there anyway, unless we're upgrading 1534 // from an older OS version or a build that contained the "old" style 1535 // flat scheme. 1536 mInstaller.pruneDexCache("."); 1537 } 1538 1539 // Collect vendor overlay packages. 1540 // (Do this before scanning any apps.) 1541 // For security and version matching reason, only consider 1542 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1543 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1544 mVendorOverlayInstallObserver = new AppDirObserver( 1545 vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false); 1546 mVendorOverlayInstallObserver.startWatching(); 1547 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1548 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1549 1550 // Find base frameworks (resource packages without code). 1551 mFrameworkInstallObserver = new AppDirObserver( 1552 frameworkDir.getPath(), OBSERVER_EVENTS, true, false); 1553 mFrameworkInstallObserver.startWatching(); 1554 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1555 | PackageParser.PARSE_IS_SYSTEM_DIR 1556 | PackageParser.PARSE_IS_PRIVILEGED, 1557 scanMode | SCAN_NO_DEX, 0); 1558 1559 // Collected privileged system packages. 1560 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1561 mPrivilegedInstallObserver = new AppDirObserver( 1562 privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true); 1563 mPrivilegedInstallObserver.startWatching(); 1564 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1565 | PackageParser.PARSE_IS_SYSTEM_DIR 1566 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1567 1568 // Collect ordinary system packages. 1569 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1570 mSystemInstallObserver = new AppDirObserver( 1571 systemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1572 mSystemInstallObserver.startWatching(); 1573 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1574 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1575 1576 // Collect all vendor packages. 1577 File vendorAppDir = new File("/vendor/app"); 1578 try { 1579 vendorAppDir = vendorAppDir.getCanonicalFile(); 1580 } catch (IOException e) { 1581 // failed to look up canonical path, continue with original one 1582 } 1583 mVendorInstallObserver = new AppDirObserver( 1584 vendorAppDir.getPath(), OBSERVER_EVENTS, true, false); 1585 mVendorInstallObserver.startWatching(); 1586 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1587 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1588 1589 // Collect all OEM packages. 1590 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1591 mOemInstallObserver = new AppDirObserver( 1592 oemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1593 mOemInstallObserver.startWatching(); 1594 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1595 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1596 1597 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1598 mInstaller.moveFiles(); 1599 1600 // Prune any system packages that no longer exist. 1601 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1602 if (!mOnlyCore) { 1603 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1604 while (psit.hasNext()) { 1605 PackageSetting ps = psit.next(); 1606 1607 /* 1608 * If this is not a system app, it can't be a 1609 * disable system app. 1610 */ 1611 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1612 continue; 1613 } 1614 1615 /* 1616 * If the package is scanned, it's not erased. 1617 */ 1618 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1619 if (scannedPkg != null) { 1620 /* 1621 * If the system app is both scanned and in the 1622 * disabled packages list, then it must have been 1623 * added via OTA. Remove it from the currently 1624 * scanned package so the previously user-installed 1625 * application can be scanned. 1626 */ 1627 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1628 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1629 + "; removing system app"); 1630 removePackageLI(ps, true); 1631 } 1632 1633 continue; 1634 } 1635 1636 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1637 psit.remove(); 1638 String msg = "System package " + ps.name 1639 + " no longer exists; wiping its data"; 1640 reportSettingsProblem(Log.WARN, msg); 1641 removeDataDirsLI(ps.name); 1642 } else { 1643 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1644 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1645 possiblyDeletedUpdatedSystemApps.add(ps.name); 1646 } 1647 } 1648 } 1649 } 1650 1651 //look for any incomplete package installations 1652 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1653 //clean up list 1654 for(int i = 0; i < deletePkgsList.size(); i++) { 1655 //clean up here 1656 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1657 } 1658 //delete tmp files 1659 deleteTempPackageFiles(); 1660 1661 // Remove any shared userIDs that have no associated packages 1662 mSettings.pruneSharedUsersLPw(); 1663 1664 if (!mOnlyCore) { 1665 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1666 SystemClock.uptimeMillis()); 1667 mAppInstallObserver = new AppDirObserver( 1668 mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1669 mAppInstallObserver.startWatching(); 1670 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1671 1672 mDrmAppInstallObserver = new AppDirObserver( 1673 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1674 mDrmAppInstallObserver.startWatching(); 1675 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1676 scanMode, 0); 1677 1678 /** 1679 * Remove disable package settings for any updated system 1680 * apps that were removed via an OTA. If they're not a 1681 * previously-updated app, remove them completely. 1682 * Otherwise, just revoke their system-level permissions. 1683 */ 1684 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1685 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1686 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1687 1688 String msg; 1689 if (deletedPkg == null) { 1690 msg = "Updated system package " + deletedAppName 1691 + " no longer exists; wiping its data"; 1692 removeDataDirsLI(deletedAppName); 1693 } else { 1694 msg = "Updated system app + " + deletedAppName 1695 + " no longer present; removing system privileges for " 1696 + deletedAppName; 1697 1698 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1699 1700 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1701 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1702 } 1703 reportSettingsProblem(Log.WARN, msg); 1704 } 1705 } else { 1706 mAppInstallObserver = null; 1707 mDrmAppInstallObserver = null; 1708 } 1709 1710 // Now that we know all of the shared libraries, update all clients to have 1711 // the correct library paths. 1712 updateAllSharedLibrariesLPw(); 1713 1714 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1715 // NOTE: We ignore potential failures here during a system scan (like 1716 // the rest of the commands above) because there's precious little we 1717 // can do about it. A settings error is reported, though. 1718 adjustCpuAbisForSharedUserLPw(setting.packages, null, 1719 false /* force dexopt */, false /* defer dexopt */); 1720 } 1721 1722 // Now that we know all the packages we are keeping, 1723 // read and update their last usage times. 1724 mPackageUsage.readLP(); 1725 1726 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1727 SystemClock.uptimeMillis()); 1728 Slog.i(TAG, "Time to scan packages: " 1729 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1730 + " seconds"); 1731 1732 // If the platform SDK has changed since the last time we booted, 1733 // we need to re-grant app permission to catch any new ones that 1734 // appear. This is really a hack, and means that apps can in some 1735 // cases get permissions that the user didn't initially explicitly 1736 // allow... it would be nice to have some better way to handle 1737 // this situation. 1738 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1739 != mSdkVersion; 1740 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1741 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1742 + "; regranting permissions for internal storage"); 1743 mSettings.mInternalSdkPlatform = mSdkVersion; 1744 1745 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1746 | (regrantPermissions 1747 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1748 : 0)); 1749 1750 // If this is the first boot, and it is a normal boot, then 1751 // we need to initialize the default preferred apps. 1752 if (!mRestoredSettings && !onlyCore) { 1753 mSettings.readDefaultPreferredAppsLPw(this, 0); 1754 } 1755 1756 // All the changes are done during package scanning. 1757 mSettings.updateInternalDatabaseVersion(); 1758 1759 // can downgrade to reader 1760 mSettings.writeLPr(); 1761 1762 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1763 SystemClock.uptimeMillis()); 1764 1765 1766 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1767 } // synchronized (mPackages) 1768 } // synchronized (mInstallLock) 1769 1770 mInstallerService = new PackageInstallerService(context, this, mAppStagingDir); 1771 1772 // Now after opening every single application zip, make sure they 1773 // are all flushed. Not really needed, but keeps things nice and 1774 // tidy. 1775 Runtime.getRuntime().gc(); 1776 } 1777 1778 @Override 1779 public boolean isFirstBoot() { 1780 return !mRestoredSettings; 1781 } 1782 1783 @Override 1784 public boolean isOnlyCoreApps() { 1785 return mOnlyCore; 1786 } 1787 1788 private String getRequiredVerifierLPr() { 1789 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1790 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1791 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1792 1793 String requiredVerifier = null; 1794 1795 final int N = receivers.size(); 1796 for (int i = 0; i < N; i++) { 1797 final ResolveInfo info = receivers.get(i); 1798 1799 if (info.activityInfo == null) { 1800 continue; 1801 } 1802 1803 final String packageName = info.activityInfo.packageName; 1804 1805 final PackageSetting ps = mSettings.mPackages.get(packageName); 1806 if (ps == null) { 1807 continue; 1808 } 1809 1810 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1811 if (!gp.grantedPermissions 1812 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1813 continue; 1814 } 1815 1816 if (requiredVerifier != null) { 1817 throw new RuntimeException("There can be only one required verifier"); 1818 } 1819 1820 requiredVerifier = packageName; 1821 } 1822 1823 return requiredVerifier; 1824 } 1825 1826 @Override 1827 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1828 throws RemoteException { 1829 try { 1830 return super.onTransact(code, data, reply, flags); 1831 } catch (RuntimeException e) { 1832 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1833 Slog.wtf(TAG, "Package Manager Crash", e); 1834 } 1835 throw e; 1836 } 1837 } 1838 1839 void cleanupInstallFailedPackage(PackageSetting ps) { 1840 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1841 removeDataDirsLI(ps.name); 1842 1843 // TODO: try cleaning up codePath directory contents first, since it 1844 // might be a cluster 1845 1846 if (ps.codePath != null) { 1847 if (!ps.codePath.delete()) { 1848 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1849 } 1850 } 1851 if (ps.resourcePath != null) { 1852 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1853 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1854 } 1855 } 1856 mSettings.removePackageLPw(ps.name); 1857 } 1858 1859 static int[] appendInts(int[] cur, int[] add) { 1860 if (add == null) return cur; 1861 if (cur == null) return add; 1862 final int N = add.length; 1863 for (int i=0; i<N; i++) { 1864 cur = appendInt(cur, add[i]); 1865 } 1866 return cur; 1867 } 1868 1869 static int[] removeInts(int[] cur, int[] rem) { 1870 if (rem == null) return cur; 1871 if (cur == null) return cur; 1872 final int N = rem.length; 1873 for (int i=0; i<N; i++) { 1874 cur = removeInt(cur, rem[i]); 1875 } 1876 return cur; 1877 } 1878 1879 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1880 if (!sUserManager.exists(userId)) return null; 1881 final PackageSetting ps = (PackageSetting) p.mExtras; 1882 if (ps == null) { 1883 return null; 1884 } 1885 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1886 final PackageUserState state = ps.readUserState(userId); 1887 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1888 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1889 state, userId); 1890 } 1891 1892 @Override 1893 public boolean isPackageAvailable(String packageName, int userId) { 1894 if (!sUserManager.exists(userId)) return false; 1895 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1896 synchronized (mPackages) { 1897 PackageParser.Package p = mPackages.get(packageName); 1898 if (p != null) { 1899 final PackageSetting ps = (PackageSetting) p.mExtras; 1900 if (ps != null) { 1901 final PackageUserState state = ps.readUserState(userId); 1902 if (state != null) { 1903 return PackageParser.isAvailable(state); 1904 } 1905 } 1906 } 1907 } 1908 return false; 1909 } 1910 1911 @Override 1912 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1913 if (!sUserManager.exists(userId)) return null; 1914 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1915 // reader 1916 synchronized (mPackages) { 1917 PackageParser.Package p = mPackages.get(packageName); 1918 if (DEBUG_PACKAGE_INFO) 1919 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1920 if (p != null) { 1921 return generatePackageInfo(p, flags, userId); 1922 } 1923 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1924 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1925 } 1926 } 1927 return null; 1928 } 1929 1930 @Override 1931 public String[] currentToCanonicalPackageNames(String[] names) { 1932 String[] out = new String[names.length]; 1933 // reader 1934 synchronized (mPackages) { 1935 for (int i=names.length-1; i>=0; i--) { 1936 PackageSetting ps = mSettings.mPackages.get(names[i]); 1937 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1938 } 1939 } 1940 return out; 1941 } 1942 1943 @Override 1944 public String[] canonicalToCurrentPackageNames(String[] names) { 1945 String[] out = new String[names.length]; 1946 // reader 1947 synchronized (mPackages) { 1948 for (int i=names.length-1; i>=0; i--) { 1949 String cur = mSettings.mRenamedPackages.get(names[i]); 1950 out[i] = cur != null ? cur : names[i]; 1951 } 1952 } 1953 return out; 1954 } 1955 1956 @Override 1957 public int getPackageUid(String packageName, int userId) { 1958 if (!sUserManager.exists(userId)) return -1; 1959 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1960 // reader 1961 synchronized (mPackages) { 1962 PackageParser.Package p = mPackages.get(packageName); 1963 if(p != null) { 1964 return UserHandle.getUid(userId, p.applicationInfo.uid); 1965 } 1966 PackageSetting ps = mSettings.mPackages.get(packageName); 1967 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1968 return -1; 1969 } 1970 p = ps.pkg; 1971 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1972 } 1973 } 1974 1975 @Override 1976 public int[] getPackageGids(String packageName) { 1977 // reader 1978 synchronized (mPackages) { 1979 PackageParser.Package p = mPackages.get(packageName); 1980 if (DEBUG_PACKAGE_INFO) 1981 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1982 if (p != null) { 1983 final PackageSetting ps = (PackageSetting)p.mExtras; 1984 return ps.getGids(); 1985 } 1986 } 1987 // stupid thing to indicate an error. 1988 return new int[0]; 1989 } 1990 1991 static final PermissionInfo generatePermissionInfo( 1992 BasePermission bp, int flags) { 1993 if (bp.perm != null) { 1994 return PackageParser.generatePermissionInfo(bp.perm, flags); 1995 } 1996 PermissionInfo pi = new PermissionInfo(); 1997 pi.name = bp.name; 1998 pi.packageName = bp.sourcePackage; 1999 pi.nonLocalizedLabel = bp.name; 2000 pi.protectionLevel = bp.protectionLevel; 2001 return pi; 2002 } 2003 2004 @Override 2005 public PermissionInfo getPermissionInfo(String name, int flags) { 2006 // reader 2007 synchronized (mPackages) { 2008 final BasePermission p = mSettings.mPermissions.get(name); 2009 if (p != null) { 2010 return generatePermissionInfo(p, flags); 2011 } 2012 return null; 2013 } 2014 } 2015 2016 @Override 2017 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2018 // reader 2019 synchronized (mPackages) { 2020 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2021 for (BasePermission p : mSettings.mPermissions.values()) { 2022 if (group == null) { 2023 if (p.perm == null || p.perm.info.group == null) { 2024 out.add(generatePermissionInfo(p, flags)); 2025 } 2026 } else { 2027 if (p.perm != null && group.equals(p.perm.info.group)) { 2028 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2029 } 2030 } 2031 } 2032 2033 if (out.size() > 0) { 2034 return out; 2035 } 2036 return mPermissionGroups.containsKey(group) ? out : null; 2037 } 2038 } 2039 2040 @Override 2041 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2042 // reader 2043 synchronized (mPackages) { 2044 return PackageParser.generatePermissionGroupInfo( 2045 mPermissionGroups.get(name), flags); 2046 } 2047 } 2048 2049 @Override 2050 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2051 // reader 2052 synchronized (mPackages) { 2053 final int N = mPermissionGroups.size(); 2054 ArrayList<PermissionGroupInfo> out 2055 = new ArrayList<PermissionGroupInfo>(N); 2056 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2057 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2058 } 2059 return out; 2060 } 2061 } 2062 2063 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2064 int userId) { 2065 if (!sUserManager.exists(userId)) return null; 2066 PackageSetting ps = mSettings.mPackages.get(packageName); 2067 if (ps != null) { 2068 if (ps.pkg == null) { 2069 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2070 flags, userId); 2071 if (pInfo != null) { 2072 return pInfo.applicationInfo; 2073 } 2074 return null; 2075 } 2076 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2077 ps.readUserState(userId), userId); 2078 } 2079 return null; 2080 } 2081 2082 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2083 int userId) { 2084 if (!sUserManager.exists(userId)) return null; 2085 PackageSetting ps = mSettings.mPackages.get(packageName); 2086 if (ps != null) { 2087 PackageParser.Package pkg = ps.pkg; 2088 if (pkg == null) { 2089 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2090 return null; 2091 } 2092 // Only data remains, so we aren't worried about code paths 2093 pkg = new PackageParser.Package(packageName); 2094 pkg.applicationInfo.packageName = packageName; 2095 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2096 pkg.applicationInfo.dataDir = 2097 getDataPathForPackage(packageName, 0).getPath(); 2098 pkg.applicationInfo.cpuAbi = ps.cpuAbiString; 2099 } 2100 return generatePackageInfo(pkg, flags, userId); 2101 } 2102 return null; 2103 } 2104 2105 @Override 2106 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2107 if (!sUserManager.exists(userId)) return null; 2108 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2109 // writer 2110 synchronized (mPackages) { 2111 PackageParser.Package p = mPackages.get(packageName); 2112 if (DEBUG_PACKAGE_INFO) Log.v( 2113 TAG, "getApplicationInfo " + packageName 2114 + ": " + p); 2115 if (p != null) { 2116 PackageSetting ps = mSettings.mPackages.get(packageName); 2117 if (ps == null) return null; 2118 // Note: isEnabledLP() does not apply here - always return info 2119 return PackageParser.generateApplicationInfo( 2120 p, flags, ps.readUserState(userId), userId); 2121 } 2122 if ("android".equals(packageName)||"system".equals(packageName)) { 2123 return mAndroidApplication; 2124 } 2125 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2126 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2127 } 2128 } 2129 return null; 2130 } 2131 2132 2133 @Override 2134 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2135 mContext.enforceCallingOrSelfPermission( 2136 android.Manifest.permission.CLEAR_APP_CACHE, null); 2137 // Queue up an async operation since clearing cache may take a little while. 2138 mHandler.post(new Runnable() { 2139 public void run() { 2140 mHandler.removeCallbacks(this); 2141 int retCode = -1; 2142 synchronized (mInstallLock) { 2143 retCode = mInstaller.freeCache(freeStorageSize); 2144 if (retCode < 0) { 2145 Slog.w(TAG, "Couldn't clear application caches"); 2146 } 2147 } 2148 if (observer != null) { 2149 try { 2150 observer.onRemoveCompleted(null, (retCode >= 0)); 2151 } catch (RemoteException e) { 2152 Slog.w(TAG, "RemoveException when invoking call back"); 2153 } 2154 } 2155 } 2156 }); 2157 } 2158 2159 @Override 2160 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2161 mContext.enforceCallingOrSelfPermission( 2162 android.Manifest.permission.CLEAR_APP_CACHE, null); 2163 // Queue up an async operation since clearing cache may take a little while. 2164 mHandler.post(new Runnable() { 2165 public void run() { 2166 mHandler.removeCallbacks(this); 2167 int retCode = -1; 2168 synchronized (mInstallLock) { 2169 retCode = mInstaller.freeCache(freeStorageSize); 2170 if (retCode < 0) { 2171 Slog.w(TAG, "Couldn't clear application caches"); 2172 } 2173 } 2174 if(pi != null) { 2175 try { 2176 // Callback via pending intent 2177 int code = (retCode >= 0) ? 1 : 0; 2178 pi.sendIntent(null, code, null, 2179 null, null); 2180 } catch (SendIntentException e1) { 2181 Slog.i(TAG, "Failed to send pending intent"); 2182 } 2183 } 2184 } 2185 }); 2186 } 2187 2188 void freeStorage(long freeStorageSize) throws IOException { 2189 synchronized (mInstallLock) { 2190 if (mInstaller.freeCache(freeStorageSize) < 0) { 2191 throw new IOException("Failed to free enough space"); 2192 } 2193 } 2194 } 2195 2196 @Override 2197 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2198 if (!sUserManager.exists(userId)) return null; 2199 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2200 synchronized (mPackages) { 2201 PackageParser.Activity a = mActivities.mActivities.get(component); 2202 2203 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2204 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2205 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2206 if (ps == null) return null; 2207 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2208 userId); 2209 } 2210 if (mResolveComponentName.equals(component)) { 2211 return mResolveActivity; 2212 } 2213 } 2214 return null; 2215 } 2216 2217 @Override 2218 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2219 String resolvedType) { 2220 synchronized (mPackages) { 2221 PackageParser.Activity a = mActivities.mActivities.get(component); 2222 if (a == null) { 2223 return false; 2224 } 2225 for (int i=0; i<a.intents.size(); i++) { 2226 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2227 intent.getData(), intent.getCategories(), TAG) >= 0) { 2228 return true; 2229 } 2230 } 2231 return false; 2232 } 2233 } 2234 2235 @Override 2236 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2237 if (!sUserManager.exists(userId)) return null; 2238 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2239 synchronized (mPackages) { 2240 PackageParser.Activity a = mReceivers.mActivities.get(component); 2241 if (DEBUG_PACKAGE_INFO) Log.v( 2242 TAG, "getReceiverInfo " + component + ": " + a); 2243 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2244 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2245 if (ps == null) return null; 2246 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2247 userId); 2248 } 2249 } 2250 return null; 2251 } 2252 2253 @Override 2254 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2255 if (!sUserManager.exists(userId)) return null; 2256 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2257 synchronized (mPackages) { 2258 PackageParser.Service s = mServices.mServices.get(component); 2259 if (DEBUG_PACKAGE_INFO) Log.v( 2260 TAG, "getServiceInfo " + component + ": " + s); 2261 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2262 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2263 if (ps == null) return null; 2264 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2265 userId); 2266 } 2267 } 2268 return null; 2269 } 2270 2271 @Override 2272 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2273 if (!sUserManager.exists(userId)) return null; 2274 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2275 synchronized (mPackages) { 2276 PackageParser.Provider p = mProviders.mProviders.get(component); 2277 if (DEBUG_PACKAGE_INFO) Log.v( 2278 TAG, "getProviderInfo " + component + ": " + p); 2279 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2280 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2281 if (ps == null) return null; 2282 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2283 userId); 2284 } 2285 } 2286 return null; 2287 } 2288 2289 @Override 2290 public String[] getSystemSharedLibraryNames() { 2291 Set<String> libSet; 2292 synchronized (mPackages) { 2293 libSet = mSharedLibraries.keySet(); 2294 int size = libSet.size(); 2295 if (size > 0) { 2296 String[] libs = new String[size]; 2297 libSet.toArray(libs); 2298 return libs; 2299 } 2300 } 2301 return null; 2302 } 2303 2304 @Override 2305 public FeatureInfo[] getSystemAvailableFeatures() { 2306 Collection<FeatureInfo> featSet; 2307 synchronized (mPackages) { 2308 featSet = mAvailableFeatures.values(); 2309 int size = featSet.size(); 2310 if (size > 0) { 2311 FeatureInfo[] features = new FeatureInfo[size+1]; 2312 featSet.toArray(features); 2313 FeatureInfo fi = new FeatureInfo(); 2314 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2315 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2316 features[size] = fi; 2317 return features; 2318 } 2319 } 2320 return null; 2321 } 2322 2323 @Override 2324 public boolean hasSystemFeature(String name) { 2325 synchronized (mPackages) { 2326 return mAvailableFeatures.containsKey(name); 2327 } 2328 } 2329 2330 private void checkValidCaller(int uid, int userId) { 2331 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2332 return; 2333 2334 throw new SecurityException("Caller uid=" + uid 2335 + " is not privileged to communicate with user=" + userId); 2336 } 2337 2338 @Override 2339 public int checkPermission(String permName, String pkgName) { 2340 synchronized (mPackages) { 2341 PackageParser.Package p = mPackages.get(pkgName); 2342 if (p != null && p.mExtras != null) { 2343 PackageSetting ps = (PackageSetting)p.mExtras; 2344 if (ps.sharedUser != null) { 2345 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2346 return PackageManager.PERMISSION_GRANTED; 2347 } 2348 } else if (ps.grantedPermissions.contains(permName)) { 2349 return PackageManager.PERMISSION_GRANTED; 2350 } 2351 } 2352 } 2353 return PackageManager.PERMISSION_DENIED; 2354 } 2355 2356 @Override 2357 public int checkUidPermission(String permName, int uid) { 2358 synchronized (mPackages) { 2359 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2360 if (obj != null) { 2361 GrantedPermissions gp = (GrantedPermissions)obj; 2362 if (gp.grantedPermissions.contains(permName)) { 2363 return PackageManager.PERMISSION_GRANTED; 2364 } 2365 } else { 2366 HashSet<String> perms = mSystemPermissions.get(uid); 2367 if (perms != null && perms.contains(permName)) { 2368 return PackageManager.PERMISSION_GRANTED; 2369 } 2370 } 2371 } 2372 return PackageManager.PERMISSION_DENIED; 2373 } 2374 2375 /** 2376 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2377 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2378 * @param message the message to log on security exception 2379 */ 2380 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2381 String message) { 2382 if (userId < 0) { 2383 throw new IllegalArgumentException("Invalid userId " + userId); 2384 } 2385 if (userId == UserHandle.getUserId(callingUid)) return; 2386 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2387 if (requireFullPermission) { 2388 mContext.enforceCallingOrSelfPermission( 2389 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2390 } else { 2391 try { 2392 mContext.enforceCallingOrSelfPermission( 2393 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2394 } catch (SecurityException se) { 2395 mContext.enforceCallingOrSelfPermission( 2396 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2397 } 2398 } 2399 } 2400 } 2401 2402 private BasePermission findPermissionTreeLP(String permName) { 2403 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2404 if (permName.startsWith(bp.name) && 2405 permName.length() > bp.name.length() && 2406 permName.charAt(bp.name.length()) == '.') { 2407 return bp; 2408 } 2409 } 2410 return null; 2411 } 2412 2413 private BasePermission checkPermissionTreeLP(String permName) { 2414 if (permName != null) { 2415 BasePermission bp = findPermissionTreeLP(permName); 2416 if (bp != null) { 2417 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2418 return bp; 2419 } 2420 throw new SecurityException("Calling uid " 2421 + Binder.getCallingUid() 2422 + " is not allowed to add to permission tree " 2423 + bp.name + " owned by uid " + bp.uid); 2424 } 2425 } 2426 throw new SecurityException("No permission tree found for " + permName); 2427 } 2428 2429 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2430 if (s1 == null) { 2431 return s2 == null; 2432 } 2433 if (s2 == null) { 2434 return false; 2435 } 2436 if (s1.getClass() != s2.getClass()) { 2437 return false; 2438 } 2439 return s1.equals(s2); 2440 } 2441 2442 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2443 if (pi1.icon != pi2.icon) return false; 2444 if (pi1.logo != pi2.logo) return false; 2445 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2446 if (!compareStrings(pi1.name, pi2.name)) return false; 2447 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2448 // We'll take care of setting this one. 2449 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2450 // These are not currently stored in settings. 2451 //if (!compareStrings(pi1.group, pi2.group)) return false; 2452 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2453 //if (pi1.labelRes != pi2.labelRes) return false; 2454 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2455 return true; 2456 } 2457 2458 int permissionInfoFootprint(PermissionInfo info) { 2459 int size = info.name.length(); 2460 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2461 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2462 return size; 2463 } 2464 2465 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2466 int size = 0; 2467 for (BasePermission perm : mSettings.mPermissions.values()) { 2468 if (perm.uid == tree.uid) { 2469 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2470 } 2471 } 2472 return size; 2473 } 2474 2475 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2476 // We calculate the max size of permissions defined by this uid and throw 2477 // if that plus the size of 'info' would exceed our stated maximum. 2478 if (tree.uid != Process.SYSTEM_UID) { 2479 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2480 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2481 throw new SecurityException("Permission tree size cap exceeded"); 2482 } 2483 } 2484 } 2485 2486 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2487 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2488 throw new SecurityException("Label must be specified in permission"); 2489 } 2490 BasePermission tree = checkPermissionTreeLP(info.name); 2491 BasePermission bp = mSettings.mPermissions.get(info.name); 2492 boolean added = bp == null; 2493 boolean changed = true; 2494 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2495 if (added) { 2496 enforcePermissionCapLocked(info, tree); 2497 bp = new BasePermission(info.name, tree.sourcePackage, 2498 BasePermission.TYPE_DYNAMIC); 2499 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2500 throw new SecurityException( 2501 "Not allowed to modify non-dynamic permission " 2502 + info.name); 2503 } else { 2504 if (bp.protectionLevel == fixedLevel 2505 && bp.perm.owner.equals(tree.perm.owner) 2506 && bp.uid == tree.uid 2507 && comparePermissionInfos(bp.perm.info, info)) { 2508 changed = false; 2509 } 2510 } 2511 bp.protectionLevel = fixedLevel; 2512 info = new PermissionInfo(info); 2513 info.protectionLevel = fixedLevel; 2514 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2515 bp.perm.info.packageName = tree.perm.info.packageName; 2516 bp.uid = tree.uid; 2517 if (added) { 2518 mSettings.mPermissions.put(info.name, bp); 2519 } 2520 if (changed) { 2521 if (!async) { 2522 mSettings.writeLPr(); 2523 } else { 2524 scheduleWriteSettingsLocked(); 2525 } 2526 } 2527 return added; 2528 } 2529 2530 @Override 2531 public boolean addPermission(PermissionInfo info) { 2532 synchronized (mPackages) { 2533 return addPermissionLocked(info, false); 2534 } 2535 } 2536 2537 @Override 2538 public boolean addPermissionAsync(PermissionInfo info) { 2539 synchronized (mPackages) { 2540 return addPermissionLocked(info, true); 2541 } 2542 } 2543 2544 @Override 2545 public void removePermission(String name) { 2546 synchronized (mPackages) { 2547 checkPermissionTreeLP(name); 2548 BasePermission bp = mSettings.mPermissions.get(name); 2549 if (bp != null) { 2550 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2551 throw new SecurityException( 2552 "Not allowed to modify non-dynamic permission " 2553 + name); 2554 } 2555 mSettings.mPermissions.remove(name); 2556 mSettings.writeLPr(); 2557 } 2558 } 2559 } 2560 2561 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2562 int index = pkg.requestedPermissions.indexOf(bp.name); 2563 if (index == -1) { 2564 throw new SecurityException("Package " + pkg.packageName 2565 + " has not requested permission " + bp.name); 2566 } 2567 boolean isNormal = 2568 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2569 == PermissionInfo.PROTECTION_NORMAL); 2570 boolean isDangerous = 2571 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2572 == PermissionInfo.PROTECTION_DANGEROUS); 2573 boolean isDevelopment = 2574 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2575 2576 if (!isNormal && !isDangerous && !isDevelopment) { 2577 throw new SecurityException("Permission " + bp.name 2578 + " is not a changeable permission type"); 2579 } 2580 2581 if (isNormal || isDangerous) { 2582 if (pkg.requestedPermissionsRequired.get(index)) { 2583 throw new SecurityException("Can't change " + bp.name 2584 + ". It is required by the application"); 2585 } 2586 } 2587 } 2588 2589 @Override 2590 public void grantPermission(String packageName, String permissionName) { 2591 mContext.enforceCallingOrSelfPermission( 2592 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2593 synchronized (mPackages) { 2594 final PackageParser.Package pkg = mPackages.get(packageName); 2595 if (pkg == null) { 2596 throw new IllegalArgumentException("Unknown package: " + packageName); 2597 } 2598 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2599 if (bp == null) { 2600 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2601 } 2602 2603 checkGrantRevokePermissions(pkg, bp); 2604 2605 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2606 if (ps == null) { 2607 return; 2608 } 2609 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2610 if (gp.grantedPermissions.add(permissionName)) { 2611 if (ps.haveGids) { 2612 gp.gids = appendInts(gp.gids, bp.gids); 2613 } 2614 mSettings.writeLPr(); 2615 } 2616 } 2617 } 2618 2619 @Override 2620 public void revokePermission(String packageName, String permissionName) { 2621 int changedAppId = -1; 2622 2623 synchronized (mPackages) { 2624 final PackageParser.Package pkg = mPackages.get(packageName); 2625 if (pkg == null) { 2626 throw new IllegalArgumentException("Unknown package: " + packageName); 2627 } 2628 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2629 mContext.enforceCallingOrSelfPermission( 2630 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2631 } 2632 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2633 if (bp == null) { 2634 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2635 } 2636 2637 checkGrantRevokePermissions(pkg, bp); 2638 2639 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2640 if (ps == null) { 2641 return; 2642 } 2643 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2644 if (gp.grantedPermissions.remove(permissionName)) { 2645 gp.grantedPermissions.remove(permissionName); 2646 if (ps.haveGids) { 2647 gp.gids = removeInts(gp.gids, bp.gids); 2648 } 2649 mSettings.writeLPr(); 2650 changedAppId = ps.appId; 2651 } 2652 } 2653 2654 if (changedAppId >= 0) { 2655 // We changed the perm on someone, kill its processes. 2656 IActivityManager am = ActivityManagerNative.getDefault(); 2657 if (am != null) { 2658 final int callingUserId = UserHandle.getCallingUserId(); 2659 final long ident = Binder.clearCallingIdentity(); 2660 try { 2661 //XXX we should only revoke for the calling user's app permissions, 2662 // but for now we impact all users. 2663 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2664 // "revoke " + permissionName); 2665 int[] users = sUserManager.getUserIds(); 2666 for (int user : users) { 2667 am.killUid(UserHandle.getUid(user, changedAppId), 2668 "revoke " + permissionName); 2669 } 2670 } catch (RemoteException e) { 2671 } finally { 2672 Binder.restoreCallingIdentity(ident); 2673 } 2674 } 2675 } 2676 } 2677 2678 @Override 2679 public boolean isProtectedBroadcast(String actionName) { 2680 synchronized (mPackages) { 2681 return mProtectedBroadcasts.contains(actionName); 2682 } 2683 } 2684 2685 @Override 2686 public int checkSignatures(String pkg1, String pkg2) { 2687 synchronized (mPackages) { 2688 final PackageParser.Package p1 = mPackages.get(pkg1); 2689 final PackageParser.Package p2 = mPackages.get(pkg2); 2690 if (p1 == null || p1.mExtras == null 2691 || p2 == null || p2.mExtras == null) { 2692 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2693 } 2694 return compareSignatures(p1.mSignatures, p2.mSignatures); 2695 } 2696 } 2697 2698 @Override 2699 public int checkUidSignatures(int uid1, int uid2) { 2700 // Map to base uids. 2701 uid1 = UserHandle.getAppId(uid1); 2702 uid2 = UserHandle.getAppId(uid2); 2703 // reader 2704 synchronized (mPackages) { 2705 Signature[] s1; 2706 Signature[] s2; 2707 Object obj = mSettings.getUserIdLPr(uid1); 2708 if (obj != null) { 2709 if (obj instanceof SharedUserSetting) { 2710 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2711 } else if (obj instanceof PackageSetting) { 2712 s1 = ((PackageSetting)obj).signatures.mSignatures; 2713 } else { 2714 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2715 } 2716 } else { 2717 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2718 } 2719 obj = mSettings.getUserIdLPr(uid2); 2720 if (obj != null) { 2721 if (obj instanceof SharedUserSetting) { 2722 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2723 } else if (obj instanceof PackageSetting) { 2724 s2 = ((PackageSetting)obj).signatures.mSignatures; 2725 } else { 2726 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2727 } 2728 } else { 2729 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2730 } 2731 return compareSignatures(s1, s2); 2732 } 2733 } 2734 2735 /** 2736 * Compares two sets of signatures. Returns: 2737 * <br /> 2738 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2739 * <br /> 2740 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2741 * <br /> 2742 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2743 * <br /> 2744 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2745 * <br /> 2746 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2747 */ 2748 static int compareSignatures(Signature[] s1, Signature[] s2) { 2749 if (s1 == null) { 2750 return s2 == null 2751 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2752 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2753 } 2754 2755 if (s2 == null) { 2756 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2757 } 2758 2759 if (s1.length != s2.length) { 2760 return PackageManager.SIGNATURE_NO_MATCH; 2761 } 2762 2763 // Since both signature sets are of size 1, we can compare without HashSets. 2764 if (s1.length == 1) { 2765 return s1[0].equals(s2[0]) ? 2766 PackageManager.SIGNATURE_MATCH : 2767 PackageManager.SIGNATURE_NO_MATCH; 2768 } 2769 2770 HashSet<Signature> set1 = new HashSet<Signature>(); 2771 for (Signature sig : s1) { 2772 set1.add(sig); 2773 } 2774 HashSet<Signature> set2 = new HashSet<Signature>(); 2775 for (Signature sig : s2) { 2776 set2.add(sig); 2777 } 2778 // Make sure s2 contains all signatures in s1. 2779 if (set1.equals(set2)) { 2780 return PackageManager.SIGNATURE_MATCH; 2781 } 2782 return PackageManager.SIGNATURE_NO_MATCH; 2783 } 2784 2785 /** 2786 * If the database version for this type of package (internal storage or 2787 * external storage) is less than the version where package signatures 2788 * were updated, return true. 2789 */ 2790 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2791 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2792 DatabaseVersion.SIGNATURE_END_ENTITY)) 2793 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2794 DatabaseVersion.SIGNATURE_END_ENTITY)); 2795 } 2796 2797 /** 2798 * Used for backward compatibility to make sure any packages with 2799 * certificate chains get upgraded to the new style. {@code existingSigs} 2800 * will be in the old format (since they were stored on disk from before the 2801 * system upgrade) and {@code scannedSigs} will be in the newer format. 2802 */ 2803 private int compareSignaturesCompat(PackageSignatures existingSigs, 2804 PackageParser.Package scannedPkg) { 2805 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2806 return PackageManager.SIGNATURE_NO_MATCH; 2807 } 2808 2809 HashSet<Signature> existingSet = new HashSet<Signature>(); 2810 for (Signature sig : existingSigs.mSignatures) { 2811 existingSet.add(sig); 2812 } 2813 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2814 for (Signature sig : scannedPkg.mSignatures) { 2815 try { 2816 Signature[] chainSignatures = sig.getChainSignatures(); 2817 for (Signature chainSig : chainSignatures) { 2818 scannedCompatSet.add(chainSig); 2819 } 2820 } catch (CertificateEncodingException e) { 2821 scannedCompatSet.add(sig); 2822 } 2823 } 2824 /* 2825 * Make sure the expanded scanned set contains all signatures in the 2826 * existing one. 2827 */ 2828 if (scannedCompatSet.equals(existingSet)) { 2829 // Migrate the old signatures to the new scheme. 2830 existingSigs.assignSignatures(scannedPkg.mSignatures); 2831 // The new KeySets will be re-added later in the scanning process. 2832 mSettings.mKeySetManagerService.removeAppKeySetData(scannedPkg.packageName); 2833 return PackageManager.SIGNATURE_MATCH; 2834 } 2835 return PackageManager.SIGNATURE_NO_MATCH; 2836 } 2837 2838 @Override 2839 public String[] getPackagesForUid(int uid) { 2840 uid = UserHandle.getAppId(uid); 2841 // reader 2842 synchronized (mPackages) { 2843 Object obj = mSettings.getUserIdLPr(uid); 2844 if (obj instanceof SharedUserSetting) { 2845 final SharedUserSetting sus = (SharedUserSetting) obj; 2846 final int N = sus.packages.size(); 2847 final String[] res = new String[N]; 2848 final Iterator<PackageSetting> it = sus.packages.iterator(); 2849 int i = 0; 2850 while (it.hasNext()) { 2851 res[i++] = it.next().name; 2852 } 2853 return res; 2854 } else if (obj instanceof PackageSetting) { 2855 final PackageSetting ps = (PackageSetting) obj; 2856 return new String[] { ps.name }; 2857 } 2858 } 2859 return null; 2860 } 2861 2862 @Override 2863 public String getNameForUid(int uid) { 2864 // reader 2865 synchronized (mPackages) { 2866 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2867 if (obj instanceof SharedUserSetting) { 2868 final SharedUserSetting sus = (SharedUserSetting) obj; 2869 return sus.name + ":" + sus.userId; 2870 } else if (obj instanceof PackageSetting) { 2871 final PackageSetting ps = (PackageSetting) obj; 2872 return ps.name; 2873 } 2874 } 2875 return null; 2876 } 2877 2878 @Override 2879 public int getUidForSharedUser(String sharedUserName) { 2880 if(sharedUserName == null) { 2881 return -1; 2882 } 2883 // reader 2884 synchronized (mPackages) { 2885 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2886 if (suid == null) { 2887 return -1; 2888 } 2889 return suid.userId; 2890 } 2891 } 2892 2893 @Override 2894 public int getFlagsForUid(int uid) { 2895 synchronized (mPackages) { 2896 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2897 if (obj instanceof SharedUserSetting) { 2898 final SharedUserSetting sus = (SharedUserSetting) obj; 2899 return sus.pkgFlags; 2900 } else if (obj instanceof PackageSetting) { 2901 final PackageSetting ps = (PackageSetting) obj; 2902 return ps.pkgFlags; 2903 } 2904 } 2905 return 0; 2906 } 2907 2908 @Override 2909 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2910 int flags, int userId) { 2911 if (!sUserManager.exists(userId)) return null; 2912 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2913 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2914 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2915 } 2916 2917 @Override 2918 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2919 IntentFilter filter, int match, ComponentName activity) { 2920 final int userId = UserHandle.getCallingUserId(); 2921 if (DEBUG_PREFERRED) { 2922 Log.v(TAG, "setLastChosenActivity intent=" + intent 2923 + " resolvedType=" + resolvedType 2924 + " flags=" + flags 2925 + " filter=" + filter 2926 + " match=" + match 2927 + " activity=" + activity); 2928 filter.dump(new PrintStreamPrinter(System.out), " "); 2929 } 2930 intent.setComponent(null); 2931 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2932 // Find any earlier preferred or last chosen entries and nuke them 2933 findPreferredActivity(intent, resolvedType, 2934 flags, query, 0, false, true, false, userId); 2935 // Add the new activity as the last chosen for this filter 2936 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2937 } 2938 2939 @Override 2940 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2941 final int userId = UserHandle.getCallingUserId(); 2942 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2943 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2944 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2945 false, false, false, userId); 2946 } 2947 2948 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2949 int flags, List<ResolveInfo> query, int userId) { 2950 if (query != null) { 2951 final int N = query.size(); 2952 if (N == 1) { 2953 return query.get(0); 2954 } else if (N > 1) { 2955 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2956 // If there is more than one activity with the same priority, 2957 // then let the user decide between them. 2958 ResolveInfo r0 = query.get(0); 2959 ResolveInfo r1 = query.get(1); 2960 if (DEBUG_INTENT_MATCHING || debug) { 2961 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2962 + r1.activityInfo.name + "=" + r1.priority); 2963 } 2964 // If the first activity has a higher priority, or a different 2965 // default, then it is always desireable to pick it. 2966 if (r0.priority != r1.priority 2967 || r0.preferredOrder != r1.preferredOrder 2968 || r0.isDefault != r1.isDefault) { 2969 return query.get(0); 2970 } 2971 // If we have saved a preference for a preferred activity for 2972 // this Intent, use that. 2973 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2974 flags, query, r0.priority, true, false, debug, userId); 2975 if (ri != null) { 2976 return ri; 2977 } 2978 if (userId != 0) { 2979 ri = new ResolveInfo(mResolveInfo); 2980 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2981 ri.activityInfo.applicationInfo = new ApplicationInfo( 2982 ri.activityInfo.applicationInfo); 2983 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2984 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2985 return ri; 2986 } 2987 return mResolveInfo; 2988 } 2989 } 2990 return null; 2991 } 2992 2993 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2994 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2995 final int N = query.size(); 2996 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2997 .get(userId); 2998 // Get the list of persistent preferred activities that handle the intent 2999 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3000 List<PersistentPreferredActivity> pprefs = ppir != null 3001 ? ppir.queryIntent(intent, resolvedType, 3002 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3003 : null; 3004 if (pprefs != null && pprefs.size() > 0) { 3005 final int M = pprefs.size(); 3006 for (int i=0; i<M; i++) { 3007 final PersistentPreferredActivity ppa = pprefs.get(i); 3008 if (DEBUG_PREFERRED || debug) { 3009 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3010 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3011 + "\n component=" + ppa.mComponent); 3012 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3013 } 3014 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3015 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3016 if (DEBUG_PREFERRED || debug) { 3017 Slog.v(TAG, "Found persistent preferred activity:"); 3018 if (ai != null) { 3019 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3020 } else { 3021 Slog.v(TAG, " null"); 3022 } 3023 } 3024 if (ai == null) { 3025 // This previously registered persistent preferred activity 3026 // component is no longer known. Ignore it and do NOT remove it. 3027 continue; 3028 } 3029 for (int j=0; j<N; j++) { 3030 final ResolveInfo ri = query.get(j); 3031 if (!ri.activityInfo.applicationInfo.packageName 3032 .equals(ai.applicationInfo.packageName)) { 3033 continue; 3034 } 3035 if (!ri.activityInfo.name.equals(ai.name)) { 3036 continue; 3037 } 3038 // Found a persistent preference that can handle the intent. 3039 if (DEBUG_PREFERRED || debug) { 3040 Slog.v(TAG, "Returning persistent preferred activity: " + 3041 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3042 } 3043 return ri; 3044 } 3045 } 3046 } 3047 return null; 3048 } 3049 3050 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3051 List<ResolveInfo> query, int priority, boolean always, 3052 boolean removeMatches, boolean debug, int userId) { 3053 if (!sUserManager.exists(userId)) return null; 3054 // writer 3055 synchronized (mPackages) { 3056 if (intent.getSelector() != null) { 3057 intent = intent.getSelector(); 3058 } 3059 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3060 3061 // Try to find a matching persistent preferred activity. 3062 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3063 debug, userId); 3064 3065 // If a persistent preferred activity matched, use it. 3066 if (pri != null) { 3067 return pri; 3068 } 3069 3070 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3071 // Get the list of preferred activities that handle the intent 3072 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3073 List<PreferredActivity> prefs = pir != null 3074 ? pir.queryIntent(intent, resolvedType, 3075 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3076 : null; 3077 if (prefs != null && prefs.size() > 0) { 3078 // First figure out how good the original match set is. 3079 // We will only allow preferred activities that came 3080 // from the same match quality. 3081 int match = 0; 3082 3083 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3084 3085 final int N = query.size(); 3086 for (int j=0; j<N; j++) { 3087 final ResolveInfo ri = query.get(j); 3088 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3089 + ": 0x" + Integer.toHexString(match)); 3090 if (ri.match > match) { 3091 match = ri.match; 3092 } 3093 } 3094 3095 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3096 + Integer.toHexString(match)); 3097 3098 match &= IntentFilter.MATCH_CATEGORY_MASK; 3099 final int M = prefs.size(); 3100 for (int i=0; i<M; i++) { 3101 final PreferredActivity pa = prefs.get(i); 3102 if (DEBUG_PREFERRED || debug) { 3103 Slog.v(TAG, "Checking PreferredActivity ds=" 3104 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3105 + "\n component=" + pa.mPref.mComponent); 3106 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3107 } 3108 if (pa.mPref.mMatch != match) { 3109 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3110 + Integer.toHexString(pa.mPref.mMatch)); 3111 continue; 3112 } 3113 // If it's not an "always" type preferred activity and that's what we're 3114 // looking for, skip it. 3115 if (always && !pa.mPref.mAlways) { 3116 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3117 continue; 3118 } 3119 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3120 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3121 if (DEBUG_PREFERRED || debug) { 3122 Slog.v(TAG, "Found preferred activity:"); 3123 if (ai != null) { 3124 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3125 } else { 3126 Slog.v(TAG, " null"); 3127 } 3128 } 3129 if (ai == null) { 3130 // This previously registered preferred activity 3131 // component is no longer known. Most likely an update 3132 // to the app was installed and in the new version this 3133 // component no longer exists. Clean it up by removing 3134 // it from the preferred activities list, and skip it. 3135 Slog.w(TAG, "Removing dangling preferred activity: " 3136 + pa.mPref.mComponent); 3137 pir.removeFilter(pa); 3138 continue; 3139 } 3140 for (int j=0; j<N; j++) { 3141 final ResolveInfo ri = query.get(j); 3142 if (!ri.activityInfo.applicationInfo.packageName 3143 .equals(ai.applicationInfo.packageName)) { 3144 continue; 3145 } 3146 if (!ri.activityInfo.name.equals(ai.name)) { 3147 continue; 3148 } 3149 3150 if (removeMatches) { 3151 pir.removeFilter(pa); 3152 if (DEBUG_PREFERRED) { 3153 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3154 } 3155 break; 3156 } 3157 3158 // Okay we found a previously set preferred or last chosen app. 3159 // If the result set is different from when this 3160 // was created, we need to clear it and re-ask the 3161 // user their preference, if we're looking for an "always" type entry. 3162 if (always && !pa.mPref.sameSet(query, priority)) { 3163 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3164 + intent + " type " + resolvedType); 3165 if (DEBUG_PREFERRED) { 3166 Slog.v(TAG, "Removing preferred activity since set changed " 3167 + pa.mPref.mComponent); 3168 } 3169 pir.removeFilter(pa); 3170 // Re-add the filter as a "last chosen" entry (!always) 3171 PreferredActivity lastChosen = new PreferredActivity( 3172 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3173 pir.addFilter(lastChosen); 3174 mSettings.writePackageRestrictionsLPr(userId); 3175 return null; 3176 } 3177 3178 // Yay! Either the set matched or we're looking for the last chosen 3179 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3180 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3181 mSettings.writePackageRestrictionsLPr(userId); 3182 return ri; 3183 } 3184 } 3185 } 3186 mSettings.writePackageRestrictionsLPr(userId); 3187 } 3188 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3189 return null; 3190 } 3191 3192 /* 3193 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3194 */ 3195 @Override 3196 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3197 int targetUserId) { 3198 mContext.enforceCallingOrSelfPermission( 3199 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3200 List<CrossProfileIntentFilter> matches = 3201 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3202 if (matches != null) { 3203 int size = matches.size(); 3204 for (int i = 0; i < size; i++) { 3205 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3206 } 3207 } 3208 3209 ArrayList<String> packageNames = null; 3210 SparseArray<ArrayList<String>> fromSource = 3211 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3212 if (fromSource != null) { 3213 packageNames = fromSource.get(targetUserId); 3214 } 3215 if (packageNames.contains(intent.getPackage())) { 3216 return true; 3217 } 3218 // We need the package name, so we try to resolve with the loosest flags possible 3219 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3220 intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3221 int count = resolveInfos.size(); 3222 for (int i = 0; i < count; i++) { 3223 ResolveInfo resolveInfo = resolveInfos.get(i); 3224 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3225 return true; 3226 } 3227 } 3228 return false; 3229 } 3230 3231 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3232 String resolvedType, int userId) { 3233 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3234 if (resolver != null) { 3235 return resolver.queryIntent(intent, resolvedType, false, userId); 3236 } 3237 return null; 3238 } 3239 3240 @Override 3241 public List<ResolveInfo> queryIntentActivities(Intent intent, 3242 String resolvedType, int flags, int userId) { 3243 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3244 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3245 ComponentName comp = intent.getComponent(); 3246 if (comp == null) { 3247 if (intent.getSelector() != null) { 3248 intent = intent.getSelector(); 3249 comp = intent.getComponent(); 3250 } 3251 } 3252 3253 if (comp != null) { 3254 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3255 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3256 if (ai != null) { 3257 final ResolveInfo ri = new ResolveInfo(); 3258 ri.activityInfo = ai; 3259 list.add(ri); 3260 } 3261 return list; 3262 } 3263 3264 // reader 3265 synchronized (mPackages) { 3266 final String pkgName = intent.getPackage(); 3267 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3268 if (pkgName == null) { 3269 ResolveInfo resolveInfo = null; 3270 if (queryCrossProfile) { 3271 // Check if the intent needs to be forwarded to another user for this package 3272 ArrayList<ResolveInfo> crossProfileResult = 3273 queryIntentActivitiesCrossProfilePackage( 3274 intent, resolvedType, flags, userId); 3275 if (!crossProfileResult.isEmpty()) { 3276 // Skip the current profile 3277 return crossProfileResult; 3278 } 3279 List<CrossProfileIntentFilter> matchingFilters = 3280 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3281 // Check for results that need to skip the current profile. 3282 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3283 resolvedType, flags, userId); 3284 if (resolveInfo != null) { 3285 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3286 result.add(resolveInfo); 3287 return result; 3288 } 3289 // Check for cross profile results. 3290 resolveInfo = queryCrossProfileIntents( 3291 matchingFilters, intent, resolvedType, flags, userId); 3292 } 3293 // Check for results in the current profile. 3294 List<ResolveInfo> result = mActivities.queryIntent( 3295 intent, resolvedType, flags, userId); 3296 if (resolveInfo != null) { 3297 result.add(resolveInfo); 3298 } 3299 return result; 3300 } 3301 final PackageParser.Package pkg = mPackages.get(pkgName); 3302 if (pkg != null) { 3303 if (queryCrossProfile) { 3304 ArrayList<ResolveInfo> crossProfileResult = 3305 queryIntentActivitiesCrossProfilePackage( 3306 intent, resolvedType, flags, userId, pkg, pkgName); 3307 if (!crossProfileResult.isEmpty()) { 3308 // Skip the current profile 3309 return crossProfileResult; 3310 } 3311 } 3312 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3313 pkg.activities, userId); 3314 } 3315 return new ArrayList<ResolveInfo>(); 3316 } 3317 } 3318 3319 private ResolveInfo querySkipCurrentProfileIntents( 3320 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3321 int flags, int sourceUserId) { 3322 if (matchingFilters != null) { 3323 int size = matchingFilters.size(); 3324 for (int i = 0; i < size; i ++) { 3325 CrossProfileIntentFilter filter = matchingFilters.get(i); 3326 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3327 // Checking if there are activities in the target user that can handle the 3328 // intent. 3329 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3330 flags, sourceUserId); 3331 if (resolveInfo != null) { 3332 return resolveInfo; 3333 } 3334 } 3335 } 3336 } 3337 return null; 3338 } 3339 3340 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3341 Intent intent, String resolvedType, int flags, int userId) { 3342 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3343 SparseArray<ArrayList<String>> sourceForwardingInfo = 3344 mSettings.mCrossProfilePackageInfo.get(userId); 3345 if (sourceForwardingInfo != null) { 3346 int NI = sourceForwardingInfo.size(); 3347 for (int i = 0; i < NI; i++) { 3348 int targetUserId = sourceForwardingInfo.keyAt(i); 3349 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3350 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3351 intent, resolvedType, flags, targetUserId); 3352 int NJ = resolveInfos.size(); 3353 for (int j = 0; j < NJ; j++) { 3354 ResolveInfo resolveInfo = resolveInfos.get(j); 3355 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3356 matchingResolveInfos.add(createForwardingResolveInfo( 3357 resolveInfo.filter, userId, targetUserId)); 3358 } 3359 } 3360 } 3361 } 3362 return matchingResolveInfos; 3363 } 3364 3365 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3366 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3367 String packageName) { 3368 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3369 SparseArray<ArrayList<String>> sourceForwardingInfo = 3370 mSettings.mCrossProfilePackageInfo.get(userId); 3371 if (sourceForwardingInfo != null) { 3372 int NI = sourceForwardingInfo.size(); 3373 for (int i = 0; i < NI; i++) { 3374 int targetUserId = sourceForwardingInfo.keyAt(i); 3375 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3376 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3377 intent, resolvedType, flags, pkg.activities, targetUserId); 3378 int NJ = resolveInfos.size(); 3379 for (int j = 0; j < NJ; j++) { 3380 ResolveInfo resolveInfo = resolveInfos.get(j); 3381 matchingResolveInfos.add(createForwardingResolveInfo( 3382 resolveInfo.filter, userId, targetUserId)); 3383 } 3384 } 3385 } 3386 } 3387 return matchingResolveInfos; 3388 } 3389 3390 // Return matching ResolveInfo if any for skip current profile intent filters. 3391 private ResolveInfo queryCrossProfileIntents( 3392 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3393 int flags, int sourceUserId) { 3394 if (matchingFilters != null) { 3395 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3396 // match the same intent. For performance reasons, it is better not to 3397 // run queryIntent twice for the same userId 3398 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3399 int size = matchingFilters.size(); 3400 for (int i = 0; i < size; i++) { 3401 CrossProfileIntentFilter filter = matchingFilters.get(i); 3402 int targetUserId = filter.getTargetUserId(); 3403 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3404 && !alreadyTriedUserIds.get(targetUserId)) { 3405 // Checking if there are activities in the target user that can handle the 3406 // intent. 3407 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3408 flags, sourceUserId); 3409 if (resolveInfo != null) return resolveInfo; 3410 alreadyTriedUserIds.put(targetUserId, true); 3411 } 3412 } 3413 } 3414 return null; 3415 } 3416 3417 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3418 String resolvedType, int flags, int sourceUserId) { 3419 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3420 resolvedType, flags, filter.getTargetUserId()); 3421 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3422 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3423 } 3424 return null; 3425 } 3426 3427 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3428 int sourceUserId, int targetUserId) { 3429 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3430 String className; 3431 if (targetUserId == UserHandle.USER_OWNER) { 3432 className = FORWARD_INTENT_TO_USER_OWNER; 3433 } else { 3434 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3435 } 3436 ComponentName forwardingActivityComponentName = new ComponentName( 3437 mAndroidApplication.packageName, className); 3438 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3439 sourceUserId); 3440 if (targetUserId == UserHandle.USER_OWNER) { 3441 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3442 forwardingResolveInfo.noResourceId = true; 3443 } 3444 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3445 forwardingResolveInfo.priority = 0; 3446 forwardingResolveInfo.preferredOrder = 0; 3447 forwardingResolveInfo.match = 0; 3448 forwardingResolveInfo.isDefault = true; 3449 forwardingResolveInfo.filter = filter; 3450 forwardingResolveInfo.targetUserId = targetUserId; 3451 return forwardingResolveInfo; 3452 } 3453 3454 @Override 3455 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3456 Intent[] specifics, String[] specificTypes, Intent intent, 3457 String resolvedType, int flags, int userId) { 3458 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3459 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3460 "query intent activity options"); 3461 final String resultsAction = intent.getAction(); 3462 3463 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3464 | PackageManager.GET_RESOLVED_FILTER, userId); 3465 3466 if (DEBUG_INTENT_MATCHING) { 3467 Log.v(TAG, "Query " + intent + ": " + results); 3468 } 3469 3470 int specificsPos = 0; 3471 int N; 3472 3473 // todo: note that the algorithm used here is O(N^2). This 3474 // isn't a problem in our current environment, but if we start running 3475 // into situations where we have more than 5 or 10 matches then this 3476 // should probably be changed to something smarter... 3477 3478 // First we go through and resolve each of the specific items 3479 // that were supplied, taking care of removing any corresponding 3480 // duplicate items in the generic resolve list. 3481 if (specifics != null) { 3482 for (int i=0; i<specifics.length; i++) { 3483 final Intent sintent = specifics[i]; 3484 if (sintent == null) { 3485 continue; 3486 } 3487 3488 if (DEBUG_INTENT_MATCHING) { 3489 Log.v(TAG, "Specific #" + i + ": " + sintent); 3490 } 3491 3492 String action = sintent.getAction(); 3493 if (resultsAction != null && resultsAction.equals(action)) { 3494 // If this action was explicitly requested, then don't 3495 // remove things that have it. 3496 action = null; 3497 } 3498 3499 ResolveInfo ri = null; 3500 ActivityInfo ai = null; 3501 3502 ComponentName comp = sintent.getComponent(); 3503 if (comp == null) { 3504 ri = resolveIntent( 3505 sintent, 3506 specificTypes != null ? specificTypes[i] : null, 3507 flags, userId); 3508 if (ri == null) { 3509 continue; 3510 } 3511 if (ri == mResolveInfo) { 3512 // ACK! Must do something better with this. 3513 } 3514 ai = ri.activityInfo; 3515 comp = new ComponentName(ai.applicationInfo.packageName, 3516 ai.name); 3517 } else { 3518 ai = getActivityInfo(comp, flags, userId); 3519 if (ai == null) { 3520 continue; 3521 } 3522 } 3523 3524 // Look for any generic query activities that are duplicates 3525 // of this specific one, and remove them from the results. 3526 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3527 N = results.size(); 3528 int j; 3529 for (j=specificsPos; j<N; j++) { 3530 ResolveInfo sri = results.get(j); 3531 if ((sri.activityInfo.name.equals(comp.getClassName()) 3532 && sri.activityInfo.applicationInfo.packageName.equals( 3533 comp.getPackageName())) 3534 || (action != null && sri.filter.matchAction(action))) { 3535 results.remove(j); 3536 if (DEBUG_INTENT_MATCHING) Log.v( 3537 TAG, "Removing duplicate item from " + j 3538 + " due to specific " + specificsPos); 3539 if (ri == null) { 3540 ri = sri; 3541 } 3542 j--; 3543 N--; 3544 } 3545 } 3546 3547 // Add this specific item to its proper place. 3548 if (ri == null) { 3549 ri = new ResolveInfo(); 3550 ri.activityInfo = ai; 3551 } 3552 results.add(specificsPos, ri); 3553 ri.specificIndex = i; 3554 specificsPos++; 3555 } 3556 } 3557 3558 // Now we go through the remaining generic results and remove any 3559 // duplicate actions that are found here. 3560 N = results.size(); 3561 for (int i=specificsPos; i<N-1; i++) { 3562 final ResolveInfo rii = results.get(i); 3563 if (rii.filter == null) { 3564 continue; 3565 } 3566 3567 // Iterate over all of the actions of this result's intent 3568 // filter... typically this should be just one. 3569 final Iterator<String> it = rii.filter.actionsIterator(); 3570 if (it == null) { 3571 continue; 3572 } 3573 while (it.hasNext()) { 3574 final String action = it.next(); 3575 if (resultsAction != null && resultsAction.equals(action)) { 3576 // If this action was explicitly requested, then don't 3577 // remove things that have it. 3578 continue; 3579 } 3580 for (int j=i+1; j<N; j++) { 3581 final ResolveInfo rij = results.get(j); 3582 if (rij.filter != null && rij.filter.hasAction(action)) { 3583 results.remove(j); 3584 if (DEBUG_INTENT_MATCHING) Log.v( 3585 TAG, "Removing duplicate item from " + j 3586 + " due to action " + action + " at " + i); 3587 j--; 3588 N--; 3589 } 3590 } 3591 } 3592 3593 // If the caller didn't request filter information, drop it now 3594 // so we don't have to marshall/unmarshall it. 3595 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3596 rii.filter = null; 3597 } 3598 } 3599 3600 // Filter out the caller activity if so requested. 3601 if (caller != null) { 3602 N = results.size(); 3603 for (int i=0; i<N; i++) { 3604 ActivityInfo ainfo = results.get(i).activityInfo; 3605 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3606 && caller.getClassName().equals(ainfo.name)) { 3607 results.remove(i); 3608 break; 3609 } 3610 } 3611 } 3612 3613 // If the caller didn't request filter information, 3614 // drop them now so we don't have to 3615 // marshall/unmarshall it. 3616 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3617 N = results.size(); 3618 for (int i=0; i<N; i++) { 3619 results.get(i).filter = null; 3620 } 3621 } 3622 3623 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3624 return results; 3625 } 3626 3627 @Override 3628 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3629 int userId) { 3630 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3631 ComponentName comp = intent.getComponent(); 3632 if (comp == null) { 3633 if (intent.getSelector() != null) { 3634 intent = intent.getSelector(); 3635 comp = intent.getComponent(); 3636 } 3637 } 3638 if (comp != null) { 3639 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3640 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3641 if (ai != null) { 3642 ResolveInfo ri = new ResolveInfo(); 3643 ri.activityInfo = ai; 3644 list.add(ri); 3645 } 3646 return list; 3647 } 3648 3649 // reader 3650 synchronized (mPackages) { 3651 String pkgName = intent.getPackage(); 3652 if (pkgName == null) { 3653 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3654 } 3655 final PackageParser.Package pkg = mPackages.get(pkgName); 3656 if (pkg != null) { 3657 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3658 userId); 3659 } 3660 return null; 3661 } 3662 } 3663 3664 @Override 3665 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3666 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3667 if (!sUserManager.exists(userId)) return null; 3668 if (query != null) { 3669 if (query.size() >= 1) { 3670 // If there is more than one service with the same priority, 3671 // just arbitrarily pick the first one. 3672 return query.get(0); 3673 } 3674 } 3675 return null; 3676 } 3677 3678 @Override 3679 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3680 int userId) { 3681 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3682 ComponentName comp = intent.getComponent(); 3683 if (comp == null) { 3684 if (intent.getSelector() != null) { 3685 intent = intent.getSelector(); 3686 comp = intent.getComponent(); 3687 } 3688 } 3689 if (comp != null) { 3690 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3691 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3692 if (si != null) { 3693 final ResolveInfo ri = new ResolveInfo(); 3694 ri.serviceInfo = si; 3695 list.add(ri); 3696 } 3697 return list; 3698 } 3699 3700 // reader 3701 synchronized (mPackages) { 3702 String pkgName = intent.getPackage(); 3703 if (pkgName == null) { 3704 return mServices.queryIntent(intent, resolvedType, flags, userId); 3705 } 3706 final PackageParser.Package pkg = mPackages.get(pkgName); 3707 if (pkg != null) { 3708 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3709 userId); 3710 } 3711 return null; 3712 } 3713 } 3714 3715 @Override 3716 public List<ResolveInfo> queryIntentContentProviders( 3717 Intent intent, String resolvedType, int flags, int userId) { 3718 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3719 ComponentName comp = intent.getComponent(); 3720 if (comp == null) { 3721 if (intent.getSelector() != null) { 3722 intent = intent.getSelector(); 3723 comp = intent.getComponent(); 3724 } 3725 } 3726 if (comp != null) { 3727 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3728 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3729 if (pi != null) { 3730 final ResolveInfo ri = new ResolveInfo(); 3731 ri.providerInfo = pi; 3732 list.add(ri); 3733 } 3734 return list; 3735 } 3736 3737 // reader 3738 synchronized (mPackages) { 3739 String pkgName = intent.getPackage(); 3740 if (pkgName == null) { 3741 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3742 } 3743 final PackageParser.Package pkg = mPackages.get(pkgName); 3744 if (pkg != null) { 3745 return mProviders.queryIntentForPackage( 3746 intent, resolvedType, flags, pkg.providers, userId); 3747 } 3748 return null; 3749 } 3750 } 3751 3752 @Override 3753 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3754 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3755 3756 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3757 3758 // writer 3759 synchronized (mPackages) { 3760 ArrayList<PackageInfo> list; 3761 if (listUninstalled) { 3762 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3763 for (PackageSetting ps : mSettings.mPackages.values()) { 3764 PackageInfo pi; 3765 if (ps.pkg != null) { 3766 pi = generatePackageInfo(ps.pkg, flags, userId); 3767 } else { 3768 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3769 } 3770 if (pi != null) { 3771 list.add(pi); 3772 } 3773 } 3774 } else { 3775 list = new ArrayList<PackageInfo>(mPackages.size()); 3776 for (PackageParser.Package p : mPackages.values()) { 3777 PackageInfo pi = generatePackageInfo(p, flags, userId); 3778 if (pi != null) { 3779 list.add(pi); 3780 } 3781 } 3782 } 3783 3784 return new ParceledListSlice<PackageInfo>(list); 3785 } 3786 } 3787 3788 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3789 String[] permissions, boolean[] tmp, int flags, int userId) { 3790 int numMatch = 0; 3791 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3792 for (int i=0; i<permissions.length; i++) { 3793 if (gp.grantedPermissions.contains(permissions[i])) { 3794 tmp[i] = true; 3795 numMatch++; 3796 } else { 3797 tmp[i] = false; 3798 } 3799 } 3800 if (numMatch == 0) { 3801 return; 3802 } 3803 PackageInfo pi; 3804 if (ps.pkg != null) { 3805 pi = generatePackageInfo(ps.pkg, flags, userId); 3806 } else { 3807 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3808 } 3809 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3810 if (numMatch == permissions.length) { 3811 pi.requestedPermissions = permissions; 3812 } else { 3813 pi.requestedPermissions = new String[numMatch]; 3814 numMatch = 0; 3815 for (int i=0; i<permissions.length; i++) { 3816 if (tmp[i]) { 3817 pi.requestedPermissions[numMatch] = permissions[i]; 3818 numMatch++; 3819 } 3820 } 3821 } 3822 } 3823 list.add(pi); 3824 } 3825 3826 @Override 3827 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3828 String[] permissions, int flags, int userId) { 3829 if (!sUserManager.exists(userId)) return null; 3830 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3831 3832 // writer 3833 synchronized (mPackages) { 3834 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3835 boolean[] tmpBools = new boolean[permissions.length]; 3836 if (listUninstalled) { 3837 for (PackageSetting ps : mSettings.mPackages.values()) { 3838 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3839 } 3840 } else { 3841 for (PackageParser.Package pkg : mPackages.values()) { 3842 PackageSetting ps = (PackageSetting)pkg.mExtras; 3843 if (ps != null) { 3844 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3845 userId); 3846 } 3847 } 3848 } 3849 3850 return new ParceledListSlice<PackageInfo>(list); 3851 } 3852 } 3853 3854 @Override 3855 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3856 if (!sUserManager.exists(userId)) return null; 3857 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3858 3859 // writer 3860 synchronized (mPackages) { 3861 ArrayList<ApplicationInfo> list; 3862 if (listUninstalled) { 3863 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3864 for (PackageSetting ps : mSettings.mPackages.values()) { 3865 ApplicationInfo ai; 3866 if (ps.pkg != null) { 3867 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3868 ps.readUserState(userId), userId); 3869 } else { 3870 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3871 } 3872 if (ai != null) { 3873 list.add(ai); 3874 } 3875 } 3876 } else { 3877 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3878 for (PackageParser.Package p : mPackages.values()) { 3879 if (p.mExtras != null) { 3880 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3881 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3882 if (ai != null) { 3883 list.add(ai); 3884 } 3885 } 3886 } 3887 } 3888 3889 return new ParceledListSlice<ApplicationInfo>(list); 3890 } 3891 } 3892 3893 public List<ApplicationInfo> getPersistentApplications(int flags) { 3894 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3895 3896 // reader 3897 synchronized (mPackages) { 3898 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3899 final int userId = UserHandle.getCallingUserId(); 3900 while (i.hasNext()) { 3901 final PackageParser.Package p = i.next(); 3902 if (p.applicationInfo != null 3903 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3904 && (!mSafeMode || isSystemApp(p))) { 3905 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3906 if (ps != null) { 3907 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3908 ps.readUserState(userId), userId); 3909 if (ai != null) { 3910 finalList.add(ai); 3911 } 3912 } 3913 } 3914 } 3915 } 3916 3917 return finalList; 3918 } 3919 3920 @Override 3921 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3922 if (!sUserManager.exists(userId)) return null; 3923 // reader 3924 synchronized (mPackages) { 3925 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3926 PackageSetting ps = provider != null 3927 ? mSettings.mPackages.get(provider.owner.packageName) 3928 : null; 3929 return ps != null 3930 && mSettings.isEnabledLPr(provider.info, flags, userId) 3931 && (!mSafeMode || (provider.info.applicationInfo.flags 3932 &ApplicationInfo.FLAG_SYSTEM) != 0) 3933 ? PackageParser.generateProviderInfo(provider, flags, 3934 ps.readUserState(userId), userId) 3935 : null; 3936 } 3937 } 3938 3939 /** 3940 * @deprecated 3941 */ 3942 @Deprecated 3943 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3944 // reader 3945 synchronized (mPackages) { 3946 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3947 .entrySet().iterator(); 3948 final int userId = UserHandle.getCallingUserId(); 3949 while (i.hasNext()) { 3950 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3951 PackageParser.Provider p = entry.getValue(); 3952 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3953 3954 if (ps != null && p.syncable 3955 && (!mSafeMode || (p.info.applicationInfo.flags 3956 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3957 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3958 ps.readUserState(userId), userId); 3959 if (info != null) { 3960 outNames.add(entry.getKey()); 3961 outInfo.add(info); 3962 } 3963 } 3964 } 3965 } 3966 } 3967 3968 @Override 3969 public List<ProviderInfo> queryContentProviders(String processName, 3970 int uid, int flags) { 3971 ArrayList<ProviderInfo> finalList = null; 3972 // reader 3973 synchronized (mPackages) { 3974 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3975 final int userId = processName != null ? 3976 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3977 while (i.hasNext()) { 3978 final PackageParser.Provider p = i.next(); 3979 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3980 if (ps != null && p.info.authority != null 3981 && (processName == null 3982 || (p.info.processName.equals(processName) 3983 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3984 && mSettings.isEnabledLPr(p.info, flags, userId) 3985 && (!mSafeMode 3986 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3987 if (finalList == null) { 3988 finalList = new ArrayList<ProviderInfo>(3); 3989 } 3990 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3991 ps.readUserState(userId), userId); 3992 if (info != null) { 3993 finalList.add(info); 3994 } 3995 } 3996 } 3997 } 3998 3999 if (finalList != null) { 4000 Collections.sort(finalList, mProviderInitOrderSorter); 4001 } 4002 4003 return finalList; 4004 } 4005 4006 @Override 4007 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4008 int flags) { 4009 // reader 4010 synchronized (mPackages) { 4011 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4012 return PackageParser.generateInstrumentationInfo(i, flags); 4013 } 4014 } 4015 4016 @Override 4017 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4018 int flags) { 4019 ArrayList<InstrumentationInfo> finalList = 4020 new ArrayList<InstrumentationInfo>(); 4021 4022 // reader 4023 synchronized (mPackages) { 4024 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4025 while (i.hasNext()) { 4026 final PackageParser.Instrumentation p = i.next(); 4027 if (targetPackage == null 4028 || targetPackage.equals(p.info.targetPackage)) { 4029 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4030 flags); 4031 if (ii != null) { 4032 finalList.add(ii); 4033 } 4034 } 4035 } 4036 } 4037 4038 return finalList; 4039 } 4040 4041 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4042 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4043 if (overlays == null) { 4044 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4045 return; 4046 } 4047 for (PackageParser.Package opkg : overlays.values()) { 4048 // Not much to do if idmap fails: we already logged the error 4049 // and we certainly don't want to abort installation of pkg simply 4050 // because an overlay didn't fit properly. For these reasons, 4051 // ignore the return value of createIdmapForPackagePairLI. 4052 createIdmapForPackagePairLI(pkg, opkg); 4053 } 4054 } 4055 4056 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4057 PackageParser.Package opkg) { 4058 if (!opkg.mTrustedOverlay) { 4059 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4060 opkg.baseCodePath + ": overlay not trusted"); 4061 return false; 4062 } 4063 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4064 if (overlaySet == null) { 4065 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4066 opkg.baseCodePath + " but target package has no known overlays"); 4067 return false; 4068 } 4069 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4070 // TODO: generate idmap for split APKs 4071 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4072 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4073 + opkg.baseCodePath); 4074 return false; 4075 } 4076 PackageParser.Package[] overlayArray = 4077 overlaySet.values().toArray(new PackageParser.Package[0]); 4078 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4079 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4080 return p1.mOverlayPriority - p2.mOverlayPriority; 4081 } 4082 }; 4083 Arrays.sort(overlayArray, cmp); 4084 4085 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4086 int i = 0; 4087 for (PackageParser.Package p : overlayArray) { 4088 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4089 } 4090 return true; 4091 } 4092 4093 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4094 final File[] files = dir.listFiles(); 4095 if (ArrayUtils.isEmpty(files)) { 4096 Log.d(TAG, "No files in app dir " + dir); 4097 return; 4098 } 4099 4100 if (DEBUG_PACKAGE_SCANNING) { 4101 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4102 + " flags=0x" + Integer.toHexString(flags)); 4103 } 4104 4105 for (File file : files) { 4106 final boolean isPackage = isApkFile(file) || file.isDirectory(); 4107 if (!isPackage) { 4108 // Ignore entries which are not apk's 4109 continue; 4110 } 4111 PackageParser.Package pkg = scanPackageLI(file, 4112 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null, null); 4113 // Don't mess around with apps in system partition. 4114 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4115 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) { 4116 // Delete the apk 4117 Slog.w(TAG, "Cleaning up failed install of " + file); 4118 file.delete(); 4119 } 4120 } 4121 } 4122 4123 private static File getSettingsProblemFile() { 4124 File dataDir = Environment.getDataDirectory(); 4125 File systemDir = new File(dataDir, "system"); 4126 File fname = new File(systemDir, "uiderrors.txt"); 4127 return fname; 4128 } 4129 4130 static void reportSettingsProblem(int priority, String msg) { 4131 try { 4132 File fname = getSettingsProblemFile(); 4133 FileOutputStream out = new FileOutputStream(fname, true); 4134 PrintWriter pw = new FastPrintWriter(out); 4135 SimpleDateFormat formatter = new SimpleDateFormat(); 4136 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4137 pw.println(dateString + ": " + msg); 4138 pw.close(); 4139 FileUtils.setPermissions( 4140 fname.toString(), 4141 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4142 -1, -1); 4143 } catch (java.io.IOException e) { 4144 } 4145 Slog.println(priority, TAG, msg); 4146 } 4147 4148 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps, 4149 PackageParser.Package pkg, File srcFile, int parseFlags) { 4150 if (ps != null 4151 && ps.codePath.equals(srcFile) 4152 && ps.timeStamp == srcFile.lastModified() 4153 && !isCompatSignatureUpdateNeeded(pkg)) { 4154 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4155 if (ps.signatures.mSignatures != null 4156 && ps.signatures.mSignatures.length != 0 4157 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4158 // Optimization: reuse the existing cached certificates 4159 // if the package appears to be unchanged. 4160 pkg.mSignatures = ps.signatures.mSignatures; 4161 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4162 pkg.mSigningKeys = ksms.getPublicKeysFromKeySet(mSigningKeySetId); 4163 return true; 4164 } 4165 4166 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them."); 4167 } else { 4168 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4169 } 4170 4171 try { 4172 pp.collectCertificates(pkg, parseFlags); 4173 pp.collectManifestDigest(pkg); 4174 } catch (PackageParserException e) { 4175 mLastScanError = e.error; 4176 return false; 4177 } 4178 return true; 4179 } 4180 4181 /* 4182 * Scan a package and return the newly parsed package. 4183 * Returns null in case of errors and the error code is stored in mLastScanError 4184 */ 4185 private PackageParser.Package scanPackageLI(File scanFile, 4186 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 4187 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 4188 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4189 parseFlags |= mDefParseFlags; 4190 PackageParser pp = new PackageParser(); 4191 pp.setSeparateProcesses(mSeparateProcesses); 4192 pp.setOnlyCoreApps(mOnlyCore); 4193 pp.setDisplayMetrics(mMetrics); 4194 4195 if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) { 4196 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4197 } 4198 4199 final PackageParser.Package pkg; 4200 try { 4201 pkg = pp.parsePackage(scanFile, parseFlags); 4202 } catch (PackageParserException e) { 4203 mLastScanError = e.error; 4204 return null; 4205 } 4206 4207 PackageSetting ps = null; 4208 PackageSetting updatedPkg; 4209 // reader 4210 synchronized (mPackages) { 4211 // Look to see if we already know about this package. 4212 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4213 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4214 // This package has been renamed to its original name. Let's 4215 // use that. 4216 ps = mSettings.peekPackageLPr(oldName); 4217 } 4218 // If there was no original package, see one for the real package name. 4219 if (ps == null) { 4220 ps = mSettings.peekPackageLPr(pkg.packageName); 4221 } 4222 // Check to see if this package could be hiding/updating a system 4223 // package. Must look for it either under the original or real 4224 // package name depending on our state. 4225 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4226 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4227 } 4228 boolean updatedPkgBetter = false; 4229 // First check if this is a system package that may involve an update 4230 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4231 if (ps != null && !ps.codePath.equals(scanFile)) { 4232 // The path has changed from what was last scanned... check the 4233 // version of the new path against what we have stored to determine 4234 // what to do. 4235 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4236 if (pkg.mVersionCode < ps.versionCode) { 4237 // The system package has been updated and the code path does not match 4238 // Ignore entry. Skip it. 4239 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4240 + " ignored: updated version " + ps.versionCode 4241 + " better than this " + pkg.mVersionCode); 4242 if (!updatedPkg.codePath.equals(scanFile)) { 4243 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4244 + ps.name + " changing from " + updatedPkg.codePathString 4245 + " to " + scanFile); 4246 updatedPkg.codePath = scanFile; 4247 updatedPkg.codePathString = scanFile.toString(); 4248 // This is the point at which we know that the system-disk APK 4249 // for this package has moved during a reboot (e.g. due to an OTA), 4250 // so we need to reevaluate it for privilege policy. 4251 if (locationIsPrivileged(scanFile)) { 4252 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4253 } 4254 } 4255 updatedPkg.pkg = pkg; 4256 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4257 return null; 4258 } else { 4259 // The current app on the system partition is better than 4260 // what we have updated to on the data partition; switch 4261 // back to the system partition version. 4262 // At this point, its safely assumed that package installation for 4263 // apps in system partition will go through. If not there won't be a working 4264 // version of the app 4265 // writer 4266 synchronized (mPackages) { 4267 // Just remove the loaded entries from package lists. 4268 mPackages.remove(ps.name); 4269 } 4270 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4271 + "reverting from " + ps.codePathString 4272 + ": new version " + pkg.mVersionCode 4273 + " better than installed " + ps.versionCode); 4274 4275 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4276 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4277 getAppInstructionSetFromSettings(ps)); 4278 synchronized (mInstallLock) { 4279 args.cleanUpResourcesLI(); 4280 } 4281 synchronized (mPackages) { 4282 mSettings.enableSystemPackageLPw(ps.name); 4283 } 4284 updatedPkgBetter = true; 4285 } 4286 } 4287 } 4288 4289 if (updatedPkg != null) { 4290 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4291 // initially 4292 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4293 4294 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4295 // flag set initially 4296 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4297 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4298 } 4299 } 4300 // Verify certificates against what was last scanned 4301 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) { 4302 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName); 4303 return null; 4304 } 4305 4306 /* 4307 * A new system app appeared, but we already had a non-system one of the 4308 * same name installed earlier. 4309 */ 4310 boolean shouldHideSystemApp = false; 4311 if (updatedPkg == null && ps != null 4312 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4313 /* 4314 * Check to make sure the signatures match first. If they don't, 4315 * wipe the installed application and its data. 4316 */ 4317 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4318 != PackageManager.SIGNATURE_MATCH) { 4319 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4320 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4321 ps = null; 4322 } else { 4323 /* 4324 * If the newly-added system app is an older version than the 4325 * already installed version, hide it. It will be scanned later 4326 * and re-added like an update. 4327 */ 4328 if (pkg.mVersionCode < ps.versionCode) { 4329 shouldHideSystemApp = true; 4330 } else { 4331 /* 4332 * The newly found system app is a newer version that the 4333 * one previously installed. Simply remove the 4334 * already-installed application and replace it with our own 4335 * while keeping the application data. 4336 */ 4337 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4338 + ps.codePathString + ": new version " + pkg.mVersionCode 4339 + " better than installed " + ps.versionCode); 4340 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4341 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4342 getAppInstructionSetFromSettings(ps)); 4343 synchronized (mInstallLock) { 4344 args.cleanUpResourcesLI(); 4345 } 4346 } 4347 } 4348 } 4349 4350 // The apk is forward locked (not public) if its code and resources 4351 // are kept in different files. (except for app in either system or 4352 // vendor path). 4353 // TODO grab this value from PackageSettings 4354 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4355 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4356 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4357 } 4358 } 4359 4360 // TODO: extend to support forward-locked splits 4361 String resourcePath = null; 4362 String baseResourcePath = null; 4363 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4364 if (ps != null && ps.resourcePathString != null) { 4365 resourcePath = ps.resourcePathString; 4366 baseResourcePath = ps.resourcePathString; 4367 } else { 4368 // Should not happen at all. Just log an error. 4369 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4370 } 4371 } else { 4372 resourcePath = pkg.codePath; 4373 baseResourcePath = pkg.baseCodePath; 4374 } 4375 4376 // Set application objects path explicitly. 4377 pkg.applicationInfo.setCodePath(pkg.codePath); 4378 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4379 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4380 pkg.applicationInfo.setResourcePath(resourcePath); 4381 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4382 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4383 4384 // Note that we invoke the following method only if we are about to unpack an application 4385 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4386 | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride); 4387 4388 /* 4389 * If the system app should be overridden by a previously installed 4390 * data, hide the system app now and let the /data/app scan pick it up 4391 * again. 4392 */ 4393 if (shouldHideSystemApp) { 4394 synchronized (mPackages) { 4395 /* 4396 * We have to grant systems permissions before we hide, because 4397 * grantPermissions will assume the package update is trying to 4398 * expand its permissions. 4399 */ 4400 grantPermissionsLPw(pkg, true); 4401 mSettings.disableSystemPackageLPw(pkg.packageName); 4402 } 4403 } 4404 4405 return scannedPkg; 4406 } 4407 4408 private static String fixProcessName(String defProcessName, 4409 String processName, int uid) { 4410 if (processName == null) { 4411 return defProcessName; 4412 } 4413 return processName; 4414 } 4415 4416 private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) { 4417 if (pkgSetting.signatures.mSignatures != null) { 4418 // Already existing package. Make sure signatures match 4419 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4420 == PackageManager.SIGNATURE_MATCH; 4421 if (!match) { 4422 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4423 == PackageManager.SIGNATURE_MATCH; 4424 } 4425 if (!match) { 4426 Slog.e(TAG, "Package " + pkg.packageName 4427 + " signatures do not match the previously installed version; ignoring!"); 4428 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 4429 return false; 4430 } 4431 } 4432 4433 // Check for shared user signatures 4434 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4435 // Already existing package. Make sure signatures match 4436 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4437 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4438 if (!match) { 4439 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4440 == PackageManager.SIGNATURE_MATCH; 4441 } 4442 if (!match) { 4443 Slog.e(TAG, "Package " + pkg.packageName 4444 + " has no signatures that match those in shared user " 4445 + pkgSetting.sharedUser.name + "; ignoring!"); 4446 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 4447 return false; 4448 } 4449 } 4450 return true; 4451 } 4452 4453 /** 4454 * Enforces that only the system UID or root's UID can call a method exposed 4455 * via Binder. 4456 * 4457 * @param message used as message if SecurityException is thrown 4458 * @throws SecurityException if the caller is not system or root 4459 */ 4460 private static final void enforceSystemOrRoot(String message) { 4461 final int uid = Binder.getCallingUid(); 4462 if (uid != Process.SYSTEM_UID && uid != 0) { 4463 throw new SecurityException(message); 4464 } 4465 } 4466 4467 @Override 4468 public void performBootDexOpt() { 4469 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4470 4471 final HashSet<PackageParser.Package> pkgs; 4472 synchronized (mPackages) { 4473 pkgs = mDeferredDexOpt; 4474 mDeferredDexOpt = null; 4475 } 4476 4477 if (pkgs != null) { 4478 // Filter out packages that aren't recently used. 4479 // 4480 // The exception is first boot of a non-eng device, which 4481 // should do a full dexopt. 4482 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4483 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4484 // TODO: add a property to control this? 4485 long dexOptLRUThresholdInMinutes; 4486 if (eng) { 4487 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4488 } else { 4489 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4490 } 4491 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4492 4493 int total = pkgs.size(); 4494 int skipped = 0; 4495 long now = System.currentTimeMillis(); 4496 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4497 PackageParser.Package pkg = i.next(); 4498 long then = pkg.mLastPackageUsageTimeInMills; 4499 if (then + dexOptLRUThresholdInMills < now) { 4500 if (DEBUG_DEXOPT) { 4501 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4502 ((then == 0) ? "never" : new Date(then))); 4503 } 4504 i.remove(); 4505 skipped++; 4506 } 4507 } 4508 if (DEBUG_DEXOPT) { 4509 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4510 } 4511 } 4512 4513 int i = 0; 4514 for (PackageParser.Package pkg : pkgs) { 4515 i++; 4516 if (DEBUG_DEXOPT) { 4517 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4518 + ": " + pkg.packageName); 4519 } 4520 if (!isFirstBoot()) { 4521 try { 4522 ActivityManagerNative.getDefault().showBootMessage( 4523 mContext.getResources().getString( 4524 R.string.android_upgrading_apk, 4525 i, pkgs.size()), true); 4526 } catch (RemoteException e) { 4527 } 4528 } 4529 PackageParser.Package p = pkg; 4530 synchronized (mInstallLock) { 4531 if (p.mDexOptNeeded) { 4532 performDexOptLI(p, false /* force dex */, false /* defer */, 4533 true /* include dependencies */); 4534 } 4535 } 4536 } 4537 } 4538 } 4539 4540 @Override 4541 public boolean performDexOpt(String packageName) { 4542 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4543 return performDexOpt(packageName, true); 4544 } 4545 4546 public boolean performDexOpt(String packageName, boolean updateUsage) { 4547 4548 PackageParser.Package p; 4549 synchronized (mPackages) { 4550 p = mPackages.get(packageName); 4551 if (p == null) { 4552 return false; 4553 } 4554 if (updateUsage) { 4555 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4556 } 4557 mPackageUsage.write(false); 4558 if (!p.mDexOptNeeded) { 4559 return false; 4560 } 4561 } 4562 4563 synchronized (mInstallLock) { 4564 return performDexOptLI(p, false /* force dex */, false /* defer */, 4565 true /* include dependencies */) == DEX_OPT_PERFORMED; 4566 } 4567 } 4568 4569 public HashSet<String> getPackagesThatNeedDexOpt() { 4570 HashSet<String> pkgs = null; 4571 synchronized (mPackages) { 4572 for (PackageParser.Package p : mPackages.values()) { 4573 if (DEBUG_DEXOPT) { 4574 Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded); 4575 } 4576 if (!p.mDexOptNeeded) { 4577 continue; 4578 } 4579 if (pkgs == null) { 4580 pkgs = new HashSet<String>(); 4581 } 4582 pkgs.add(p.packageName); 4583 } 4584 } 4585 return pkgs; 4586 } 4587 4588 public void shutdown() { 4589 mPackageUsage.write(true); 4590 } 4591 4592 private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet, 4593 boolean forceDex, boolean defer, HashSet<String> done) { 4594 for (int i=0; i<libs.size(); i++) { 4595 PackageParser.Package libPkg; 4596 String libName; 4597 synchronized (mPackages) { 4598 libName = libs.get(i); 4599 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4600 if (lib != null && lib.apk != null) { 4601 libPkg = mPackages.get(lib.apk); 4602 } else { 4603 libPkg = null; 4604 } 4605 } 4606 if (libPkg != null && !done.contains(libName)) { 4607 performDexOptLI(libPkg, instructionSet, forceDex, defer, done); 4608 } 4609 } 4610 } 4611 4612 static final int DEX_OPT_SKIPPED = 0; 4613 static final int DEX_OPT_PERFORMED = 1; 4614 static final int DEX_OPT_DEFERRED = 2; 4615 static final int DEX_OPT_FAILED = -1; 4616 4617 private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride, 4618 boolean forceDex, boolean defer, HashSet<String> done) { 4619 final String instructionSet = instructionSetOverride != null ? 4620 instructionSetOverride : getAppInstructionSet(pkg.applicationInfo); 4621 4622 if (done != null) { 4623 done.add(pkg.packageName); 4624 if (pkg.usesLibraries != null) { 4625 performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done); 4626 } 4627 if (pkg.usesOptionalLibraries != null) { 4628 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done); 4629 } 4630 } 4631 4632 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0) { 4633 final Collection<String> paths = pkg.getAllCodePaths(); 4634 for (String path : paths) { 4635 try { 4636 boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path, 4637 pkg.packageName, instructionSet, defer); 4638 // There are three basic cases here: 4639 // 1.) we need to dexopt, either because we are forced or it is needed 4640 // 2.) we are defering a needed dexopt 4641 // 3.) we are skipping an unneeded dexopt 4642 if (forceDex || (!defer && isDexOptNeededInternal)) { 4643 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName); 4644 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4645 int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4646 pkg.packageName, instructionSet); 4647 // Note that we ran dexopt, since rerunning will 4648 // probably just result in an error again. 4649 pkg.mDexOptNeeded = false; 4650 if (ret < 0) { 4651 return DEX_OPT_FAILED; 4652 } 4653 return DEX_OPT_PERFORMED; 4654 } 4655 if (defer && isDexOptNeededInternal) { 4656 if (mDeferredDexOpt == null) { 4657 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4658 } 4659 mDeferredDexOpt.add(pkg); 4660 return DEX_OPT_DEFERRED; 4661 } 4662 pkg.mDexOptNeeded = false; 4663 return DEX_OPT_SKIPPED; 4664 } catch (FileNotFoundException e) { 4665 Slog.w(TAG, "Apk not found for dexopt: " + path); 4666 return DEX_OPT_FAILED; 4667 } catch (IOException e) { 4668 Slog.w(TAG, "IOException reading apk: " + path, e); 4669 return DEX_OPT_FAILED; 4670 } catch (StaleDexCacheError e) { 4671 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4672 return DEX_OPT_FAILED; 4673 } catch (Exception e) { 4674 Slog.w(TAG, "Exception when doing dexopt : ", e); 4675 return DEX_OPT_FAILED; 4676 } 4677 } 4678 } 4679 return DEX_OPT_SKIPPED; 4680 } 4681 4682 private String getAppInstructionSet(ApplicationInfo info) { 4683 String instructionSet = getPreferredInstructionSet(); 4684 4685 if (info.cpuAbi != null) { 4686 instructionSet = VMRuntime.getInstructionSet(info.cpuAbi); 4687 } 4688 4689 return instructionSet; 4690 } 4691 4692 private String getAppInstructionSetFromSettings(PackageSetting ps) { 4693 String instructionSet = getPreferredInstructionSet(); 4694 4695 if (ps.cpuAbiString != null) { 4696 instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString); 4697 } 4698 4699 return instructionSet; 4700 } 4701 4702 private static String getPreferredInstructionSet() { 4703 if (sPreferredInstructionSet == null) { 4704 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4705 } 4706 4707 return sPreferredInstructionSet; 4708 } 4709 4710 private static List<String> getAllInstructionSets() { 4711 final String[] allAbis = Build.SUPPORTED_ABIS; 4712 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4713 4714 for (String abi : allAbis) { 4715 final String instructionSet = VMRuntime.getInstructionSet(abi); 4716 if (!allInstructionSets.contains(instructionSet)) { 4717 allInstructionSets.add(instructionSet); 4718 } 4719 } 4720 4721 return allInstructionSets; 4722 } 4723 4724 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer, 4725 boolean inclDependencies) { 4726 HashSet<String> done; 4727 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4728 done = new HashSet<String>(); 4729 done.add(pkg.packageName); 4730 } else { 4731 done = null; 4732 } 4733 return performDexOptLI(pkg, null /* instruction set override */, forceDex, defer, done); 4734 } 4735 4736 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4737 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4738 Slog.w(TAG, "Unable to update from " + oldPkg.name 4739 + " to " + newPkg.packageName 4740 + ": old package not in system partition"); 4741 return false; 4742 } else if (mPackages.get(oldPkg.name) != null) { 4743 Slog.w(TAG, "Unable to update from " + oldPkg.name 4744 + " to " + newPkg.packageName 4745 + ": old package still exists"); 4746 return false; 4747 } 4748 return true; 4749 } 4750 4751 File getDataPathForUser(int userId) { 4752 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4753 } 4754 4755 private File getDataPathForPackage(String packageName, int userId) { 4756 /* 4757 * Until we fully support multiple users, return the directory we 4758 * previously would have. The PackageManagerTests will need to be 4759 * revised when this is changed back.. 4760 */ 4761 if (userId == 0) { 4762 return new File(mAppDataDir, packageName); 4763 } else { 4764 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4765 + File.separator + packageName); 4766 } 4767 } 4768 4769 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4770 int[] users = sUserManager.getUserIds(); 4771 int res = mInstaller.install(packageName, uid, uid, seinfo); 4772 if (res < 0) { 4773 return res; 4774 } 4775 for (int user : users) { 4776 if (user != 0) { 4777 res = mInstaller.createUserData(packageName, 4778 UserHandle.getUid(user, uid), user, seinfo); 4779 if (res < 0) { 4780 return res; 4781 } 4782 } 4783 } 4784 return res; 4785 } 4786 4787 private int removeDataDirsLI(String packageName) { 4788 int[] users = sUserManager.getUserIds(); 4789 int res = 0; 4790 for (int user : users) { 4791 int resInner = mInstaller.remove(packageName, user); 4792 if (resInner < 0) { 4793 res = resInner; 4794 } 4795 } 4796 4797 final File nativeLibraryFile = new File(mAppLibInstallDir, packageName); 4798 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 4799 if (!nativeLibraryFile.delete()) { 4800 Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath()); 4801 } 4802 4803 return res; 4804 } 4805 4806 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4807 PackageParser.Package changingLib) { 4808 if (file.path != null) { 4809 usesLibraryFiles.add(file.path); 4810 return; 4811 } 4812 PackageParser.Package p = mPackages.get(file.apk); 4813 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4814 // If we are doing this while in the middle of updating a library apk, 4815 // then we need to make sure to use that new apk for determining the 4816 // dependencies here. (We haven't yet finished committing the new apk 4817 // to the package manager state.) 4818 if (p == null || p.packageName.equals(changingLib.packageName)) { 4819 p = changingLib; 4820 } 4821 } 4822 if (p != null) { 4823 usesLibraryFiles.addAll(p.getAllCodePaths()); 4824 } 4825 } 4826 4827 private boolean updateSharedLibrariesLPw(PackageParser.Package pkg, 4828 PackageParser.Package changingLib) { 4829 // We might be upgrading from a version of the platform that did not 4830 // provide per-package native library directories for system apps. 4831 // Fix that up here. 4832 if (isSystemApp(pkg)) { 4833 PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName); 4834 setInternalAppNativeLibraryPath(pkg, ps); 4835 } 4836 4837 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4838 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4839 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4840 for (int i=0; i<N; i++) { 4841 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4842 if (file == null) { 4843 Slog.e(TAG, "Package " + pkg.packageName 4844 + " requires unavailable shared library " 4845 + pkg.usesLibraries.get(i) + "; failing!"); 4846 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 4847 return false; 4848 } 4849 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4850 } 4851 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4852 for (int i=0; i<N; i++) { 4853 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4854 if (file == null) { 4855 Slog.w(TAG, "Package " + pkg.packageName 4856 + " desires unavailable shared library " 4857 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4858 } else { 4859 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4860 } 4861 } 4862 N = usesLibraryFiles.size(); 4863 if (N > 0) { 4864 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4865 } else { 4866 pkg.usesLibraryFiles = null; 4867 } 4868 } 4869 return true; 4870 } 4871 4872 private static boolean hasString(List<String> list, List<String> which) { 4873 if (list == null) { 4874 return false; 4875 } 4876 for (int i=list.size()-1; i>=0; i--) { 4877 for (int j=which.size()-1; j>=0; j--) { 4878 if (which.get(j).equals(list.get(i))) { 4879 return true; 4880 } 4881 } 4882 } 4883 return false; 4884 } 4885 4886 private void updateAllSharedLibrariesLPw() { 4887 for (PackageParser.Package pkg : mPackages.values()) { 4888 updateSharedLibrariesLPw(pkg, null); 4889 } 4890 } 4891 4892 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4893 PackageParser.Package changingPkg) { 4894 ArrayList<PackageParser.Package> res = null; 4895 for (PackageParser.Package pkg : mPackages.values()) { 4896 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4897 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4898 if (res == null) { 4899 res = new ArrayList<PackageParser.Package>(); 4900 } 4901 res.add(pkg); 4902 updateSharedLibrariesLPw(pkg, changingPkg); 4903 } 4904 } 4905 return res; 4906 } 4907 4908 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, 4909 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 4910 final File scanFile = new File(pkg.codePath); 4911 if (pkg.applicationInfo.getCodePath() == null || 4912 pkg.applicationInfo.getResourcePath() == null) { 4913 // Bail out. The resource and code paths haven't been set. 4914 Slog.w(TAG, " Code and resource paths haven't been set correctly"); 4915 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK; 4916 return null; 4917 } 4918 4919 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4920 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4921 } 4922 4923 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4924 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4925 } 4926 4927 if (mCustomResolverComponentName != null && 4928 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4929 setUpCustomResolverActivity(pkg); 4930 } 4931 4932 if (pkg.packageName.equals("android")) { 4933 synchronized (mPackages) { 4934 if (mAndroidApplication != null) { 4935 Slog.w(TAG, "*************************************************"); 4936 Slog.w(TAG, "Core android package being redefined. Skipping."); 4937 Slog.w(TAG, " file=" + scanFile); 4938 Slog.w(TAG, "*************************************************"); 4939 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4940 return null; 4941 } 4942 4943 // Set up information for our fall-back user intent resolution activity. 4944 mPlatformPackage = pkg; 4945 pkg.mVersionCode = mSdkVersion; 4946 mAndroidApplication = pkg.applicationInfo; 4947 4948 if (!mResolverReplaced) { 4949 mResolveActivity.applicationInfo = mAndroidApplication; 4950 mResolveActivity.name = ResolverActivity.class.getName(); 4951 mResolveActivity.packageName = mAndroidApplication.packageName; 4952 mResolveActivity.processName = "system:ui"; 4953 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 4954 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 4955 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 4956 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 4957 mResolveActivity.exported = true; 4958 mResolveActivity.enabled = true; 4959 mResolveInfo.activityInfo = mResolveActivity; 4960 mResolveInfo.priority = 0; 4961 mResolveInfo.preferredOrder = 0; 4962 mResolveInfo.match = 0; 4963 mResolveComponentName = new ComponentName( 4964 mAndroidApplication.packageName, mResolveActivity.name); 4965 } 4966 } 4967 } 4968 4969 if (DEBUG_PACKAGE_SCANNING) { 4970 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4971 Log.d(TAG, "Scanning package " + pkg.packageName); 4972 } 4973 4974 if (mPackages.containsKey(pkg.packageName) 4975 || mSharedLibraries.containsKey(pkg.packageName)) { 4976 Slog.w(TAG, "Application package " + pkg.packageName 4977 + " already installed. Skipping duplicate."); 4978 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4979 return null; 4980 } 4981 4982 // Initialize package source and resource directories 4983 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 4984 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 4985 4986 SharedUserSetting suid = null; 4987 PackageSetting pkgSetting = null; 4988 4989 if (!isSystemApp(pkg)) { 4990 // Only system apps can use these features. 4991 pkg.mOriginalPackages = null; 4992 pkg.mRealPackage = null; 4993 pkg.mAdoptPermissions = null; 4994 } 4995 4996 // writer 4997 synchronized (mPackages) { 4998 if (pkg.mSharedUserId != null) { 4999 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5000 if (suid == null) { 5001 Slog.w(TAG, "Creating application package " + pkg.packageName 5002 + " for shared user failed"); 5003 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5004 return null; 5005 } 5006 if (DEBUG_PACKAGE_SCANNING) { 5007 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5008 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5009 + "): packages=" + suid.packages); 5010 } 5011 } 5012 5013 // Check if we are renaming from an original package name. 5014 PackageSetting origPackage = null; 5015 String realName = null; 5016 if (pkg.mOriginalPackages != null) { 5017 // This package may need to be renamed to a previously 5018 // installed name. Let's check on that... 5019 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5020 if (pkg.mOriginalPackages.contains(renamed)) { 5021 // This package had originally been installed as the 5022 // original name, and we have already taken care of 5023 // transitioning to the new one. Just update the new 5024 // one to continue using the old name. 5025 realName = pkg.mRealPackage; 5026 if (!pkg.packageName.equals(renamed)) { 5027 // Callers into this function may have already taken 5028 // care of renaming the package; only do it here if 5029 // it is not already done. 5030 pkg.setPackageName(renamed); 5031 } 5032 5033 } else { 5034 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5035 if ((origPackage = mSettings.peekPackageLPr( 5036 pkg.mOriginalPackages.get(i))) != null) { 5037 // We do have the package already installed under its 5038 // original name... should we use it? 5039 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5040 // New package is not compatible with original. 5041 origPackage = null; 5042 continue; 5043 } else if (origPackage.sharedUser != null) { 5044 // Make sure uid is compatible between packages. 5045 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5046 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5047 + " to " + pkg.packageName + ": old uid " 5048 + origPackage.sharedUser.name 5049 + " differs from " + pkg.mSharedUserId); 5050 origPackage = null; 5051 continue; 5052 } 5053 } else { 5054 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5055 + pkg.packageName + " to old name " + origPackage.name); 5056 } 5057 break; 5058 } 5059 } 5060 } 5061 } 5062 5063 if (mTransferedPackages.contains(pkg.packageName)) { 5064 Slog.w(TAG, "Package " + pkg.packageName 5065 + " was transferred to another, but its .apk remains"); 5066 } 5067 5068 // Just create the setting, don't add it yet. For already existing packages 5069 // the PkgSetting exists already and doesn't have to be created. 5070 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5071 destResourceFile, pkg.applicationInfo.nativeLibraryDir, 5072 pkg.applicationInfo.cpuAbi, 5073 pkg.applicationInfo.flags, user, false); 5074 if (pkgSetting == null) { 5075 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed"); 5076 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5077 return null; 5078 } 5079 5080 if (pkgSetting.origPackage != null) { 5081 // If we are first transitioning from an original package, 5082 // fix up the new package's name now. We need to do this after 5083 // looking up the package under its new name, so getPackageLP 5084 // can take care of fiddling things correctly. 5085 pkg.setPackageName(origPackage.name); 5086 5087 // File a report about this. 5088 String msg = "New package " + pkgSetting.realName 5089 + " renamed to replace old package " + pkgSetting.name; 5090 reportSettingsProblem(Log.WARN, msg); 5091 5092 // Make a note of it. 5093 mTransferedPackages.add(origPackage.name); 5094 5095 // No longer need to retain this. 5096 pkgSetting.origPackage = null; 5097 } 5098 5099 if (realName != null) { 5100 // Make a note of it. 5101 mTransferedPackages.add(pkg.packageName); 5102 } 5103 5104 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5105 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5106 } 5107 5108 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5109 // Check all shared libraries and map to their actual file path. 5110 // We only do this here for apps not on a system dir, because those 5111 // are the only ones that can fail an install due to this. We 5112 // will take care of the system apps by updating all of their 5113 // library paths after the scan is done. 5114 if (!updateSharedLibrariesLPw(pkg, null)) { 5115 return null; 5116 } 5117 } 5118 5119 if (mFoundPolicyFile) { 5120 SELinuxMMAC.assignSeinfoValue(pkg); 5121 } 5122 5123 pkg.applicationInfo.uid = pkgSetting.appId; 5124 pkg.mExtras = pkgSetting; 5125 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5126 if (!verifySignaturesLP(pkgSetting, pkg)) { 5127 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5128 return null; 5129 } 5130 // The signature has changed, but this package is in the system 5131 // image... let's recover! 5132 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5133 // However... if this package is part of a shared user, but it 5134 // doesn't match the signature of the shared user, let's fail. 5135 // What this means is that you can't change the signatures 5136 // associated with an overall shared user, which doesn't seem all 5137 // that unreasonable. 5138 if (pkgSetting.sharedUser != null) { 5139 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5140 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5141 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser); 5142 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 5143 return null; 5144 } 5145 } 5146 // File a report about this. 5147 String msg = "System package " + pkg.packageName 5148 + " signature changed; retaining data."; 5149 reportSettingsProblem(Log.WARN, msg); 5150 } 5151 } else { 5152 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5153 Slog.e(TAG, "Package " + pkg.packageName 5154 + " upgrade keys do not match the previously installed version; "); 5155 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 5156 return null; 5157 } else { 5158 // signatures may have changed as result of upgrade 5159 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5160 } 5161 } 5162 // Verify that this new package doesn't have any content providers 5163 // that conflict with existing packages. Only do this if the 5164 // package isn't already installed, since we don't want to break 5165 // things that are installed. 5166 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5167 final int N = pkg.providers.size(); 5168 int i; 5169 for (i=0; i<N; i++) { 5170 PackageParser.Provider p = pkg.providers.get(i); 5171 if (p.info.authority != null) { 5172 String names[] = p.info.authority.split(";"); 5173 for (int j = 0; j < names.length; j++) { 5174 if (mProvidersByAuthority.containsKey(names[j])) { 5175 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5176 Slog.w(TAG, "Can't install because provider name " + names[j] + 5177 " (in package " + pkg.applicationInfo.packageName + 5178 ") is already used by " 5179 + ((other != null && other.getComponentName() != null) 5180 ? other.getComponentName().getPackageName() : "?")); 5181 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 5182 return null; 5183 } 5184 } 5185 } 5186 } 5187 } 5188 5189 if (pkg.mAdoptPermissions != null) { 5190 // This package wants to adopt ownership of permissions from 5191 // another package. 5192 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5193 final String origName = pkg.mAdoptPermissions.get(i); 5194 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5195 if (orig != null) { 5196 if (verifyPackageUpdateLPr(orig, pkg)) { 5197 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5198 + pkg.packageName); 5199 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5200 } 5201 } 5202 } 5203 } 5204 } 5205 5206 final String pkgName = pkg.packageName; 5207 5208 final long scanFileTime = scanFile.lastModified(); 5209 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5210 pkg.applicationInfo.processName = fixProcessName( 5211 pkg.applicationInfo.packageName, 5212 pkg.applicationInfo.processName, 5213 pkg.applicationInfo.uid); 5214 5215 File dataPath; 5216 if (mPlatformPackage == pkg) { 5217 // The system package is special. 5218 dataPath = new File (Environment.getDataDirectory(), "system"); 5219 pkg.applicationInfo.dataDir = dataPath.getPath(); 5220 } else { 5221 // This is a normal package, need to make its data directory. 5222 dataPath = getDataPathForPackage(pkg.packageName, 0); 5223 5224 boolean uidError = false; 5225 5226 if (dataPath.exists()) { 5227 int currentUid = 0; 5228 try { 5229 StructStat stat = Os.stat(dataPath.getPath()); 5230 currentUid = stat.st_uid; 5231 } catch (ErrnoException e) { 5232 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5233 } 5234 5235 // If we have mismatched owners for the data path, we have a problem. 5236 if (currentUid != pkg.applicationInfo.uid) { 5237 boolean recovered = false; 5238 if (currentUid == 0) { 5239 // The directory somehow became owned by root. Wow. 5240 // This is probably because the system was stopped while 5241 // installd was in the middle of messing with its libs 5242 // directory. Ask installd to fix that. 5243 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5244 pkg.applicationInfo.uid); 5245 if (ret >= 0) { 5246 recovered = true; 5247 String msg = "Package " + pkg.packageName 5248 + " unexpectedly changed to uid 0; recovered to " + 5249 + pkg.applicationInfo.uid; 5250 reportSettingsProblem(Log.WARN, msg); 5251 } 5252 } 5253 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5254 || (scanMode&SCAN_BOOTING) != 0)) { 5255 // If this is a system app, we can at least delete its 5256 // current data so the application will still work. 5257 int ret = removeDataDirsLI(pkgName); 5258 if (ret >= 0) { 5259 // TODO: Kill the processes first 5260 // Old data gone! 5261 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5262 ? "System package " : "Third party package "; 5263 String msg = prefix + pkg.packageName 5264 + " has changed from uid: " 5265 + currentUid + " to " 5266 + pkg.applicationInfo.uid + "; old data erased"; 5267 reportSettingsProblem(Log.WARN, msg); 5268 recovered = true; 5269 5270 // And now re-install the app. 5271 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5272 pkg.applicationInfo.seinfo); 5273 if (ret == -1) { 5274 // Ack should not happen! 5275 msg = prefix + pkg.packageName 5276 + " could not have data directory re-created after delete."; 5277 reportSettingsProblem(Log.WARN, msg); 5278 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5279 return null; 5280 } 5281 } 5282 if (!recovered) { 5283 mHasSystemUidErrors = true; 5284 } 5285 } else if (!recovered) { 5286 // If we allow this install to proceed, we will be broken. 5287 // Abort, abort! 5288 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED; 5289 return null; 5290 } 5291 if (!recovered) { 5292 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5293 + pkg.applicationInfo.uid + "/fs_" 5294 + currentUid; 5295 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5296 String msg = "Package " + pkg.packageName 5297 + " has mismatched uid: " 5298 + currentUid + " on disk, " 5299 + pkg.applicationInfo.uid + " in settings"; 5300 // writer 5301 synchronized (mPackages) { 5302 mSettings.mReadMessages.append(msg); 5303 mSettings.mReadMessages.append('\n'); 5304 uidError = true; 5305 if (!pkgSetting.uidError) { 5306 reportSettingsProblem(Log.ERROR, msg); 5307 } 5308 } 5309 } 5310 } 5311 pkg.applicationInfo.dataDir = dataPath.getPath(); 5312 if (mShouldRestoreconData) { 5313 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5314 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5315 pkg.applicationInfo.uid); 5316 } 5317 } else { 5318 if (DEBUG_PACKAGE_SCANNING) { 5319 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5320 Log.v(TAG, "Want this data dir: " + dataPath); 5321 } 5322 //invoke installer to do the actual installation 5323 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5324 pkg.applicationInfo.seinfo); 5325 if (ret < 0) { 5326 // Error from installer 5327 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5328 return null; 5329 } 5330 5331 if (dataPath.exists()) { 5332 pkg.applicationInfo.dataDir = dataPath.getPath(); 5333 } else { 5334 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5335 pkg.applicationInfo.dataDir = null; 5336 } 5337 } 5338 5339 /* 5340 * Set the data dir to the default "/data/data/<package name>/lib" 5341 * if we got here without anyone telling us different (e.g., apps 5342 * stored on SD card have their native libraries stored in the ASEC 5343 * container with the APK). 5344 * 5345 * This happens during an upgrade from a package settings file that 5346 * doesn't have a native library path attribute at all. 5347 */ 5348 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) { 5349 if (pkgSetting.nativeLibraryPathString == null) { 5350 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5351 } else { 5352 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString; 5353 } 5354 } 5355 pkgSetting.uidError = uidError; 5356 } 5357 5358 final String path = scanFile.getPath(); 5359 /* Note: We don't want to unpack the native binaries for 5360 * system applications, unless they have been updated 5361 * (the binaries are already under /system/lib). 5362 * Also, don't unpack libs for apps on the external card 5363 * since they should have their libraries in the ASEC 5364 * container already. 5365 * 5366 * In other words, we're going to unpack the binaries 5367 * only for non-system apps and system app upgrades. 5368 */ 5369 if (pkg.applicationInfo.nativeLibraryDir != null) { 5370 NativeLibraryHelper.Handle handle = null; 5371 try { 5372 handle = NativeLibraryHelper.Handle.create(scanFile); 5373 // Enable gross and lame hacks for apps that are built with old 5374 // SDK tools. We must scan their APKs for renderscript bitcode and 5375 // not launch them if it's present. Don't bother checking on devices 5376 // that don't have 64 bit support. 5377 String[] abiList = Build.SUPPORTED_ABIS; 5378 boolean hasLegacyRenderscriptBitcode = false; 5379 if (abiOverride != null) { 5380 abiList = new String[] { abiOverride }; 5381 } else if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && 5382 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5383 abiList = Build.SUPPORTED_32_BIT_ABIS; 5384 hasLegacyRenderscriptBitcode = true; 5385 } 5386 5387 File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5388 final String dataPathString = dataPath.getCanonicalPath(); 5389 5390 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5391 /* 5392 * Upgrading from a previous version of the OS sometimes 5393 * leaves native libraries in the /data/data/<app>/lib 5394 * directory for system apps even when they shouldn't be. 5395 * Recent changes in the JNI library search path 5396 * necessitates we remove those to match previous behavior. 5397 */ 5398 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) { 5399 Log.i(TAG, "removed obsolete native libraries for system package " 5400 + path); 5401 } 5402 if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5403 pkg.applicationInfo.cpuAbi = abiList[0]; 5404 pkgSetting.cpuAbiString = abiList[0]; 5405 } else { 5406 setInternalAppAbi(pkg, pkgSetting); 5407 } 5408 } else { 5409 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 5410 /* 5411 * Update native library dir if it starts with 5412 * /data/data 5413 */ 5414 if (nativeLibraryDir.getPath().startsWith(dataPathString)) { 5415 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5416 nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5417 } 5418 5419 try { 5420 int copyRet = copyNativeLibrariesForInternalApp(handle, 5421 nativeLibraryDir, abiList); 5422 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5423 Slog.e(TAG, "Unable to copy native libraries"); 5424 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5425 return null; 5426 } 5427 5428 // We've successfully copied native libraries across, so we make a 5429 // note of what ABI we're using 5430 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5431 pkg.applicationInfo.cpuAbi = abiList[copyRet]; 5432 } else if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5433 pkg.applicationInfo.cpuAbi = abiList[0]; 5434 } else { 5435 pkg.applicationInfo.cpuAbi = null; 5436 } 5437 } catch (IOException e) { 5438 Slog.e(TAG, "Unable to copy native libraries", e); 5439 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5440 return null; 5441 } 5442 } else { 5443 // We don't have to copy the shared libraries if we're in the ASEC container 5444 // but we still need to scan the file to figure out what ABI the app needs. 5445 // 5446 // TODO: This duplicates work done in the default container service. It's possible 5447 // to clean this up but we'll need to change the interface between this service 5448 // and IMediaContainerService (but doing so will spread this logic out, rather 5449 // than centralizing it). 5450 final int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5451 if (abi >= 0) { 5452 pkg.applicationInfo.cpuAbi = abiList[abi]; 5453 } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) { 5454 // Note that (non upgraded) system apps will not have any native 5455 // libraries bundled in their APK, but we're guaranteed not to be 5456 // such an app at this point. 5457 if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5458 pkg.applicationInfo.cpuAbi = abiList[0]; 5459 } else { 5460 pkg.applicationInfo.cpuAbi = null; 5461 } 5462 } else { 5463 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5464 return null; 5465 } 5466 } 5467 5468 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5469 final int[] userIds = sUserManager.getUserIds(); 5470 synchronized (mInstallLock) { 5471 for (int userId : userIds) { 5472 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 5473 pkg.applicationInfo.nativeLibraryDir, userId) < 0) { 5474 Slog.w(TAG, "Failed linking native library dir (user=" + userId 5475 + ")"); 5476 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5477 return null; 5478 } 5479 } 5480 } 5481 } 5482 5483 pkgSetting.cpuAbiString = pkg.applicationInfo.cpuAbi; 5484 } catch (IOException ioe) { 5485 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5486 } finally { 5487 IoUtils.closeQuietly(handle); 5488 } 5489 } 5490 5491 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5492 // We don't do this here during boot because we can do it all 5493 // at once after scanning all existing packages. 5494 // 5495 // We also do this *before* we perform dexopt on this package, so that 5496 // we can avoid redundant dexopts, and also to make sure we've got the 5497 // code and package path correct. 5498 if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5499 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) { 5500 mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE; 5501 return null; 5502 } 5503 } 5504 5505 if ((scanMode&SCAN_NO_DEX) == 0) { 5506 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5507 == DEX_OPT_FAILED) { 5508 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5509 removeDataDirsLI(pkg.packageName); 5510 } 5511 5512 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5513 return null; 5514 } 5515 } 5516 5517 if (mFactoryTest && pkg.requestedPermissions.contains( 5518 android.Manifest.permission.FACTORY_TEST)) { 5519 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5520 } 5521 5522 ArrayList<PackageParser.Package> clientLibPkgs = null; 5523 5524 // writer 5525 synchronized (mPackages) { 5526 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5527 // Only system apps can add new shared libraries. 5528 if (pkg.libraryNames != null) { 5529 for (int i=0; i<pkg.libraryNames.size(); i++) { 5530 String name = pkg.libraryNames.get(i); 5531 boolean allowed = false; 5532 if (isUpdatedSystemApp(pkg)) { 5533 // New library entries can only be added through the 5534 // system image. This is important to get rid of a lot 5535 // of nasty edge cases: for example if we allowed a non- 5536 // system update of the app to add a library, then uninstalling 5537 // the update would make the library go away, and assumptions 5538 // we made such as through app install filtering would now 5539 // have allowed apps on the device which aren't compatible 5540 // with it. Better to just have the restriction here, be 5541 // conservative, and create many fewer cases that can negatively 5542 // impact the user experience. 5543 final PackageSetting sysPs = mSettings 5544 .getDisabledSystemPkgLPr(pkg.packageName); 5545 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5546 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5547 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5548 allowed = true; 5549 allowed = true; 5550 break; 5551 } 5552 } 5553 } 5554 } else { 5555 allowed = true; 5556 } 5557 if (allowed) { 5558 if (!mSharedLibraries.containsKey(name)) { 5559 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5560 } else if (!name.equals(pkg.packageName)) { 5561 Slog.w(TAG, "Package " + pkg.packageName + " library " 5562 + name + " already exists; skipping"); 5563 } 5564 } else { 5565 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5566 + name + " that is not declared on system image; skipping"); 5567 } 5568 } 5569 if ((scanMode&SCAN_BOOTING) == 0) { 5570 // If we are not booting, we need to update any applications 5571 // that are clients of our shared library. If we are booting, 5572 // this will all be done once the scan is complete. 5573 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5574 } 5575 } 5576 } 5577 } 5578 5579 // We also need to dexopt any apps that are dependent on this library. Note that 5580 // if these fail, we should abort the install since installing the library will 5581 // result in some apps being broken. 5582 if (clientLibPkgs != null) { 5583 if ((scanMode&SCAN_NO_DEX) == 0) { 5584 for (int i=0; i<clientLibPkgs.size(); i++) { 5585 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5586 if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5587 == DEX_OPT_FAILED) { 5588 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5589 removeDataDirsLI(pkg.packageName); 5590 } 5591 5592 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5593 return null; 5594 } 5595 } 5596 } 5597 } 5598 5599 // Request the ActivityManager to kill the process(only for existing packages) 5600 // so that we do not end up in a confused state while the user is still using the older 5601 // version of the application while the new one gets installed. 5602 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5603 // If the package lives in an asec, tell everyone that the container is going 5604 // away so they can clean up any references to its resources (which would prevent 5605 // vold from being able to unmount the asec) 5606 if (isForwardLocked(pkg) || isExternal(pkg)) { 5607 if (DEBUG_INSTALL) { 5608 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5609 } 5610 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5611 final ArrayList<String> pkgList = new ArrayList<String>(1); 5612 pkgList.add(pkg.applicationInfo.packageName); 5613 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5614 } 5615 5616 // Post the request that it be killed now that the going-away broadcast is en route 5617 killApplication(pkg.applicationInfo.packageName, 5618 pkg.applicationInfo.uid, "update pkg"); 5619 } 5620 5621 // Also need to kill any apps that are dependent on the library. 5622 if (clientLibPkgs != null) { 5623 for (int i=0; i<clientLibPkgs.size(); i++) { 5624 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5625 killApplication(clientPkg.applicationInfo.packageName, 5626 clientPkg.applicationInfo.uid, "update lib"); 5627 } 5628 } 5629 5630 // writer 5631 synchronized (mPackages) { 5632 // We don't expect installation to fail beyond this point, 5633 if ((scanMode&SCAN_MONITOR) != 0) { 5634 mAppDirs.put(pkg.codePath, pkg); 5635 } 5636 // Add the new setting to mSettings 5637 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5638 // Add the new setting to mPackages 5639 mPackages.put(pkg.applicationInfo.packageName, pkg); 5640 // Make sure we don't accidentally delete its data. 5641 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5642 while (iter.hasNext()) { 5643 PackageCleanItem item = iter.next(); 5644 if (pkgName.equals(item.packageName)) { 5645 iter.remove(); 5646 } 5647 } 5648 5649 // Take care of first install / last update times. 5650 if (currentTime != 0) { 5651 if (pkgSetting.firstInstallTime == 0) { 5652 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5653 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5654 pkgSetting.lastUpdateTime = currentTime; 5655 } 5656 } else if (pkgSetting.firstInstallTime == 0) { 5657 // We need *something*. Take time time stamp of the file. 5658 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5659 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5660 if (scanFileTime != pkgSetting.timeStamp) { 5661 // A package on the system image has changed; consider this 5662 // to be an update. 5663 pkgSetting.lastUpdateTime = scanFileTime; 5664 } 5665 } 5666 5667 // Add the package's KeySets to the global KeySetManagerService 5668 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5669 try { 5670 // Old KeySetData no longer valid. 5671 ksms.removeAppKeySetData(pkg.packageName); 5672 ksms.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys); 5673 if (pkg.mKeySetMapping != null) { 5674 for (Map.Entry<String, Set<PublicKey>> entry : 5675 pkg.mKeySetMapping.entrySet()) { 5676 if (entry.getValue() != null) { 5677 ksms.addDefinedKeySetToPackage(pkg.packageName, 5678 entry.getValue(), entry.getKey()); 5679 } 5680 } 5681 if (pkg.mUpgradeKeySets != null 5682 && pkg.mKeySetMapping.keySet().containsAll(pkg.mUpgradeKeySets)) { 5683 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5684 ksms.addUpgradeKeySetToPackage(pkg.packageName, upgradeAlias); 5685 } 5686 } 5687 } 5688 } catch (NullPointerException e) { 5689 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5690 } catch (IllegalArgumentException e) { 5691 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5692 } 5693 5694 int N = pkg.providers.size(); 5695 StringBuilder r = null; 5696 int i; 5697 for (i=0; i<N; i++) { 5698 PackageParser.Provider p = pkg.providers.get(i); 5699 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5700 p.info.processName, pkg.applicationInfo.uid); 5701 mProviders.addProvider(p); 5702 p.syncable = p.info.isSyncable; 5703 if (p.info.authority != null) { 5704 String names[] = p.info.authority.split(";"); 5705 p.info.authority = null; 5706 for (int j = 0; j < names.length; j++) { 5707 if (j == 1 && p.syncable) { 5708 // We only want the first authority for a provider to possibly be 5709 // syncable, so if we already added this provider using a different 5710 // authority clear the syncable flag. We copy the provider before 5711 // changing it because the mProviders object contains a reference 5712 // to a provider that we don't want to change. 5713 // Only do this for the second authority since the resulting provider 5714 // object can be the same for all future authorities for this provider. 5715 p = new PackageParser.Provider(p); 5716 p.syncable = false; 5717 } 5718 if (!mProvidersByAuthority.containsKey(names[j])) { 5719 mProvidersByAuthority.put(names[j], p); 5720 if (p.info.authority == null) { 5721 p.info.authority = names[j]; 5722 } else { 5723 p.info.authority = p.info.authority + ";" + names[j]; 5724 } 5725 if (DEBUG_PACKAGE_SCANNING) { 5726 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5727 Log.d(TAG, "Registered content provider: " + names[j] 5728 + ", className = " + p.info.name + ", isSyncable = " 5729 + p.info.isSyncable); 5730 } 5731 } else { 5732 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5733 Slog.w(TAG, "Skipping provider name " + names[j] + 5734 " (in package " + pkg.applicationInfo.packageName + 5735 "): name already used by " 5736 + ((other != null && other.getComponentName() != null) 5737 ? other.getComponentName().getPackageName() : "?")); 5738 } 5739 } 5740 } 5741 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5742 if (r == null) { 5743 r = new StringBuilder(256); 5744 } else { 5745 r.append(' '); 5746 } 5747 r.append(p.info.name); 5748 } 5749 } 5750 if (r != null) { 5751 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5752 } 5753 5754 N = pkg.services.size(); 5755 r = null; 5756 for (i=0; i<N; i++) { 5757 PackageParser.Service s = pkg.services.get(i); 5758 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5759 s.info.processName, pkg.applicationInfo.uid); 5760 mServices.addService(s); 5761 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5762 if (r == null) { 5763 r = new StringBuilder(256); 5764 } else { 5765 r.append(' '); 5766 } 5767 r.append(s.info.name); 5768 } 5769 } 5770 if (r != null) { 5771 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5772 } 5773 5774 N = pkg.receivers.size(); 5775 r = null; 5776 for (i=0; i<N; i++) { 5777 PackageParser.Activity a = pkg.receivers.get(i); 5778 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5779 a.info.processName, pkg.applicationInfo.uid); 5780 mReceivers.addActivity(a, "receiver"); 5781 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5782 if (r == null) { 5783 r = new StringBuilder(256); 5784 } else { 5785 r.append(' '); 5786 } 5787 r.append(a.info.name); 5788 } 5789 } 5790 if (r != null) { 5791 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5792 } 5793 5794 N = pkg.activities.size(); 5795 r = null; 5796 for (i=0; i<N; i++) { 5797 PackageParser.Activity a = pkg.activities.get(i); 5798 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5799 a.info.processName, pkg.applicationInfo.uid); 5800 mActivities.addActivity(a, "activity"); 5801 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5802 if (r == null) { 5803 r = new StringBuilder(256); 5804 } else { 5805 r.append(' '); 5806 } 5807 r.append(a.info.name); 5808 } 5809 } 5810 if (r != null) { 5811 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5812 } 5813 5814 N = pkg.permissionGroups.size(); 5815 r = null; 5816 for (i=0; i<N; i++) { 5817 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5818 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5819 if (cur == null) { 5820 mPermissionGroups.put(pg.info.name, pg); 5821 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5822 if (r == null) { 5823 r = new StringBuilder(256); 5824 } else { 5825 r.append(' '); 5826 } 5827 r.append(pg.info.name); 5828 } 5829 } else { 5830 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5831 + pg.info.packageName + " ignored: original from " 5832 + cur.info.packageName); 5833 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5834 if (r == null) { 5835 r = new StringBuilder(256); 5836 } else { 5837 r.append(' '); 5838 } 5839 r.append("DUP:"); 5840 r.append(pg.info.name); 5841 } 5842 } 5843 } 5844 if (r != null) { 5845 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5846 } 5847 5848 N = pkg.permissions.size(); 5849 r = null; 5850 for (i=0; i<N; i++) { 5851 PackageParser.Permission p = pkg.permissions.get(i); 5852 HashMap<String, BasePermission> permissionMap = 5853 p.tree ? mSettings.mPermissionTrees 5854 : mSettings.mPermissions; 5855 p.group = mPermissionGroups.get(p.info.group); 5856 if (p.info.group == null || p.group != null) { 5857 BasePermission bp = permissionMap.get(p.info.name); 5858 if (bp == null) { 5859 bp = new BasePermission(p.info.name, p.info.packageName, 5860 BasePermission.TYPE_NORMAL); 5861 permissionMap.put(p.info.name, bp); 5862 } 5863 if (bp.perm == null) { 5864 if (bp.sourcePackage != null 5865 && !bp.sourcePackage.equals(p.info.packageName)) { 5866 // If this is a permission that was formerly defined by a non-system 5867 // app, but is now defined by a system app (following an upgrade), 5868 // discard the previous declaration and consider the system's to be 5869 // canonical. 5870 if (isSystemApp(p.owner)) { 5871 String msg = "New decl " + p.owner + " of permission " 5872 + p.info.name + " is system"; 5873 reportSettingsProblem(Log.WARN, msg); 5874 bp.sourcePackage = null; 5875 } 5876 } 5877 if (bp.sourcePackage == null 5878 || bp.sourcePackage.equals(p.info.packageName)) { 5879 BasePermission tree = findPermissionTreeLP(p.info.name); 5880 if (tree == null 5881 || tree.sourcePackage.equals(p.info.packageName)) { 5882 bp.packageSetting = pkgSetting; 5883 bp.perm = p; 5884 bp.uid = pkg.applicationInfo.uid; 5885 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5886 if (r == null) { 5887 r = new StringBuilder(256); 5888 } else { 5889 r.append(' '); 5890 } 5891 r.append(p.info.name); 5892 } 5893 } else { 5894 Slog.w(TAG, "Permission " + p.info.name + " from package " 5895 + p.info.packageName + " ignored: base tree " 5896 + tree.name + " is from package " 5897 + tree.sourcePackage); 5898 } 5899 } else { 5900 Slog.w(TAG, "Permission " + p.info.name + " from package " 5901 + p.info.packageName + " ignored: original from " 5902 + bp.sourcePackage); 5903 } 5904 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5905 if (r == null) { 5906 r = new StringBuilder(256); 5907 } else { 5908 r.append(' '); 5909 } 5910 r.append("DUP:"); 5911 r.append(p.info.name); 5912 } 5913 if (bp.perm == p) { 5914 bp.protectionLevel = p.info.protectionLevel; 5915 } 5916 } else { 5917 Slog.w(TAG, "Permission " + p.info.name + " from package " 5918 + p.info.packageName + " ignored: no group " 5919 + p.group); 5920 } 5921 } 5922 if (r != null) { 5923 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 5924 } 5925 5926 N = pkg.instrumentation.size(); 5927 r = null; 5928 for (i=0; i<N; i++) { 5929 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5930 a.info.packageName = pkg.applicationInfo.packageName; 5931 a.info.sourceDir = pkg.applicationInfo.sourceDir; 5932 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 5933 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 5934 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 5935 a.info.dataDir = pkg.applicationInfo.dataDir; 5936 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 5937 mInstrumentation.put(a.getComponentName(), a); 5938 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5939 if (r == null) { 5940 r = new StringBuilder(256); 5941 } else { 5942 r.append(' '); 5943 } 5944 r.append(a.info.name); 5945 } 5946 } 5947 if (r != null) { 5948 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 5949 } 5950 5951 if (pkg.protectedBroadcasts != null) { 5952 N = pkg.protectedBroadcasts.size(); 5953 for (i=0; i<N; i++) { 5954 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 5955 } 5956 } 5957 5958 pkgSetting.setTimeStamp(scanFileTime); 5959 5960 // Create idmap files for pairs of (packages, overlay packages). 5961 // Note: "android", ie framework-res.apk, is handled by native layers. 5962 if (pkg.mOverlayTarget != null) { 5963 // This is an overlay package. 5964 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 5965 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 5966 mOverlays.put(pkg.mOverlayTarget, 5967 new HashMap<String, PackageParser.Package>()); 5968 } 5969 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 5970 map.put(pkg.packageName, pkg); 5971 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 5972 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 5973 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 5974 return null; 5975 } 5976 } 5977 } else if (mOverlays.containsKey(pkg.packageName) && 5978 !pkg.packageName.equals("android")) { 5979 // This is a regular package, with one or more known overlay packages. 5980 createIdmapsForPackageLI(pkg); 5981 } 5982 } 5983 5984 return pkg; 5985 } 5986 5987 /** 5988 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 5989 * i.e, so that all packages can be run inside a single process if required. 5990 * 5991 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 5992 * this function will either try and make the ABI for all packages in {@code packagesForUser} 5993 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 5994 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 5995 * updating a package that belongs to a shared user. 5996 */ 5997 private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 5998 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 5999 String requiredInstructionSet = null; 6000 if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) { 6001 requiredInstructionSet = VMRuntime.getInstructionSet( 6002 scannedPackage.applicationInfo.cpuAbi); 6003 } 6004 6005 PackageSetting requirer = null; 6006 for (PackageSetting ps : packagesForUser) { 6007 // If packagesForUser contains scannedPackage, we skip it. This will happen 6008 // when scannedPackage is an update of an existing package. Without this check, 6009 // we will never be able to change the ABI of any package belonging to a shared 6010 // user, even if it's compatible with other packages. 6011 if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) { 6012 if (ps.cpuAbiString == null) { 6013 continue; 6014 } 6015 6016 final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString); 6017 if (requiredInstructionSet != null) { 6018 if (!instructionSet.equals(requiredInstructionSet)) { 6019 // We have a mismatch between instruction sets (say arm vs arm64). 6020 // bail out. 6021 String errorMessage = "Instruction set mismatch, " 6022 + ((requirer == null) ? "[caller]" : requirer) 6023 + " requires " + requiredInstructionSet + " whereas " + ps 6024 + " requires " + instructionSet; 6025 Slog.e(TAG, errorMessage); 6026 6027 reportSettingsProblem(Log.WARN, errorMessage); 6028 // Give up, don't bother making any other changes to the package settings. 6029 return false; 6030 } 6031 } else { 6032 requiredInstructionSet = instructionSet; 6033 requirer = ps; 6034 } 6035 } 6036 } 6037 6038 if (requiredInstructionSet != null) { 6039 String adjustedAbi; 6040 if (requirer != null) { 6041 // requirer != null implies that either scannedPackage was null or that scannedPackage 6042 // did not require an ABI, in which case we have to adjust scannedPackage to match 6043 // the ABI of the set (which is the same as requirer's ABI) 6044 adjustedAbi = requirer.cpuAbiString; 6045 if (scannedPackage != null) { 6046 scannedPackage.applicationInfo.cpuAbi = adjustedAbi; 6047 } 6048 } else { 6049 // requirer == null implies that we're updating all ABIs in the set to 6050 // match scannedPackage. 6051 adjustedAbi = scannedPackage.applicationInfo.cpuAbi; 6052 } 6053 6054 for (PackageSetting ps : packagesForUser) { 6055 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6056 if (ps.cpuAbiString != null) { 6057 continue; 6058 } 6059 6060 ps.cpuAbiString = adjustedAbi; 6061 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6062 ps.pkg.applicationInfo.cpuAbi = adjustedAbi; 6063 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6064 6065 if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) { 6066 ps.cpuAbiString = null; 6067 ps.pkg.applicationInfo.cpuAbi = null; 6068 return false; 6069 } else { 6070 mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet()); 6071 } 6072 } 6073 } 6074 } 6075 } 6076 6077 return true; 6078 } 6079 6080 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6081 synchronized (mPackages) { 6082 mResolverReplaced = true; 6083 // Set up information for custom user intent resolution activity. 6084 mResolveActivity.applicationInfo = pkg.applicationInfo; 6085 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6086 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6087 mResolveActivity.processName = null; 6088 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6089 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6090 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6091 mResolveActivity.theme = 0; 6092 mResolveActivity.exported = true; 6093 mResolveActivity.enabled = true; 6094 mResolveInfo.activityInfo = mResolveActivity; 6095 mResolveInfo.priority = 0; 6096 mResolveInfo.preferredOrder = 0; 6097 mResolveInfo.match = 0; 6098 mResolveComponentName = mCustomResolverComponentName; 6099 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6100 mResolveComponentName); 6101 } 6102 } 6103 6104 private String calculateApkRoot(final String codePathString) { 6105 final File codePath = new File(codePathString); 6106 final File codeRoot; 6107 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6108 codeRoot = Environment.getRootDirectory(); 6109 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6110 codeRoot = Environment.getOemDirectory(); 6111 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6112 codeRoot = Environment.getVendorDirectory(); 6113 } else { 6114 // Unrecognized code path; take its top real segment as the apk root: 6115 // e.g. /something/app/blah.apk => /something 6116 try { 6117 File f = codePath.getCanonicalFile(); 6118 File parent = f.getParentFile(); // non-null because codePath is a file 6119 File tmp; 6120 while ((tmp = parent.getParentFile()) != null) { 6121 f = parent; 6122 parent = tmp; 6123 } 6124 codeRoot = f; 6125 Slog.w(TAG, "Unrecognized code path " 6126 + codePath + " - using " + codeRoot); 6127 } catch (IOException e) { 6128 // Can't canonicalize the lib path -- shenanigans? 6129 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6130 return Environment.getRootDirectory().getPath(); 6131 } 6132 } 6133 return codeRoot.getPath(); 6134 } 6135 6136 // This is the initial scan-time determination of how to handle a given 6137 // package for purposes of native library location. 6138 private void setInternalAppNativeLibraryPath(PackageParser.Package pkg, 6139 PackageSetting pkgSetting) { 6140 // "bundled" here means system-installed with no overriding update 6141 final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg); 6142 final File codeFile = new File(pkg.applicationInfo.getCodePath()); 6143 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6144 6145 String nativeLibraryPath = null; 6146 if (bundledApk) { 6147 // If "/system/lib64/apkname" exists, assume that is the per-package 6148 // native library directory to use; otherwise use "/system/lib/apkname". 6149 String apkRoot = calculateApkRoot(pkg.applicationInfo.getCodePath()); 6150 File lib64 = new File(apkRoot, LIB64_DIR_NAME); 6151 File packLib64 = new File(lib64, apkName); 6152 File libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME); 6153 nativeLibraryPath = (new File(libDir, apkName)).getAbsolutePath(); 6154 } else if (isApkFile(codeFile)) { 6155 // Monolithic install 6156 nativeLibraryPath = (new File(mAppLibInstallDir, apkName)).getAbsolutePath(); 6157 } else { 6158 // Cluster install 6159 // TODO: pipe through abiOverride 6160 String[] abiList = Build.SUPPORTED_ABIS; 6161 NativeLibraryHelper.Handle handle = null; 6162 try { 6163 handle = NativeLibraryHelper.Handle.create(codeFile); 6164 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && 6165 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6166 abiList = Build.SUPPORTED_32_BIT_ABIS; 6167 } 6168 6169 final int abiIndex = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6170 if (abiIndex >= 0) { 6171 final File baseLibFile = new File(codeFile, LIB_DIR_NAME); 6172 final String abi = Build.SUPPORTED_ABIS[abiIndex]; 6173 final String instructionSet = VMRuntime.getInstructionSet(abi); 6174 nativeLibraryPath = new File(baseLibFile, instructionSet).getAbsolutePath(); 6175 } 6176 } catch (IOException e) { 6177 Slog.e(TAG, "Failed to detect native libraries", e); 6178 } finally { 6179 IoUtils.closeQuietly(handle); 6180 } 6181 } 6182 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath; 6183 // pkgSetting might be null during rescan following uninstall of updates 6184 // to a bundled app, so accommodate that possibility. The settings in 6185 // that case will be established later from the parsed package. 6186 if (pkgSetting != null) { 6187 pkgSetting.nativeLibraryPathString = nativeLibraryPath; 6188 } 6189 } 6190 6191 // Deduces the required ABI of an upgraded system app. 6192 private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) { 6193 final String apkRoot = calculateApkRoot(pkg.applicationInfo.getCodePath()); 6194 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6195 6196 // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>" 6197 // or similar. 6198 final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath()); 6199 final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath()); 6200 6201 // Assume that the bundled native libraries always correspond to the 6202 // most preferred 32 or 64 bit ABI. 6203 if (lib64.exists()) { 6204 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6205 pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0]; 6206 } else if (lib.exists()) { 6207 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6208 pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0]; 6209 } else { 6210 // This is the case where the app has no native code. 6211 pkg.applicationInfo.cpuAbi = null; 6212 pkgSetting.cpuAbiString = null; 6213 } 6214 } 6215 6216 private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle, 6217 final File nativeLibraryDir, String[] abiList) throws IOException { 6218 if (!nativeLibraryDir.isDirectory()) { 6219 nativeLibraryDir.delete(); 6220 6221 if (!nativeLibraryDir.mkdir()) { 6222 throw new IOException("Cannot create " + nativeLibraryDir.getPath()); 6223 } 6224 6225 try { 6226 Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6227 } catch (ErrnoException e) { 6228 throw new IOException("Cannot chmod native library directory " 6229 + nativeLibraryDir.getPath(), e); 6230 } 6231 } else if (!SELinux.restorecon(nativeLibraryDir)) { 6232 throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath()); 6233 } 6234 6235 /* 6236 * If this is an internal application or our nativeLibraryPath points to 6237 * the app-lib directory, unpack the libraries if necessary. 6238 */ 6239 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6240 if (abi >= 0) { 6241 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, 6242 nativeLibraryDir, Build.SUPPORTED_ABIS[abi]); 6243 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6244 return copyRet; 6245 } 6246 } 6247 6248 return abi; 6249 } 6250 6251 private void killApplication(String pkgName, int appId, String reason) { 6252 // Request the ActivityManager to kill the process(only for existing packages) 6253 // so that we do not end up in a confused state while the user is still using the older 6254 // version of the application while the new one gets installed. 6255 IActivityManager am = ActivityManagerNative.getDefault(); 6256 if (am != null) { 6257 try { 6258 am.killApplicationWithAppId(pkgName, appId, reason); 6259 } catch (RemoteException e) { 6260 } 6261 } 6262 } 6263 6264 void removePackageLI(PackageSetting ps, boolean chatty) { 6265 if (DEBUG_INSTALL) { 6266 if (chatty) 6267 Log.d(TAG, "Removing package " + ps.name); 6268 } 6269 6270 // writer 6271 synchronized (mPackages) { 6272 mPackages.remove(ps.name); 6273 if (ps.codePathString != null) { 6274 mAppDirs.remove(ps.codePathString); 6275 } 6276 6277 final PackageParser.Package pkg = ps.pkg; 6278 if (pkg != null) { 6279 cleanPackageDataStructuresLILPw(pkg, chatty); 6280 } 6281 } 6282 } 6283 6284 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6285 if (DEBUG_INSTALL) { 6286 if (chatty) 6287 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6288 } 6289 6290 // writer 6291 synchronized (mPackages) { 6292 mPackages.remove(pkg.applicationInfo.packageName); 6293 if (pkg.codePath != null) { 6294 mAppDirs.remove(pkg.codePath); 6295 } 6296 cleanPackageDataStructuresLILPw(pkg, chatty); 6297 } 6298 } 6299 6300 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6301 int N = pkg.providers.size(); 6302 StringBuilder r = null; 6303 int i; 6304 for (i=0; i<N; i++) { 6305 PackageParser.Provider p = pkg.providers.get(i); 6306 mProviders.removeProvider(p); 6307 if (p.info.authority == null) { 6308 6309 /* There was another ContentProvider with this authority when 6310 * this app was installed so this authority is null, 6311 * Ignore it as we don't have to unregister the provider. 6312 */ 6313 continue; 6314 } 6315 String names[] = p.info.authority.split(";"); 6316 for (int j = 0; j < names.length; j++) { 6317 if (mProvidersByAuthority.get(names[j]) == p) { 6318 mProvidersByAuthority.remove(names[j]); 6319 if (DEBUG_REMOVE) { 6320 if (chatty) 6321 Log.d(TAG, "Unregistered content provider: " + names[j] 6322 + ", className = " + p.info.name + ", isSyncable = " 6323 + p.info.isSyncable); 6324 } 6325 } 6326 } 6327 if (DEBUG_REMOVE && chatty) { 6328 if (r == null) { 6329 r = new StringBuilder(256); 6330 } else { 6331 r.append(' '); 6332 } 6333 r.append(p.info.name); 6334 } 6335 } 6336 if (r != null) { 6337 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6338 } 6339 6340 N = pkg.services.size(); 6341 r = null; 6342 for (i=0; i<N; i++) { 6343 PackageParser.Service s = pkg.services.get(i); 6344 mServices.removeService(s); 6345 if (chatty) { 6346 if (r == null) { 6347 r = new StringBuilder(256); 6348 } else { 6349 r.append(' '); 6350 } 6351 r.append(s.info.name); 6352 } 6353 } 6354 if (r != null) { 6355 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6356 } 6357 6358 N = pkg.receivers.size(); 6359 r = null; 6360 for (i=0; i<N; i++) { 6361 PackageParser.Activity a = pkg.receivers.get(i); 6362 mReceivers.removeActivity(a, "receiver"); 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, " Receivers: " + r); 6374 } 6375 6376 N = pkg.activities.size(); 6377 r = null; 6378 for (i=0; i<N; i++) { 6379 PackageParser.Activity a = pkg.activities.get(i); 6380 mActivities.removeActivity(a, "activity"); 6381 if (DEBUG_REMOVE && chatty) { 6382 if (r == null) { 6383 r = new StringBuilder(256); 6384 } else { 6385 r.append(' '); 6386 } 6387 r.append(a.info.name); 6388 } 6389 } 6390 if (r != null) { 6391 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6392 } 6393 6394 N = pkg.permissions.size(); 6395 r = null; 6396 for (i=0; i<N; i++) { 6397 PackageParser.Permission p = pkg.permissions.get(i); 6398 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6399 if (bp == null) { 6400 bp = mSettings.mPermissionTrees.get(p.info.name); 6401 } 6402 if (bp != null && bp.perm == p) { 6403 bp.perm = null; 6404 if (DEBUG_REMOVE && chatty) { 6405 if (r == null) { 6406 r = new StringBuilder(256); 6407 } else { 6408 r.append(' '); 6409 } 6410 r.append(p.info.name); 6411 } 6412 } 6413 } 6414 if (r != null) { 6415 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6416 } 6417 6418 N = pkg.instrumentation.size(); 6419 r = null; 6420 for (i=0; i<N; i++) { 6421 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6422 mInstrumentation.remove(a.getComponentName()); 6423 if (DEBUG_REMOVE && chatty) { 6424 if (r == null) { 6425 r = new StringBuilder(256); 6426 } else { 6427 r.append(' '); 6428 } 6429 r.append(a.info.name); 6430 } 6431 } 6432 if (r != null) { 6433 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6434 } 6435 6436 r = null; 6437 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6438 // Only system apps can hold shared libraries. 6439 if (pkg.libraryNames != null) { 6440 for (i=0; i<pkg.libraryNames.size(); i++) { 6441 String name = pkg.libraryNames.get(i); 6442 SharedLibraryEntry cur = mSharedLibraries.get(name); 6443 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6444 mSharedLibraries.remove(name); 6445 if (DEBUG_REMOVE && chatty) { 6446 if (r == null) { 6447 r = new StringBuilder(256); 6448 } else { 6449 r.append(' '); 6450 } 6451 r.append(name); 6452 } 6453 } 6454 } 6455 } 6456 } 6457 if (r != null) { 6458 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6459 } 6460 } 6461 6462 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6463 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6464 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6465 return true; 6466 } 6467 } 6468 return false; 6469 } 6470 6471 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6472 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6473 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6474 6475 private void updatePermissionsLPw(String changingPkg, 6476 PackageParser.Package pkgInfo, int flags) { 6477 // Make sure there are no dangling permission trees. 6478 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6479 while (it.hasNext()) { 6480 final BasePermission bp = it.next(); 6481 if (bp.packageSetting == null) { 6482 // We may not yet have parsed the package, so just see if 6483 // we still know about its settings. 6484 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6485 } 6486 if (bp.packageSetting == null) { 6487 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6488 + " from package " + bp.sourcePackage); 6489 it.remove(); 6490 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6491 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6492 Slog.i(TAG, "Removing old permission tree: " + bp.name 6493 + " from package " + bp.sourcePackage); 6494 flags |= UPDATE_PERMISSIONS_ALL; 6495 it.remove(); 6496 } 6497 } 6498 } 6499 6500 // Make sure all dynamic permissions have been assigned to a package, 6501 // and make sure there are no dangling permissions. 6502 it = mSettings.mPermissions.values().iterator(); 6503 while (it.hasNext()) { 6504 final BasePermission bp = it.next(); 6505 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6506 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6507 + bp.name + " pkg=" + bp.sourcePackage 6508 + " info=" + bp.pendingInfo); 6509 if (bp.packageSetting == null && bp.pendingInfo != null) { 6510 final BasePermission tree = findPermissionTreeLP(bp.name); 6511 if (tree != null && tree.perm != null) { 6512 bp.packageSetting = tree.packageSetting; 6513 bp.perm = new PackageParser.Permission(tree.perm.owner, 6514 new PermissionInfo(bp.pendingInfo)); 6515 bp.perm.info.packageName = tree.perm.info.packageName; 6516 bp.perm.info.name = bp.name; 6517 bp.uid = tree.uid; 6518 } 6519 } 6520 } 6521 if (bp.packageSetting == null) { 6522 // We may not yet have parsed the package, so just see if 6523 // we still know about its settings. 6524 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6525 } 6526 if (bp.packageSetting == null) { 6527 Slog.w(TAG, "Removing dangling permission: " + bp.name 6528 + " from package " + bp.sourcePackage); 6529 it.remove(); 6530 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6531 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6532 Slog.i(TAG, "Removing old permission: " + bp.name 6533 + " from package " + bp.sourcePackage); 6534 flags |= UPDATE_PERMISSIONS_ALL; 6535 it.remove(); 6536 } 6537 } 6538 } 6539 6540 // Now update the permissions for all packages, in particular 6541 // replace the granted permissions of the system packages. 6542 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6543 for (PackageParser.Package pkg : mPackages.values()) { 6544 if (pkg != pkgInfo) { 6545 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6546 } 6547 } 6548 } 6549 6550 if (pkgInfo != null) { 6551 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6552 } 6553 } 6554 6555 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6556 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6557 if (ps == null) { 6558 return; 6559 } 6560 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6561 HashSet<String> origPermissions = gp.grantedPermissions; 6562 boolean changedPermission = false; 6563 6564 if (replace) { 6565 ps.permissionsFixed = false; 6566 if (gp == ps) { 6567 origPermissions = new HashSet<String>(gp.grantedPermissions); 6568 gp.grantedPermissions.clear(); 6569 gp.gids = mGlobalGids; 6570 } 6571 } 6572 6573 if (gp.gids == null) { 6574 gp.gids = mGlobalGids; 6575 } 6576 6577 final int N = pkg.requestedPermissions.size(); 6578 for (int i=0; i<N; i++) { 6579 final String name = pkg.requestedPermissions.get(i); 6580 final boolean required = pkg.requestedPermissionsRequired.get(i); 6581 final BasePermission bp = mSettings.mPermissions.get(name); 6582 if (DEBUG_INSTALL) { 6583 if (gp != ps) { 6584 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6585 } 6586 } 6587 6588 if (bp == null || bp.packageSetting == null) { 6589 Slog.w(TAG, "Unknown permission " + name 6590 + " in package " + pkg.packageName); 6591 continue; 6592 } 6593 6594 final String perm = bp.name; 6595 boolean allowed; 6596 boolean allowedSig = false; 6597 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6598 if (level == PermissionInfo.PROTECTION_NORMAL 6599 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6600 // We grant a normal or dangerous permission if any of the following 6601 // are true: 6602 // 1) The permission is required 6603 // 2) The permission is optional, but was granted in the past 6604 // 3) The permission is optional, but was requested by an 6605 // app in /system (not /data) 6606 // 6607 // Otherwise, reject the permission. 6608 allowed = (required || origPermissions.contains(perm) 6609 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6610 } else if (bp.packageSetting == null) { 6611 // This permission is invalid; skip it. 6612 allowed = false; 6613 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6614 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6615 if (allowed) { 6616 allowedSig = true; 6617 } 6618 } else { 6619 allowed = false; 6620 } 6621 if (DEBUG_INSTALL) { 6622 if (gp != ps) { 6623 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6624 } 6625 } 6626 if (allowed) { 6627 if (!isSystemApp(ps) && ps.permissionsFixed) { 6628 // If this is an existing, non-system package, then 6629 // we can't add any new permissions to it. 6630 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6631 // Except... if this is a permission that was added 6632 // to the platform (note: need to only do this when 6633 // updating the platform). 6634 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6635 } 6636 } 6637 if (allowed) { 6638 if (!gp.grantedPermissions.contains(perm)) { 6639 changedPermission = true; 6640 gp.grantedPermissions.add(perm); 6641 gp.gids = appendInts(gp.gids, bp.gids); 6642 } else if (!ps.haveGids) { 6643 gp.gids = appendInts(gp.gids, bp.gids); 6644 } 6645 } else { 6646 Slog.w(TAG, "Not granting permission " + perm 6647 + " to package " + pkg.packageName 6648 + " because it was previously installed without"); 6649 } 6650 } else { 6651 if (gp.grantedPermissions.remove(perm)) { 6652 changedPermission = true; 6653 gp.gids = removeInts(gp.gids, bp.gids); 6654 Slog.i(TAG, "Un-granting permission " + perm 6655 + " from package " + pkg.packageName 6656 + " (protectionLevel=" + bp.protectionLevel 6657 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6658 + ")"); 6659 } else { 6660 Slog.w(TAG, "Not granting permission " + perm 6661 + " to package " + pkg.packageName 6662 + " (protectionLevel=" + bp.protectionLevel 6663 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6664 + ")"); 6665 } 6666 } 6667 } 6668 6669 if ((changedPermission || replace) && !ps.permissionsFixed && 6670 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6671 // This is the first that we have heard about this package, so the 6672 // permissions we have now selected are fixed until explicitly 6673 // changed. 6674 ps.permissionsFixed = true; 6675 } 6676 ps.haveGids = true; 6677 } 6678 6679 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6680 boolean allowed = false; 6681 final int NP = PackageParser.NEW_PERMISSIONS.length; 6682 for (int ip=0; ip<NP; ip++) { 6683 final PackageParser.NewPermissionInfo npi 6684 = PackageParser.NEW_PERMISSIONS[ip]; 6685 if (npi.name.equals(perm) 6686 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6687 allowed = true; 6688 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6689 + pkg.packageName); 6690 break; 6691 } 6692 } 6693 return allowed; 6694 } 6695 6696 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6697 BasePermission bp, HashSet<String> origPermissions) { 6698 boolean allowed; 6699 allowed = (compareSignatures( 6700 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6701 == PackageManager.SIGNATURE_MATCH) 6702 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6703 == PackageManager.SIGNATURE_MATCH); 6704 if (!allowed && (bp.protectionLevel 6705 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6706 if (isSystemApp(pkg)) { 6707 // For updated system applications, a system permission 6708 // is granted only if it had been defined by the original application. 6709 if (isUpdatedSystemApp(pkg)) { 6710 final PackageSetting sysPs = mSettings 6711 .getDisabledSystemPkgLPr(pkg.packageName); 6712 final GrantedPermissions origGp = sysPs.sharedUser != null 6713 ? sysPs.sharedUser : sysPs; 6714 6715 if (origGp.grantedPermissions.contains(perm)) { 6716 // If the original was granted this permission, we take 6717 // that grant decision as read and propagate it to the 6718 // update. 6719 allowed = true; 6720 } else { 6721 // The system apk may have been updated with an older 6722 // version of the one on the data partition, but which 6723 // granted a new system permission that it didn't have 6724 // before. In this case we do want to allow the app to 6725 // now get the new permission if the ancestral apk is 6726 // privileged to get it. 6727 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6728 for (int j=0; 6729 j<sysPs.pkg.requestedPermissions.size(); j++) { 6730 if (perm.equals( 6731 sysPs.pkg.requestedPermissions.get(j))) { 6732 allowed = true; 6733 break; 6734 } 6735 } 6736 } 6737 } 6738 } else { 6739 allowed = isPrivilegedApp(pkg); 6740 } 6741 } 6742 } 6743 if (!allowed && (bp.protectionLevel 6744 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6745 // For development permissions, a development permission 6746 // is granted only if it was already granted. 6747 allowed = origPermissions.contains(perm); 6748 } 6749 return allowed; 6750 } 6751 6752 final class ActivityIntentResolver 6753 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6754 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6755 boolean defaultOnly, int userId) { 6756 if (!sUserManager.exists(userId)) return null; 6757 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6758 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6759 } 6760 6761 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6762 int userId) { 6763 if (!sUserManager.exists(userId)) return null; 6764 mFlags = flags; 6765 return super.queryIntent(intent, resolvedType, 6766 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6767 } 6768 6769 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6770 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6771 if (!sUserManager.exists(userId)) return null; 6772 if (packageActivities == null) { 6773 return null; 6774 } 6775 mFlags = flags; 6776 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6777 final int N = packageActivities.size(); 6778 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6779 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6780 6781 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6782 for (int i = 0; i < N; ++i) { 6783 intentFilters = packageActivities.get(i).intents; 6784 if (intentFilters != null && intentFilters.size() > 0) { 6785 PackageParser.ActivityIntentInfo[] array = 6786 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6787 intentFilters.toArray(array); 6788 listCut.add(array); 6789 } 6790 } 6791 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6792 } 6793 6794 public final void addActivity(PackageParser.Activity a, String type) { 6795 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6796 mActivities.put(a.getComponentName(), a); 6797 if (DEBUG_SHOW_INFO) 6798 Log.v( 6799 TAG, " " + type + " " + 6800 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6801 if (DEBUG_SHOW_INFO) 6802 Log.v(TAG, " Class=" + a.info.name); 6803 final int NI = a.intents.size(); 6804 for (int j=0; j<NI; j++) { 6805 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6806 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6807 intent.setPriority(0); 6808 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6809 + a.className + " with priority > 0, forcing to 0"); 6810 } 6811 if (DEBUG_SHOW_INFO) { 6812 Log.v(TAG, " IntentFilter:"); 6813 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6814 } 6815 if (!intent.debugCheck()) { 6816 Log.w(TAG, "==> For Activity " + a.info.name); 6817 } 6818 addFilter(intent); 6819 } 6820 } 6821 6822 public final void removeActivity(PackageParser.Activity a, String type) { 6823 mActivities.remove(a.getComponentName()); 6824 if (DEBUG_SHOW_INFO) { 6825 Log.v(TAG, " " + type + " " 6826 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6827 : a.info.name) + ":"); 6828 Log.v(TAG, " Class=" + a.info.name); 6829 } 6830 final int NI = a.intents.size(); 6831 for (int j=0; j<NI; j++) { 6832 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6833 if (DEBUG_SHOW_INFO) { 6834 Log.v(TAG, " IntentFilter:"); 6835 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6836 } 6837 removeFilter(intent); 6838 } 6839 } 6840 6841 @Override 6842 protected boolean allowFilterResult( 6843 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 6844 ActivityInfo filterAi = filter.activity.info; 6845 for (int i=dest.size()-1; i>=0; i--) { 6846 ActivityInfo destAi = dest.get(i).activityInfo; 6847 if (destAi.name == filterAi.name 6848 && destAi.packageName == filterAi.packageName) { 6849 return false; 6850 } 6851 } 6852 return true; 6853 } 6854 6855 @Override 6856 protected ActivityIntentInfo[] newArray(int size) { 6857 return new ActivityIntentInfo[size]; 6858 } 6859 6860 @Override 6861 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 6862 if (!sUserManager.exists(userId)) return true; 6863 PackageParser.Package p = filter.activity.owner; 6864 if (p != null) { 6865 PackageSetting ps = (PackageSetting)p.mExtras; 6866 if (ps != null) { 6867 // System apps are never considered stopped for purposes of 6868 // filtering, because there may be no way for the user to 6869 // actually re-launch them. 6870 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 6871 && ps.getStopped(userId); 6872 } 6873 } 6874 return false; 6875 } 6876 6877 @Override 6878 protected boolean isPackageForFilter(String packageName, 6879 PackageParser.ActivityIntentInfo info) { 6880 return packageName.equals(info.activity.owner.packageName); 6881 } 6882 6883 @Override 6884 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 6885 int match, int userId) { 6886 if (!sUserManager.exists(userId)) return null; 6887 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 6888 return null; 6889 } 6890 final PackageParser.Activity activity = info.activity; 6891 if (mSafeMode && (activity.info.applicationInfo.flags 6892 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6893 return null; 6894 } 6895 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 6896 if (ps == null) { 6897 return null; 6898 } 6899 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 6900 ps.readUserState(userId), userId); 6901 if (ai == null) { 6902 return null; 6903 } 6904 final ResolveInfo res = new ResolveInfo(); 6905 res.activityInfo = ai; 6906 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 6907 res.filter = info; 6908 } 6909 res.priority = info.getPriority(); 6910 res.preferredOrder = activity.owner.mPreferredOrder; 6911 //System.out.println("Result: " + res.activityInfo.className + 6912 // " = " + res.priority); 6913 res.match = match; 6914 res.isDefault = info.hasDefault; 6915 res.labelRes = info.labelRes; 6916 res.nonLocalizedLabel = info.nonLocalizedLabel; 6917 if (userNeedsBadging(userId)) { 6918 res.noResourceId = true; 6919 } else { 6920 res.icon = info.icon; 6921 } 6922 res.system = isSystemApp(res.activityInfo.applicationInfo); 6923 return res; 6924 } 6925 6926 @Override 6927 protected void sortResults(List<ResolveInfo> results) { 6928 Collections.sort(results, mResolvePrioritySorter); 6929 } 6930 6931 @Override 6932 protected void dumpFilter(PrintWriter out, String prefix, 6933 PackageParser.ActivityIntentInfo filter) { 6934 out.print(prefix); out.print( 6935 Integer.toHexString(System.identityHashCode(filter.activity))); 6936 out.print(' '); 6937 filter.activity.printComponentShortName(out); 6938 out.print(" filter "); 6939 out.println(Integer.toHexString(System.identityHashCode(filter))); 6940 } 6941 6942// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 6943// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 6944// final List<ResolveInfo> retList = Lists.newArrayList(); 6945// while (i.hasNext()) { 6946// final ResolveInfo resolveInfo = i.next(); 6947// if (isEnabledLP(resolveInfo.activityInfo)) { 6948// retList.add(resolveInfo); 6949// } 6950// } 6951// return retList; 6952// } 6953 6954 // Keys are String (activity class name), values are Activity. 6955 private final HashMap<ComponentName, PackageParser.Activity> mActivities 6956 = new HashMap<ComponentName, PackageParser.Activity>(); 6957 private int mFlags; 6958 } 6959 6960 private final class ServiceIntentResolver 6961 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 6962 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6963 boolean defaultOnly, int userId) { 6964 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6965 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6966 } 6967 6968 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6969 int userId) { 6970 if (!sUserManager.exists(userId)) return null; 6971 mFlags = flags; 6972 return super.queryIntent(intent, resolvedType, 6973 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6974 } 6975 6976 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6977 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 6978 if (!sUserManager.exists(userId)) return null; 6979 if (packageServices == null) { 6980 return null; 6981 } 6982 mFlags = flags; 6983 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6984 final int N = packageServices.size(); 6985 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 6986 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 6987 6988 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 6989 for (int i = 0; i < N; ++i) { 6990 intentFilters = packageServices.get(i).intents; 6991 if (intentFilters != null && intentFilters.size() > 0) { 6992 PackageParser.ServiceIntentInfo[] array = 6993 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 6994 intentFilters.toArray(array); 6995 listCut.add(array); 6996 } 6997 } 6998 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6999 } 7000 7001 public final void addService(PackageParser.Service s) { 7002 mServices.put(s.getComponentName(), s); 7003 if (DEBUG_SHOW_INFO) { 7004 Log.v(TAG, " " 7005 + (s.info.nonLocalizedLabel != null 7006 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7007 Log.v(TAG, " Class=" + s.info.name); 7008 } 7009 final int NI = s.intents.size(); 7010 int j; 7011 for (j=0; j<NI; j++) { 7012 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7013 if (DEBUG_SHOW_INFO) { 7014 Log.v(TAG, " IntentFilter:"); 7015 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7016 } 7017 if (!intent.debugCheck()) { 7018 Log.w(TAG, "==> For Service " + s.info.name); 7019 } 7020 addFilter(intent); 7021 } 7022 } 7023 7024 public final void removeService(PackageParser.Service s) { 7025 mServices.remove(s.getComponentName()); 7026 if (DEBUG_SHOW_INFO) { 7027 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7028 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7029 Log.v(TAG, " Class=" + s.info.name); 7030 } 7031 final int NI = s.intents.size(); 7032 int j; 7033 for (j=0; j<NI; j++) { 7034 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7035 if (DEBUG_SHOW_INFO) { 7036 Log.v(TAG, " IntentFilter:"); 7037 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7038 } 7039 removeFilter(intent); 7040 } 7041 } 7042 7043 @Override 7044 protected boolean allowFilterResult( 7045 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7046 ServiceInfo filterSi = filter.service.info; 7047 for (int i=dest.size()-1; i>=0; i--) { 7048 ServiceInfo destAi = dest.get(i).serviceInfo; 7049 if (destAi.name == filterSi.name 7050 && destAi.packageName == filterSi.packageName) { 7051 return false; 7052 } 7053 } 7054 return true; 7055 } 7056 7057 @Override 7058 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7059 return new PackageParser.ServiceIntentInfo[size]; 7060 } 7061 7062 @Override 7063 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7064 if (!sUserManager.exists(userId)) return true; 7065 PackageParser.Package p = filter.service.owner; 7066 if (p != null) { 7067 PackageSetting ps = (PackageSetting)p.mExtras; 7068 if (ps != null) { 7069 // System apps are never considered stopped for purposes of 7070 // filtering, because there may be no way for the user to 7071 // actually re-launch them. 7072 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7073 && ps.getStopped(userId); 7074 } 7075 } 7076 return false; 7077 } 7078 7079 @Override 7080 protected boolean isPackageForFilter(String packageName, 7081 PackageParser.ServiceIntentInfo info) { 7082 return packageName.equals(info.service.owner.packageName); 7083 } 7084 7085 @Override 7086 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7087 int match, int userId) { 7088 if (!sUserManager.exists(userId)) return null; 7089 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7090 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7091 return null; 7092 } 7093 final PackageParser.Service service = info.service; 7094 if (mSafeMode && (service.info.applicationInfo.flags 7095 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7096 return null; 7097 } 7098 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7099 if (ps == null) { 7100 return null; 7101 } 7102 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7103 ps.readUserState(userId), userId); 7104 if (si == null) { 7105 return null; 7106 } 7107 final ResolveInfo res = new ResolveInfo(); 7108 res.serviceInfo = si; 7109 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7110 res.filter = filter; 7111 } 7112 res.priority = info.getPriority(); 7113 res.preferredOrder = service.owner.mPreferredOrder; 7114 //System.out.println("Result: " + res.activityInfo.className + 7115 // " = " + res.priority); 7116 res.match = match; 7117 res.isDefault = info.hasDefault; 7118 res.labelRes = info.labelRes; 7119 res.nonLocalizedLabel = info.nonLocalizedLabel; 7120 res.icon = info.icon; 7121 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7122 return res; 7123 } 7124 7125 @Override 7126 protected void sortResults(List<ResolveInfo> results) { 7127 Collections.sort(results, mResolvePrioritySorter); 7128 } 7129 7130 @Override 7131 protected void dumpFilter(PrintWriter out, String prefix, 7132 PackageParser.ServiceIntentInfo filter) { 7133 out.print(prefix); out.print( 7134 Integer.toHexString(System.identityHashCode(filter.service))); 7135 out.print(' '); 7136 filter.service.printComponentShortName(out); 7137 out.print(" filter "); 7138 out.println(Integer.toHexString(System.identityHashCode(filter))); 7139 } 7140 7141// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7142// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7143// final List<ResolveInfo> retList = Lists.newArrayList(); 7144// while (i.hasNext()) { 7145// final ResolveInfo resolveInfo = (ResolveInfo) i; 7146// if (isEnabledLP(resolveInfo.serviceInfo)) { 7147// retList.add(resolveInfo); 7148// } 7149// } 7150// return retList; 7151// } 7152 7153 // Keys are String (activity class name), values are Activity. 7154 private final HashMap<ComponentName, PackageParser.Service> mServices 7155 = new HashMap<ComponentName, PackageParser.Service>(); 7156 private int mFlags; 7157 }; 7158 7159 private final class ProviderIntentResolver 7160 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7161 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7162 boolean defaultOnly, int userId) { 7163 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7164 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7165 } 7166 7167 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7168 int userId) { 7169 if (!sUserManager.exists(userId)) 7170 return null; 7171 mFlags = flags; 7172 return super.queryIntent(intent, resolvedType, 7173 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7174 } 7175 7176 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7177 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7178 if (!sUserManager.exists(userId)) 7179 return null; 7180 if (packageProviders == null) { 7181 return null; 7182 } 7183 mFlags = flags; 7184 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7185 final int N = packageProviders.size(); 7186 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7187 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7188 7189 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7190 for (int i = 0; i < N; ++i) { 7191 intentFilters = packageProviders.get(i).intents; 7192 if (intentFilters != null && intentFilters.size() > 0) { 7193 PackageParser.ProviderIntentInfo[] array = 7194 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7195 intentFilters.toArray(array); 7196 listCut.add(array); 7197 } 7198 } 7199 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7200 } 7201 7202 public final void addProvider(PackageParser.Provider p) { 7203 if (mProviders.containsKey(p.getComponentName())) { 7204 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7205 return; 7206 } 7207 7208 mProviders.put(p.getComponentName(), p); 7209 if (DEBUG_SHOW_INFO) { 7210 Log.v(TAG, " " 7211 + (p.info.nonLocalizedLabel != null 7212 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7213 Log.v(TAG, " Class=" + p.info.name); 7214 } 7215 final int NI = p.intents.size(); 7216 int j; 7217 for (j = 0; j < NI; j++) { 7218 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7219 if (DEBUG_SHOW_INFO) { 7220 Log.v(TAG, " IntentFilter:"); 7221 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7222 } 7223 if (!intent.debugCheck()) { 7224 Log.w(TAG, "==> For Provider " + p.info.name); 7225 } 7226 addFilter(intent); 7227 } 7228 } 7229 7230 public final void removeProvider(PackageParser.Provider p) { 7231 mProviders.remove(p.getComponentName()); 7232 if (DEBUG_SHOW_INFO) { 7233 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7234 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7235 Log.v(TAG, " Class=" + p.info.name); 7236 } 7237 final int NI = p.intents.size(); 7238 int j; 7239 for (j = 0; j < NI; j++) { 7240 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7241 if (DEBUG_SHOW_INFO) { 7242 Log.v(TAG, " IntentFilter:"); 7243 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7244 } 7245 removeFilter(intent); 7246 } 7247 } 7248 7249 @Override 7250 protected boolean allowFilterResult( 7251 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7252 ProviderInfo filterPi = filter.provider.info; 7253 for (int i = dest.size() - 1; i >= 0; i--) { 7254 ProviderInfo destPi = dest.get(i).providerInfo; 7255 if (destPi.name == filterPi.name 7256 && destPi.packageName == filterPi.packageName) { 7257 return false; 7258 } 7259 } 7260 return true; 7261 } 7262 7263 @Override 7264 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7265 return new PackageParser.ProviderIntentInfo[size]; 7266 } 7267 7268 @Override 7269 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7270 if (!sUserManager.exists(userId)) 7271 return true; 7272 PackageParser.Package p = filter.provider.owner; 7273 if (p != null) { 7274 PackageSetting ps = (PackageSetting) p.mExtras; 7275 if (ps != null) { 7276 // System apps are never considered stopped for purposes of 7277 // filtering, because there may be no way for the user to 7278 // actually re-launch them. 7279 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7280 && ps.getStopped(userId); 7281 } 7282 } 7283 return false; 7284 } 7285 7286 @Override 7287 protected boolean isPackageForFilter(String packageName, 7288 PackageParser.ProviderIntentInfo info) { 7289 return packageName.equals(info.provider.owner.packageName); 7290 } 7291 7292 @Override 7293 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7294 int match, int userId) { 7295 if (!sUserManager.exists(userId)) 7296 return null; 7297 final PackageParser.ProviderIntentInfo info = filter; 7298 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7299 return null; 7300 } 7301 final PackageParser.Provider provider = info.provider; 7302 if (mSafeMode && (provider.info.applicationInfo.flags 7303 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7304 return null; 7305 } 7306 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7307 if (ps == null) { 7308 return null; 7309 } 7310 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7311 ps.readUserState(userId), userId); 7312 if (pi == null) { 7313 return null; 7314 } 7315 final ResolveInfo res = new ResolveInfo(); 7316 res.providerInfo = pi; 7317 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7318 res.filter = filter; 7319 } 7320 res.priority = info.getPriority(); 7321 res.preferredOrder = provider.owner.mPreferredOrder; 7322 res.match = match; 7323 res.isDefault = info.hasDefault; 7324 res.labelRes = info.labelRes; 7325 res.nonLocalizedLabel = info.nonLocalizedLabel; 7326 res.icon = info.icon; 7327 res.system = isSystemApp(res.providerInfo.applicationInfo); 7328 return res; 7329 } 7330 7331 @Override 7332 protected void sortResults(List<ResolveInfo> results) { 7333 Collections.sort(results, mResolvePrioritySorter); 7334 } 7335 7336 @Override 7337 protected void dumpFilter(PrintWriter out, String prefix, 7338 PackageParser.ProviderIntentInfo filter) { 7339 out.print(prefix); 7340 out.print( 7341 Integer.toHexString(System.identityHashCode(filter.provider))); 7342 out.print(' '); 7343 filter.provider.printComponentShortName(out); 7344 out.print(" filter "); 7345 out.println(Integer.toHexString(System.identityHashCode(filter))); 7346 } 7347 7348 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7349 = new HashMap<ComponentName, PackageParser.Provider>(); 7350 private int mFlags; 7351 }; 7352 7353 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7354 new Comparator<ResolveInfo>() { 7355 public int compare(ResolveInfo r1, ResolveInfo r2) { 7356 int v1 = r1.priority; 7357 int v2 = r2.priority; 7358 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7359 if (v1 != v2) { 7360 return (v1 > v2) ? -1 : 1; 7361 } 7362 v1 = r1.preferredOrder; 7363 v2 = r2.preferredOrder; 7364 if (v1 != v2) { 7365 return (v1 > v2) ? -1 : 1; 7366 } 7367 if (r1.isDefault != r2.isDefault) { 7368 return r1.isDefault ? -1 : 1; 7369 } 7370 v1 = r1.match; 7371 v2 = r2.match; 7372 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7373 if (v1 != v2) { 7374 return (v1 > v2) ? -1 : 1; 7375 } 7376 if (r1.system != r2.system) { 7377 return r1.system ? -1 : 1; 7378 } 7379 return 0; 7380 } 7381 }; 7382 7383 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7384 new Comparator<ProviderInfo>() { 7385 public int compare(ProviderInfo p1, ProviderInfo p2) { 7386 final int v1 = p1.initOrder; 7387 final int v2 = p2.initOrder; 7388 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7389 } 7390 }; 7391 7392 static final void sendPackageBroadcast(String action, String pkg, 7393 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7394 int[] userIds) { 7395 IActivityManager am = ActivityManagerNative.getDefault(); 7396 if (am != null) { 7397 try { 7398 if (userIds == null) { 7399 userIds = am.getRunningUserIds(); 7400 } 7401 for (int id : userIds) { 7402 final Intent intent = new Intent(action, 7403 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7404 if (extras != null) { 7405 intent.putExtras(extras); 7406 } 7407 if (targetPkg != null) { 7408 intent.setPackage(targetPkg); 7409 } 7410 // Modify the UID when posting to other users 7411 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7412 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7413 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7414 intent.putExtra(Intent.EXTRA_UID, uid); 7415 } 7416 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7417 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7418 if (DEBUG_BROADCASTS) { 7419 RuntimeException here = new RuntimeException("here"); 7420 here.fillInStackTrace(); 7421 Slog.d(TAG, "Sending to user " + id + ": " 7422 + intent.toShortString(false, true, false, false) 7423 + " " + intent.getExtras(), here); 7424 } 7425 am.broadcastIntent(null, intent, null, finishedReceiver, 7426 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7427 finishedReceiver != null, false, id); 7428 } 7429 } catch (RemoteException ex) { 7430 } 7431 } 7432 } 7433 7434 /** 7435 * Check if the external storage media is available. This is true if there 7436 * is a mounted external storage medium or if the external storage is 7437 * emulated. 7438 */ 7439 private boolean isExternalMediaAvailable() { 7440 return mMediaMounted || Environment.isExternalStorageEmulated(); 7441 } 7442 7443 @Override 7444 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7445 // writer 7446 synchronized (mPackages) { 7447 if (!isExternalMediaAvailable()) { 7448 // If the external storage is no longer mounted at this point, 7449 // the caller may not have been able to delete all of this 7450 // packages files and can not delete any more. Bail. 7451 return null; 7452 } 7453 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7454 if (lastPackage != null) { 7455 pkgs.remove(lastPackage); 7456 } 7457 if (pkgs.size() > 0) { 7458 return pkgs.get(0); 7459 } 7460 } 7461 return null; 7462 } 7463 7464 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7465 if (false) { 7466 RuntimeException here = new RuntimeException("here"); 7467 here.fillInStackTrace(); 7468 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7469 + " andCode=" + andCode, here); 7470 } 7471 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7472 userId, andCode ? 1 : 0, packageName)); 7473 } 7474 7475 void startCleaningPackages() { 7476 // reader 7477 synchronized (mPackages) { 7478 if (!isExternalMediaAvailable()) { 7479 return; 7480 } 7481 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7482 return; 7483 } 7484 } 7485 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7486 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7487 IActivityManager am = ActivityManagerNative.getDefault(); 7488 if (am != null) { 7489 try { 7490 am.startService(null, intent, null, UserHandle.USER_OWNER); 7491 } catch (RemoteException e) { 7492 } 7493 } 7494 } 7495 7496 private final class AppDirObserver extends FileObserver { 7497 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 7498 super(path, mask); 7499 mRootDir = path; 7500 mIsRom = isrom; 7501 mIsPrivileged = isPrivileged; 7502 } 7503 7504 public void onEvent(int event, String path) { 7505 String removedPackage = null; 7506 int removedAppId = -1; 7507 int[] removedUsers = null; 7508 String addedPackage = null; 7509 int addedAppId = -1; 7510 int[] addedUsers = null; 7511 7512 // TODO post a message to the handler to obtain serial ordering 7513 synchronized (mInstallLock) { 7514 String fullPathStr = null; 7515 File fullPath = null; 7516 if (path != null) { 7517 fullPath = new File(mRootDir, path); 7518 fullPathStr = fullPath.getPath(); 7519 } 7520 7521 if (DEBUG_APP_DIR_OBSERVER) 7522 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 7523 7524 if (!isApkFile(fullPath)) { 7525 if (DEBUG_APP_DIR_OBSERVER) 7526 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 7527 return; 7528 } 7529 7530 // Ignore packages that are being installed or 7531 // have just been installed. 7532 if (ignoreCodePath(fullPathStr)) { 7533 return; 7534 } 7535 PackageParser.Package p = null; 7536 PackageSetting ps = null; 7537 // reader 7538 synchronized (mPackages) { 7539 p = mAppDirs.get(fullPathStr); 7540 if (p != null) { 7541 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 7542 if (ps != null) { 7543 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7544 } else { 7545 removedUsers = sUserManager.getUserIds(); 7546 } 7547 } 7548 addedUsers = sUserManager.getUserIds(); 7549 } 7550 if ((event&REMOVE_EVENTS) != 0) { 7551 if (ps != null) { 7552 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 7553 removePackageLI(ps, true); 7554 removedPackage = ps.name; 7555 removedAppId = ps.appId; 7556 } 7557 } 7558 7559 if ((event&ADD_EVENTS) != 0) { 7560 if (p == null) { 7561 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 7562 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 7563 if (mIsRom) { 7564 flags |= PackageParser.PARSE_IS_SYSTEM 7565 | PackageParser.PARSE_IS_SYSTEM_DIR; 7566 if (mIsPrivileged) { 7567 flags |= PackageParser.PARSE_IS_PRIVILEGED; 7568 } 7569 } 7570 p = scanPackageLI(fullPath, flags, 7571 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 7572 System.currentTimeMillis(), UserHandle.ALL, null); 7573 if (p != null) { 7574 /* 7575 * TODO this seems dangerous as the package may have 7576 * changed since we last acquired the mPackages 7577 * lock. 7578 */ 7579 // writer 7580 synchronized (mPackages) { 7581 updatePermissionsLPw(p.packageName, p, 7582 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 7583 } 7584 addedPackage = p.applicationInfo.packageName; 7585 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 7586 } 7587 } 7588 } 7589 7590 // reader 7591 synchronized (mPackages) { 7592 mSettings.writeLPr(); 7593 } 7594 } 7595 7596 if (removedPackage != null) { 7597 Bundle extras = new Bundle(1); 7598 extras.putInt(Intent.EXTRA_UID, removedAppId); 7599 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 7600 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7601 extras, null, null, removedUsers); 7602 } 7603 if (addedPackage != null) { 7604 Bundle extras = new Bundle(1); 7605 extras.putInt(Intent.EXTRA_UID, addedAppId); 7606 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 7607 extras, null, null, addedUsers); 7608 } 7609 } 7610 7611 private final String mRootDir; 7612 private final boolean mIsRom; 7613 private final boolean mIsPrivileged; 7614 } 7615 7616 @Override 7617 public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags, 7618 String installerPackageName, VerificationParams verificationParams, 7619 String packageAbiOverride) { 7620 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7621 null); 7622 7623 final File originFile = new File(originPath); 7624 final int uid = Binder.getCallingUid(); 7625 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7626 try { 7627 if (observer != null) { 7628 observer.packageInstalled("", null, INSTALL_FAILED_USER_RESTRICTED); 7629 } 7630 } catch (RemoteException re) { 7631 } 7632 return; 7633 } 7634 7635 UserHandle user; 7636 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7637 user = UserHandle.ALL; 7638 } else { 7639 user = new UserHandle(UserHandle.getUserId(uid)); 7640 } 7641 7642 final int filteredFlags; 7643 if (uid == Process.SHELL_UID || uid == 0) { 7644 if (DEBUG_INSTALL) { 7645 Slog.v(TAG, "Install from ADB"); 7646 } 7647 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7648 } else { 7649 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7650 } 7651 7652 verificationParams.setInstallerUid(uid); 7653 7654 final Message msg = mHandler.obtainMessage(INIT_COPY); 7655 msg.obj = new InstallParams(originFile, observer, filteredFlags, installerPackageName, 7656 verificationParams, user, packageAbiOverride); 7657 mHandler.sendMessage(msg); 7658 } 7659 7660 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7661 Bundle extras = new Bundle(1); 7662 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7663 7664 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7665 packageName, extras, null, null, new int[] {userId}); 7666 try { 7667 IActivityManager am = ActivityManagerNative.getDefault(); 7668 final boolean isSystem = 7669 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7670 if (isSystem && am.isUserRunning(userId, false)) { 7671 // The just-installed/enabled app is bundled on the system, so presumed 7672 // to be able to run automatically without needing an explicit launch. 7673 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7674 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7675 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7676 .setPackage(packageName); 7677 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7678 android.app.AppOpsManager.OP_NONE, false, false, userId); 7679 } 7680 } catch (RemoteException e) { 7681 // shouldn't happen 7682 Slog.w(TAG, "Unable to bootstrap installed package", e); 7683 } 7684 } 7685 7686 @Override 7687 public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked, 7688 int userId) { 7689 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7690 PackageSetting pkgSetting; 7691 final int uid = Binder.getCallingUid(); 7692 if (UserHandle.getUserId(uid) != userId) { 7693 mContext.enforceCallingOrSelfPermission( 7694 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7695 "setApplicationBlockedSetting for user " + userId); 7696 } 7697 7698 if (blocked && isPackageDeviceAdmin(packageName, userId)) { 7699 Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin"); 7700 return false; 7701 } 7702 7703 long callingId = Binder.clearCallingIdentity(); 7704 try { 7705 boolean sendAdded = false; 7706 boolean sendRemoved = false; 7707 // writer 7708 synchronized (mPackages) { 7709 pkgSetting = mSettings.mPackages.get(packageName); 7710 if (pkgSetting == null) { 7711 return false; 7712 } 7713 if (pkgSetting.getBlocked(userId) != blocked) { 7714 pkgSetting.setBlocked(blocked, userId); 7715 mSettings.writePackageRestrictionsLPr(userId); 7716 if (blocked) { 7717 sendRemoved = true; 7718 } else { 7719 sendAdded = true; 7720 } 7721 } 7722 } 7723 if (sendAdded) { 7724 sendPackageAddedForUser(packageName, pkgSetting, userId); 7725 return true; 7726 } 7727 if (sendRemoved) { 7728 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7729 "blocking pkg"); 7730 sendPackageBlockedForUser(packageName, pkgSetting, userId); 7731 } 7732 } finally { 7733 Binder.restoreCallingIdentity(callingId); 7734 } 7735 return false; 7736 } 7737 7738 private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting, 7739 int userId) { 7740 final PackageRemovedInfo info = new PackageRemovedInfo(); 7741 info.removedPackage = packageName; 7742 info.removedUsers = new int[] {userId}; 7743 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7744 info.sendBroadcast(false, false, false); 7745 } 7746 7747 /** 7748 * Returns true if application is not found or there was an error. Otherwise it returns 7749 * the blocked state of the package for the given user. 7750 */ 7751 @Override 7752 public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) { 7753 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7754 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7755 "getApplicationBlocked for user " + userId); 7756 PackageSetting pkgSetting; 7757 long callingId = Binder.clearCallingIdentity(); 7758 try { 7759 // writer 7760 synchronized (mPackages) { 7761 pkgSetting = mSettings.mPackages.get(packageName); 7762 if (pkgSetting == null) { 7763 return true; 7764 } 7765 return pkgSetting.getBlocked(userId); 7766 } 7767 } finally { 7768 Binder.restoreCallingIdentity(callingId); 7769 } 7770 } 7771 7772 void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer2, 7773 PackageInstallerParams params, String installerPackageName, int installerUid, 7774 UserHandle user) { 7775 Slog.e(TAG, "TODO: install stage!"); 7776 try { 7777 observer2.packageInstalled(packageName, null, 7778 PackageManager.INSTALL_FAILED_INTERNAL_ERROR); 7779 } catch (RemoteException ignored) { 7780 } 7781 } 7782 7783 /** 7784 * @hide 7785 */ 7786 @Override 7787 public int installExistingPackageAsUser(String packageName, int userId) { 7788 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7789 null); 7790 PackageSetting pkgSetting; 7791 final int uid = Binder.getCallingUid(); 7792 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7793 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7794 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7795 } 7796 7797 long callingId = Binder.clearCallingIdentity(); 7798 try { 7799 boolean sendAdded = false; 7800 Bundle extras = new Bundle(1); 7801 7802 // writer 7803 synchronized (mPackages) { 7804 pkgSetting = mSettings.mPackages.get(packageName); 7805 if (pkgSetting == null) { 7806 return PackageManager.INSTALL_FAILED_INVALID_URI; 7807 } 7808 if (!pkgSetting.getInstalled(userId)) { 7809 pkgSetting.setInstalled(true, userId); 7810 pkgSetting.setBlocked(false, userId); 7811 mSettings.writePackageRestrictionsLPr(userId); 7812 sendAdded = true; 7813 } 7814 } 7815 7816 if (sendAdded) { 7817 sendPackageAddedForUser(packageName, pkgSetting, userId); 7818 } 7819 } finally { 7820 Binder.restoreCallingIdentity(callingId); 7821 } 7822 7823 return PackageManager.INSTALL_SUCCEEDED; 7824 } 7825 7826 boolean isUserRestricted(int userId, String restrictionKey) { 7827 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7828 if (restrictions.getBoolean(restrictionKey, false)) { 7829 Log.w(TAG, "User is restricted: " + restrictionKey); 7830 return true; 7831 } 7832 return false; 7833 } 7834 7835 @Override 7836 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7837 mContext.enforceCallingOrSelfPermission( 7838 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7839 "Only package verification agents can verify applications"); 7840 7841 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7842 final PackageVerificationResponse response = new PackageVerificationResponse( 7843 verificationCode, Binder.getCallingUid()); 7844 msg.arg1 = id; 7845 msg.obj = response; 7846 mHandler.sendMessage(msg); 7847 } 7848 7849 @Override 7850 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7851 long millisecondsToDelay) { 7852 mContext.enforceCallingOrSelfPermission( 7853 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7854 "Only package verification agents can extend verification timeouts"); 7855 7856 final PackageVerificationState state = mPendingVerification.get(id); 7857 final PackageVerificationResponse response = new PackageVerificationResponse( 7858 verificationCodeAtTimeout, Binder.getCallingUid()); 7859 7860 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7861 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7862 } 7863 if (millisecondsToDelay < 0) { 7864 millisecondsToDelay = 0; 7865 } 7866 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7867 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7868 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7869 } 7870 7871 if ((state != null) && !state.timeoutExtended()) { 7872 state.extendTimeout(); 7873 7874 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7875 msg.arg1 = id; 7876 msg.obj = response; 7877 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7878 } 7879 } 7880 7881 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7882 int verificationCode, UserHandle user) { 7883 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7884 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7885 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7886 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7887 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 7888 7889 mContext.sendBroadcastAsUser(intent, user, 7890 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 7891 } 7892 7893 private ComponentName matchComponentForVerifier(String packageName, 7894 List<ResolveInfo> receivers) { 7895 ActivityInfo targetReceiver = null; 7896 7897 final int NR = receivers.size(); 7898 for (int i = 0; i < NR; i++) { 7899 final ResolveInfo info = receivers.get(i); 7900 if (info.activityInfo == null) { 7901 continue; 7902 } 7903 7904 if (packageName.equals(info.activityInfo.packageName)) { 7905 targetReceiver = info.activityInfo; 7906 break; 7907 } 7908 } 7909 7910 if (targetReceiver == null) { 7911 return null; 7912 } 7913 7914 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 7915 } 7916 7917 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 7918 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 7919 if (pkgInfo.verifiers.length == 0) { 7920 return null; 7921 } 7922 7923 final int N = pkgInfo.verifiers.length; 7924 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 7925 for (int i = 0; i < N; i++) { 7926 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 7927 7928 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 7929 receivers); 7930 if (comp == null) { 7931 continue; 7932 } 7933 7934 final int verifierUid = getUidForVerifier(verifierInfo); 7935 if (verifierUid == -1) { 7936 continue; 7937 } 7938 7939 if (DEBUG_VERIFY) { 7940 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 7941 + " with the correct signature"); 7942 } 7943 sufficientVerifiers.add(comp); 7944 verificationState.addSufficientVerifier(verifierUid); 7945 } 7946 7947 return sufficientVerifiers; 7948 } 7949 7950 private int getUidForVerifier(VerifierInfo verifierInfo) { 7951 synchronized (mPackages) { 7952 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 7953 if (pkg == null) { 7954 return -1; 7955 } else if (pkg.mSignatures.length != 1) { 7956 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 7957 + " has more than one signature; ignoring"); 7958 return -1; 7959 } 7960 7961 /* 7962 * If the public key of the package's signature does not match 7963 * our expected public key, then this is a different package and 7964 * we should skip. 7965 */ 7966 7967 final byte[] expectedPublicKey; 7968 try { 7969 final Signature verifierSig = pkg.mSignatures[0]; 7970 final PublicKey publicKey = verifierSig.getPublicKey(); 7971 expectedPublicKey = publicKey.getEncoded(); 7972 } catch (CertificateException e) { 7973 return -1; 7974 } 7975 7976 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 7977 7978 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 7979 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 7980 + " does not have the expected public key; ignoring"); 7981 return -1; 7982 } 7983 7984 return pkg.applicationInfo.uid; 7985 } 7986 } 7987 7988 @Override 7989 public void finishPackageInstall(int token) { 7990 enforceSystemOrRoot("Only the system is allowed to finish installs"); 7991 7992 if (DEBUG_INSTALL) { 7993 Slog.v(TAG, "BM finishing package install for " + token); 7994 } 7995 7996 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 7997 mHandler.sendMessage(msg); 7998 } 7999 8000 /** 8001 * Get the verification agent timeout. 8002 * 8003 * @return verification timeout in milliseconds 8004 */ 8005 private long getVerificationTimeout() { 8006 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8007 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8008 DEFAULT_VERIFICATION_TIMEOUT); 8009 } 8010 8011 /** 8012 * Get the default verification agent response code. 8013 * 8014 * @return default verification response code 8015 */ 8016 private int getDefaultVerificationResponse() { 8017 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8018 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8019 DEFAULT_VERIFICATION_RESPONSE); 8020 } 8021 8022 /** 8023 * Check whether or not package verification has been enabled. 8024 * 8025 * @return true if verification should be performed 8026 */ 8027 private boolean isVerificationEnabled(int userId, int flags) { 8028 if (!DEFAULT_VERIFY_ENABLE) { 8029 return false; 8030 } 8031 8032 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8033 8034 // Check if installing from ADB 8035 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8036 // Do not run verification in a test harness environment 8037 if (ActivityManager.isRunningInTestHarness()) { 8038 return false; 8039 } 8040 if (ensureVerifyAppsEnabled) { 8041 return true; 8042 } 8043 // Check if the developer does not want package verification for ADB installs 8044 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8045 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8046 return false; 8047 } 8048 } 8049 8050 if (ensureVerifyAppsEnabled) { 8051 return true; 8052 } 8053 8054 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8055 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8056 } 8057 8058 /** 8059 * Get the "allow unknown sources" setting. 8060 * 8061 * @return the current "allow unknown sources" setting 8062 */ 8063 private int getUnknownSourcesSettings() { 8064 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8065 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8066 -1); 8067 } 8068 8069 @Override 8070 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8071 final int uid = Binder.getCallingUid(); 8072 // writer 8073 synchronized (mPackages) { 8074 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8075 if (targetPackageSetting == null) { 8076 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8077 } 8078 8079 PackageSetting installerPackageSetting; 8080 if (installerPackageName != null) { 8081 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8082 if (installerPackageSetting == null) { 8083 throw new IllegalArgumentException("Unknown installer package: " 8084 + installerPackageName); 8085 } 8086 } else { 8087 installerPackageSetting = null; 8088 } 8089 8090 Signature[] callerSignature; 8091 Object obj = mSettings.getUserIdLPr(uid); 8092 if (obj != null) { 8093 if (obj instanceof SharedUserSetting) { 8094 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8095 } else if (obj instanceof PackageSetting) { 8096 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8097 } else { 8098 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8099 } 8100 } else { 8101 throw new SecurityException("Unknown calling uid " + uid); 8102 } 8103 8104 // Verify: can't set installerPackageName to a package that is 8105 // not signed with the same cert as the caller. 8106 if (installerPackageSetting != null) { 8107 if (compareSignatures(callerSignature, 8108 installerPackageSetting.signatures.mSignatures) 8109 != PackageManager.SIGNATURE_MATCH) { 8110 throw new SecurityException( 8111 "Caller does not have same cert as new installer package " 8112 + installerPackageName); 8113 } 8114 } 8115 8116 // Verify: if target already has an installer package, it must 8117 // be signed with the same cert as the caller. 8118 if (targetPackageSetting.installerPackageName != null) { 8119 PackageSetting setting = mSettings.mPackages.get( 8120 targetPackageSetting.installerPackageName); 8121 // If the currently set package isn't valid, then it's always 8122 // okay to change it. 8123 if (setting != null) { 8124 if (compareSignatures(callerSignature, 8125 setting.signatures.mSignatures) 8126 != PackageManager.SIGNATURE_MATCH) { 8127 throw new SecurityException( 8128 "Caller does not have same cert as old installer package " 8129 + targetPackageSetting.installerPackageName); 8130 } 8131 } 8132 } 8133 8134 // Okay! 8135 targetPackageSetting.installerPackageName = installerPackageName; 8136 scheduleWriteSettingsLocked(); 8137 } 8138 } 8139 8140 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8141 // Queue up an async operation since the package installation may take a little while. 8142 mHandler.post(new Runnable() { 8143 public void run() { 8144 mHandler.removeCallbacks(this); 8145 // Result object to be returned 8146 PackageInstalledInfo res = new PackageInstalledInfo(); 8147 res.returnCode = currentStatus; 8148 res.uid = -1; 8149 res.pkg = null; 8150 res.removedInfo = new PackageRemovedInfo(); 8151 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8152 args.doPreInstall(res.returnCode); 8153 synchronized (mInstallLock) { 8154 installPackageLI(args, true, res); 8155 } 8156 args.doPostInstall(res.returnCode, res.uid); 8157 } 8158 8159 // A restore should be performed at this point if (a) the install 8160 // succeeded, (b) the operation is not an update, and (c) the new 8161 // package has a backupAgent defined. 8162 final boolean update = res.removedInfo.removedPackage != null; 8163 boolean doRestore = (!update 8164 && res.pkg != null 8165 && res.pkg.applicationInfo.backupAgentName != null); 8166 8167 // Set up the post-install work request bookkeeping. This will be used 8168 // and cleaned up by the post-install event handling regardless of whether 8169 // there's a restore pass performed. Token values are >= 1. 8170 int token; 8171 if (mNextInstallToken < 0) mNextInstallToken = 1; 8172 token = mNextInstallToken++; 8173 8174 PostInstallData data = new PostInstallData(args, res); 8175 mRunningInstalls.put(token, data); 8176 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8177 8178 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8179 // Pass responsibility to the Backup Manager. It will perform a 8180 // restore if appropriate, then pass responsibility back to the 8181 // Package Manager to run the post-install observer callbacks 8182 // and broadcasts. 8183 IBackupManager bm = IBackupManager.Stub.asInterface( 8184 ServiceManager.getService(Context.BACKUP_SERVICE)); 8185 if (bm != null) { 8186 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8187 + " to BM for possible restore"); 8188 try { 8189 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8190 } catch (RemoteException e) { 8191 // can't happen; the backup manager is local 8192 } catch (Exception e) { 8193 Slog.e(TAG, "Exception trying to enqueue restore", e); 8194 doRestore = false; 8195 } 8196 } else { 8197 Slog.e(TAG, "Backup Manager not found!"); 8198 doRestore = false; 8199 } 8200 } 8201 8202 if (!doRestore) { 8203 // No restore possible, or the Backup Manager was mysteriously not 8204 // available -- just fire the post-install work request directly. 8205 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8206 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8207 mHandler.sendMessage(msg); 8208 } 8209 } 8210 }); 8211 } 8212 8213 private abstract class HandlerParams { 8214 private static final int MAX_RETRIES = 4; 8215 8216 /** 8217 * Number of times startCopy() has been attempted and had a non-fatal 8218 * error. 8219 */ 8220 private int mRetries = 0; 8221 8222 /** User handle for the user requesting the information or installation. */ 8223 private final UserHandle mUser; 8224 8225 HandlerParams(UserHandle user) { 8226 mUser = user; 8227 } 8228 8229 UserHandle getUser() { 8230 return mUser; 8231 } 8232 8233 final boolean startCopy() { 8234 boolean res; 8235 try { 8236 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8237 8238 if (++mRetries > MAX_RETRIES) { 8239 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8240 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8241 handleServiceError(); 8242 return false; 8243 } else { 8244 handleStartCopy(); 8245 res = true; 8246 } 8247 } catch (RemoteException e) { 8248 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8249 mHandler.sendEmptyMessage(MCS_RECONNECT); 8250 res = false; 8251 } 8252 handleReturnCode(); 8253 return res; 8254 } 8255 8256 final void serviceError() { 8257 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8258 handleServiceError(); 8259 handleReturnCode(); 8260 } 8261 8262 abstract void handleStartCopy() throws RemoteException; 8263 abstract void handleServiceError(); 8264 abstract void handleReturnCode(); 8265 } 8266 8267 class MeasureParams extends HandlerParams { 8268 private final PackageStats mStats; 8269 private boolean mSuccess; 8270 8271 private final IPackageStatsObserver mObserver; 8272 8273 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8274 super(new UserHandle(stats.userHandle)); 8275 mObserver = observer; 8276 mStats = stats; 8277 } 8278 8279 @Override 8280 public String toString() { 8281 return "MeasureParams{" 8282 + Integer.toHexString(System.identityHashCode(this)) 8283 + " " + mStats.packageName + "}"; 8284 } 8285 8286 @Override 8287 void handleStartCopy() throws RemoteException { 8288 synchronized (mInstallLock) { 8289 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8290 } 8291 8292 if (mSuccess) { 8293 final boolean mounted; 8294 if (Environment.isExternalStorageEmulated()) { 8295 mounted = true; 8296 } else { 8297 final String status = Environment.getExternalStorageState(); 8298 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8299 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8300 } 8301 8302 if (mounted) { 8303 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8304 8305 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8306 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8307 8308 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8309 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8310 8311 // Always subtract cache size, since it's a subdirectory 8312 mStats.externalDataSize -= mStats.externalCacheSize; 8313 8314 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8315 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8316 8317 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8318 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8319 } 8320 } 8321 } 8322 8323 @Override 8324 void handleReturnCode() { 8325 if (mObserver != null) { 8326 try { 8327 mObserver.onGetStatsCompleted(mStats, mSuccess); 8328 } catch (RemoteException e) { 8329 Slog.i(TAG, "Observer no longer exists."); 8330 } 8331 } 8332 } 8333 8334 @Override 8335 void handleServiceError() { 8336 Slog.e(TAG, "Could not measure application " + mStats.packageName 8337 + " external storage"); 8338 } 8339 } 8340 8341 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8342 throws RemoteException { 8343 long result = 0; 8344 for (File path : paths) { 8345 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8346 } 8347 return result; 8348 } 8349 8350 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8351 for (File path : paths) { 8352 try { 8353 mcs.clearDirectory(path.getAbsolutePath()); 8354 } catch (RemoteException e) { 8355 } 8356 } 8357 } 8358 8359 class InstallParams extends HandlerParams { 8360 /** 8361 * Location where install is coming from, before it has been 8362 * copied/renamed into place. This could be a single monolithic APK 8363 * file, or a cluster directory. This location may be untrusted. 8364 */ 8365 final File originFile; 8366 8367 /** 8368 * Flag indicating that {@link #originFile} lives in a trusted location, 8369 * meaning downstream users don't need to defensively copy the contents. 8370 */ 8371 boolean originTrusted; 8372 8373 final IPackageInstallObserver2 observer; 8374 int flags; 8375 final String installerPackageName; 8376 final VerificationParams verificationParams; 8377 private InstallArgs mArgs; 8378 private int mRet; 8379 final String packageAbiOverride; 8380 final String packageInstructionSetOverride; 8381 8382 InstallParams(File originFile, IPackageInstallObserver2 observer, int flags, 8383 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8384 String packageAbiOverride) { 8385 super(user); 8386 this.originFile = Preconditions.checkNotNull(originFile); 8387 this.originTrusted = false; 8388 this.observer = observer; 8389 this.flags = flags; 8390 this.installerPackageName = installerPackageName; 8391 this.verificationParams = verificationParams; 8392 this.packageAbiOverride = packageAbiOverride; 8393 this.packageInstructionSetOverride = (packageAbiOverride == null) ? 8394 packageAbiOverride : VMRuntime.getInstructionSet(packageAbiOverride); 8395 } 8396 8397 @Override 8398 public String toString() { 8399 return "InstallParams{" 8400 + Integer.toHexString(System.identityHashCode(this)) 8401 + " " + originFile + "}"; 8402 } 8403 8404 public ManifestDigest getManifestDigest() { 8405 if (verificationParams == null) { 8406 return null; 8407 } 8408 return verificationParams.getManifestDigest(); 8409 } 8410 8411 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8412 String packageName = pkgLite.packageName; 8413 int installLocation = pkgLite.installLocation; 8414 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8415 // reader 8416 synchronized (mPackages) { 8417 PackageParser.Package pkg = mPackages.get(packageName); 8418 if (pkg != null) { 8419 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8420 // Check for downgrading. 8421 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8422 if (pkgLite.versionCode < pkg.mVersionCode) { 8423 Slog.w(TAG, "Can't install update of " + packageName 8424 + " update version " + pkgLite.versionCode 8425 + " is older than installed version " 8426 + pkg.mVersionCode); 8427 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8428 } 8429 } 8430 // Check for updated system application. 8431 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8432 if (onSd) { 8433 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8434 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8435 } 8436 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8437 } else { 8438 if (onSd) { 8439 // Install flag overrides everything. 8440 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8441 } 8442 // If current upgrade specifies particular preference 8443 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8444 // Application explicitly specified internal. 8445 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8446 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8447 // App explictly prefers external. Let policy decide 8448 } else { 8449 // Prefer previous location 8450 if (isExternal(pkg)) { 8451 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8452 } 8453 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8454 } 8455 } 8456 } else { 8457 // Invalid install. Return error code 8458 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8459 } 8460 } 8461 } 8462 // All the special cases have been taken care of. 8463 // Return result based on recommended install location. 8464 if (onSd) { 8465 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8466 } 8467 return pkgLite.recommendedInstallLocation; 8468 } 8469 8470 private long getMemoryLowThreshold() { 8471 final DeviceStorageMonitorInternal 8472 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8473 if (dsm == null) { 8474 return 0L; 8475 } 8476 return dsm.getMemoryLowThreshold(); 8477 } 8478 8479 /* 8480 * Invoke remote method to get package information and install 8481 * location values. Override install location based on default 8482 * policy if needed and then create install arguments based 8483 * on the install location. 8484 */ 8485 public void handleStartCopy() throws RemoteException { 8486 int ret = PackageManager.INSTALL_SUCCEEDED; 8487 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8488 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8489 PackageInfoLite pkgLite = null; 8490 8491 if (onInt && onSd) { 8492 // Check if both bits are set. 8493 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8494 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8495 } else { 8496 final long lowThreshold = getMemoryLowThreshold(); 8497 if (lowThreshold == 0L) { 8498 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8499 } 8500 8501 // Remote call to find out default install location 8502 final String originPath = originFile.getAbsolutePath(); 8503 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold, 8504 packageAbiOverride); 8505 8506 /* 8507 * If we have too little free space, try to free cache 8508 * before giving up. 8509 */ 8510 if (pkgLite.recommendedInstallLocation 8511 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8512 final long size = mContainerService.calculateInstalledSize( 8513 originPath, isForwardLocked(), packageAbiOverride); 8514 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8515 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, 8516 lowThreshold, packageAbiOverride); 8517 } 8518 /* 8519 * The cache free must have deleted the file we 8520 * downloaded to install. 8521 * 8522 * TODO: fix the "freeCache" call to not delete 8523 * the file we care about. 8524 */ 8525 if (pkgLite.recommendedInstallLocation 8526 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8527 pkgLite.recommendedInstallLocation 8528 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8529 } 8530 } 8531 } 8532 8533 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8534 int loc = pkgLite.recommendedInstallLocation; 8535 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8536 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8537 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8538 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8539 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8540 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8541 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8542 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8543 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8544 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8545 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8546 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8547 } else { 8548 // Override with defaults if needed. 8549 loc = installLocationPolicy(pkgLite, flags); 8550 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8551 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8552 } else if (!onSd && !onInt) { 8553 // Override install location with flags 8554 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8555 // Set the flag to install on external media. 8556 flags |= PackageManager.INSTALL_EXTERNAL; 8557 flags &= ~PackageManager.INSTALL_INTERNAL; 8558 } else { 8559 // Make sure the flag for installing on external 8560 // media is unset 8561 flags |= PackageManager.INSTALL_INTERNAL; 8562 flags &= ~PackageManager.INSTALL_EXTERNAL; 8563 } 8564 } 8565 } 8566 } 8567 8568 final InstallArgs args = createInstallArgs(this); 8569 mArgs = args; 8570 8571 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8572 /* 8573 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8574 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8575 */ 8576 int userIdentifier = getUser().getIdentifier(); 8577 if (userIdentifier == UserHandle.USER_ALL 8578 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8579 userIdentifier = UserHandle.USER_OWNER; 8580 } 8581 8582 /* 8583 * Determine if we have any installed package verifiers. If we 8584 * do, then we'll defer to them to verify the packages. 8585 */ 8586 final int requiredUid = mRequiredVerifierPackage == null ? -1 8587 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8588 if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) { 8589 // TODO: send verifier the install session instead of uri 8590 final Intent verification = new Intent( 8591 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8592 verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE); 8593 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8594 8595 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8596 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8597 0 /* TODO: Which userId? */); 8598 8599 if (DEBUG_VERIFY) { 8600 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8601 + verification.toString() + " with " + pkgLite.verifiers.length 8602 + " optional verifiers"); 8603 } 8604 8605 final int verificationId = mPendingVerificationToken++; 8606 8607 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8608 8609 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8610 installerPackageName); 8611 8612 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8613 8614 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8615 pkgLite.packageName); 8616 8617 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8618 pkgLite.versionCode); 8619 8620 if (verificationParams != null) { 8621 if (verificationParams.getVerificationURI() != null) { 8622 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8623 verificationParams.getVerificationURI()); 8624 } 8625 if (verificationParams.getOriginatingURI() != null) { 8626 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8627 verificationParams.getOriginatingURI()); 8628 } 8629 if (verificationParams.getReferrer() != null) { 8630 verification.putExtra(Intent.EXTRA_REFERRER, 8631 verificationParams.getReferrer()); 8632 } 8633 if (verificationParams.getOriginatingUid() >= 0) { 8634 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8635 verificationParams.getOriginatingUid()); 8636 } 8637 if (verificationParams.getInstallerUid() >= 0) { 8638 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8639 verificationParams.getInstallerUid()); 8640 } 8641 } 8642 8643 final PackageVerificationState verificationState = new PackageVerificationState( 8644 requiredUid, args); 8645 8646 mPendingVerification.append(verificationId, verificationState); 8647 8648 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8649 receivers, verificationState); 8650 8651 /* 8652 * If any sufficient verifiers were listed in the package 8653 * manifest, attempt to ask them. 8654 */ 8655 if (sufficientVerifiers != null) { 8656 final int N = sufficientVerifiers.size(); 8657 if (N == 0) { 8658 Slog.i(TAG, "Additional verifiers required, but none installed."); 8659 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8660 } else { 8661 for (int i = 0; i < N; i++) { 8662 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8663 8664 final Intent sufficientIntent = new Intent(verification); 8665 sufficientIntent.setComponent(verifierComponent); 8666 8667 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8668 } 8669 } 8670 } 8671 8672 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8673 mRequiredVerifierPackage, receivers); 8674 if (ret == PackageManager.INSTALL_SUCCEEDED 8675 && mRequiredVerifierPackage != null) { 8676 /* 8677 * Send the intent to the required verification agent, 8678 * but only start the verification timeout after the 8679 * target BroadcastReceivers have run. 8680 */ 8681 verification.setComponent(requiredVerifierComponent); 8682 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8683 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8684 new BroadcastReceiver() { 8685 @Override 8686 public void onReceive(Context context, Intent intent) { 8687 final Message msg = mHandler 8688 .obtainMessage(CHECK_PENDING_VERIFICATION); 8689 msg.arg1 = verificationId; 8690 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8691 } 8692 }, null, 0, null, null); 8693 8694 /* 8695 * We don't want the copy to proceed until verification 8696 * succeeds, so null out this field. 8697 */ 8698 mArgs = null; 8699 } 8700 } else { 8701 /* 8702 * No package verification is enabled, so immediately start 8703 * the remote call to initiate copy using temporary file. 8704 */ 8705 ret = args.copyApk(mContainerService, true); 8706 } 8707 } 8708 8709 mRet = ret; 8710 } 8711 8712 @Override 8713 void handleReturnCode() { 8714 // If mArgs is null, then MCS couldn't be reached. When it 8715 // reconnects, it will try again to install. At that point, this 8716 // will succeed. 8717 if (mArgs != null) { 8718 processPendingInstall(mArgs, mRet); 8719 } 8720 } 8721 8722 @Override 8723 void handleServiceError() { 8724 mArgs = createInstallArgs(this); 8725 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8726 } 8727 8728 public boolean isForwardLocked() { 8729 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8730 } 8731 } 8732 8733 /* 8734 * Utility class used in movePackage api. 8735 * srcArgs and targetArgs are not set for invalid flags and make 8736 * sure to do null checks when invoking methods on them. 8737 * We probably want to return ErrorPrams for both failed installs 8738 * and moves. 8739 */ 8740 class MoveParams extends HandlerParams { 8741 final IPackageMoveObserver observer; 8742 final int flags; 8743 final String packageName; 8744 final InstallArgs srcArgs; 8745 final InstallArgs targetArgs; 8746 int uid; 8747 int mRet; 8748 8749 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8750 String packageName, String instructionSet, int uid, UserHandle user) { 8751 super(user); 8752 this.srcArgs = srcArgs; 8753 this.observer = observer; 8754 this.flags = flags; 8755 this.packageName = packageName; 8756 this.uid = uid; 8757 if (srcArgs != null) { 8758 final String codePath = srcArgs.getCodePath(); 8759 targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, 8760 instructionSet); 8761 } else { 8762 targetArgs = null; 8763 } 8764 } 8765 8766 @Override 8767 public String toString() { 8768 return "MoveParams{" 8769 + Integer.toHexString(System.identityHashCode(this)) 8770 + " " + packageName + "}"; 8771 } 8772 8773 public void handleStartCopy() throws RemoteException { 8774 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8775 // Check for storage space on target medium 8776 if (!targetArgs.checkFreeStorage(mContainerService)) { 8777 Log.w(TAG, "Insufficient storage to install"); 8778 return; 8779 } 8780 8781 mRet = srcArgs.doPreCopy(); 8782 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8783 return; 8784 } 8785 8786 mRet = targetArgs.copyApk(mContainerService, false); 8787 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8788 srcArgs.doPostCopy(uid); 8789 return; 8790 } 8791 8792 mRet = srcArgs.doPostCopy(uid); 8793 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8794 return; 8795 } 8796 8797 mRet = targetArgs.doPreInstall(mRet); 8798 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8799 return; 8800 } 8801 8802 if (DEBUG_SD_INSTALL) { 8803 StringBuilder builder = new StringBuilder(); 8804 if (srcArgs != null) { 8805 builder.append("src: "); 8806 builder.append(srcArgs.getCodePath()); 8807 } 8808 if (targetArgs != null) { 8809 builder.append(" target : "); 8810 builder.append(targetArgs.getCodePath()); 8811 } 8812 Log.i(TAG, builder.toString()); 8813 } 8814 } 8815 8816 @Override 8817 void handleReturnCode() { 8818 targetArgs.doPostInstall(mRet, uid); 8819 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8820 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8821 currentStatus = PackageManager.MOVE_SUCCEEDED; 8822 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8823 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8824 } 8825 processPendingMove(this, currentStatus); 8826 } 8827 8828 @Override 8829 void handleServiceError() { 8830 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8831 } 8832 } 8833 8834 /** 8835 * Used during creation of InstallArgs 8836 * 8837 * @param flags package installation flags 8838 * @return true if should be installed on external storage 8839 */ 8840 private static boolean installOnSd(int flags) { 8841 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8842 return false; 8843 } 8844 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8845 return true; 8846 } 8847 return false; 8848 } 8849 8850 /** 8851 * Used during creation of InstallArgs 8852 * 8853 * @param flags package installation flags 8854 * @return true if should be installed as forward locked 8855 */ 8856 private static boolean installForwardLocked(int flags) { 8857 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8858 } 8859 8860 private InstallArgs createInstallArgs(InstallParams params) { 8861 // TODO: extend to support incoming zero-copy locations 8862 8863 if (installOnSd(params.flags) || params.isForwardLocked()) { 8864 return new AsecInstallArgs(params); 8865 } else { 8866 return new FileInstallArgs(params); 8867 } 8868 } 8869 8870 /** 8871 * Create args that describe an existing installed package. Typically used 8872 * when cleaning up old installs, or used as a move source. 8873 */ 8874 private InstallArgs createInstallArgsForExisting(int flags, String codePath, 8875 String resourcePath, String nativeLibraryPath, String instructionSet) { 8876 final boolean isInAsec; 8877 if (installOnSd(flags)) { 8878 /* Apps on SD card are always in ASEC containers. */ 8879 isInAsec = true; 8880 } else if (installForwardLocked(flags) 8881 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8882 /* 8883 * Forward-locked apps are only in ASEC containers if they're the 8884 * new style 8885 */ 8886 isInAsec = true; 8887 } else { 8888 isInAsec = false; 8889 } 8890 8891 if (isInAsec) { 8892 return new AsecInstallArgs(codePath, resourcePath, nativeLibraryPath, 8893 instructionSet, installOnSd(flags), installForwardLocked(flags)); 8894 } else { 8895 return new FileInstallArgs(codePath, resourcePath, nativeLibraryPath, instructionSet); 8896 } 8897 } 8898 8899 private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName, 8900 String instructionSet) { 8901 final File codeFile = new File(codePath); 8902 if (installOnSd(flags) || installForwardLocked(flags)) { 8903 String cid = getNextCodePath(codePath, pkgName, "/" 8904 + AsecInstallArgs.RES_FILE_NAME); 8905 return new AsecInstallArgs(codeFile, cid, instructionSet, installOnSd(flags), 8906 installForwardLocked(flags)); 8907 } else { 8908 return new FileInstallArgs(codeFile, instructionSet); 8909 } 8910 } 8911 8912 static abstract class InstallArgs { 8913 /** @see InstallParams#originFile */ 8914 final File originFile; 8915 /** @see InstallParams#originTrusted */ 8916 final boolean originTrusted; 8917 8918 // TODO: define inherit location 8919 8920 final IPackageInstallObserver2 observer; 8921 // Always refers to PackageManager flags only 8922 final int flags; 8923 final String installerPackageName; 8924 final ManifestDigest manifestDigest; 8925 final UserHandle user; 8926 final String instructionSet; 8927 final String abiOverride; 8928 8929 InstallArgs(File originFile, boolean originTrusted, IPackageInstallObserver2 observer, 8930 int flags, String installerPackageName, ManifestDigest manifestDigest, 8931 UserHandle user, String instructionSet, String abiOverride) { 8932 this.originFile = originFile; 8933 this.originTrusted = originTrusted; 8934 this.flags = flags; 8935 this.observer = observer; 8936 this.installerPackageName = installerPackageName; 8937 this.manifestDigest = manifestDigest; 8938 this.user = user; 8939 this.instructionSet = instructionSet; 8940 this.abiOverride = abiOverride; 8941 } 8942 8943 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 8944 abstract int doPreInstall(int status); 8945 8946 /** 8947 * Rename package into final resting place. All paths on the given 8948 * scanned package should be updated to reflect the rename. 8949 */ 8950 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 8951 abstract int doPostInstall(int status, int uid); 8952 8953 /** @see PackageSettingBase#codePathString */ 8954 abstract String getCodePath(); 8955 /** @see PackageSettingBase#resourcePathString */ 8956 abstract String getResourcePath(); 8957 /** @see PackageSettingBase#nativeLibraryPathString */ 8958 abstract String getNativeLibraryPath(); 8959 8960 // Need installer lock especially for dex file removal. 8961 abstract void cleanUpResourcesLI(); 8962 abstract boolean doPostDeleteLI(boolean delete); 8963 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 8964 8965 /** 8966 * Called before the source arguments are copied. This is used mostly 8967 * for MoveParams when it needs to read the source file to put it in the 8968 * destination. 8969 */ 8970 int doPreCopy() { 8971 return PackageManager.INSTALL_SUCCEEDED; 8972 } 8973 8974 /** 8975 * Called after the source arguments are copied. This is used mostly for 8976 * MoveParams when it needs to read the source file to put it in the 8977 * destination. 8978 * 8979 * @return 8980 */ 8981 int doPostCopy(int uid) { 8982 return PackageManager.INSTALL_SUCCEEDED; 8983 } 8984 8985 protected boolean isFwdLocked() { 8986 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8987 } 8988 8989 UserHandle getUser() { 8990 return user; 8991 } 8992 } 8993 8994 /** 8995 * Logic to handle installation of non-ASEC applications, including copying 8996 * and renaming logic. 8997 */ 8998 class FileInstallArgs extends InstallArgs { 8999 private File codeFile; 9000 private File resourceFile; 9001 private File nativeLibraryFile; 9002 9003 // Example topology: 9004 // /data/app/com.example/base.apk 9005 // /data/app/com.example/split_foo.apk 9006 // /data/app/com.example/lib/arm/libfoo.so 9007 // /data/app/com.example/lib/arm64/libfoo.so 9008 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9009 9010 /** New install */ 9011 FileInstallArgs(InstallParams params) { 9012 super(params.originFile, params.originTrusted, params.observer, params.flags, 9013 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9014 params.packageInstructionSetOverride, params.packageAbiOverride); 9015 if (isFwdLocked()) { 9016 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9017 } 9018 } 9019 9020 /** Existing install */ 9021 FileInstallArgs(String codePath, String resourcePath, String nativeLibraryPath, 9022 String instructionSet) { 9023 super(null, false, null, 0, null, null, null, instructionSet, null); 9024 this.codeFile = (codePath != null) ? new File(codePath) : null; 9025 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9026 this.nativeLibraryFile = (nativeLibraryPath != null) ? new File(nativeLibraryPath) : null; 9027 } 9028 9029 /** New install from existing */ 9030 FileInstallArgs(File originFile, String instructionSet) { 9031 super(originFile, true, null, 0, null, null, null, instructionSet, null); 9032 } 9033 9034 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9035 final long lowThreshold; 9036 9037 final DeviceStorageMonitorInternal 9038 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9039 if (dsm == null) { 9040 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9041 lowThreshold = 0L; 9042 } else { 9043 if (dsm.isMemoryLow()) { 9044 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9045 return false; 9046 } 9047 9048 lowThreshold = dsm.getMemoryLowThreshold(); 9049 } 9050 9051 return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9052 lowThreshold); 9053 } 9054 9055 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9056 try { 9057 final File tempDir = createTempPackageDir(mAppInstallDir); 9058 codeFile = tempDir; 9059 resourceFile = tempDir; 9060 } catch (IOException e) { 9061 Slog.w(TAG, "Failed to create copy file: " + e); 9062 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9063 } 9064 9065 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9066 @Override 9067 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9068 if (!FileUtils.isValidExtFilename(name)) { 9069 throw new IllegalArgumentException("Invalid filename: " + name); 9070 } 9071 try { 9072 final File file = new File(codeFile, name); 9073 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9074 O_RDWR | O_CREAT, 0644); 9075 Os.chmod(file.getAbsolutePath(), 0644); 9076 return new ParcelFileDescriptor(fd); 9077 } catch (ErrnoException e) { 9078 throw new RemoteException("Failed to open: " + e.getMessage()); 9079 } 9080 } 9081 }; 9082 9083 int ret = imcs.copyPackage(originFile.getAbsolutePath(), target); 9084 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9085 Slog.e(TAG, "Failed to copy package"); 9086 return ret; 9087 } 9088 9089 String[] abiList = (abiOverride != null) ? 9090 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 9091 NativeLibraryHelper.Handle handle = null; 9092 try { 9093 handle = NativeLibraryHelper.Handle.create(codeFile); 9094 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && 9095 abiOverride == null && 9096 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9097 abiList = Build.SUPPORTED_32_BIT_ABIS; 9098 } 9099 9100 // TODO: refactor to avoid double findSupportedAbi() 9101 final int abiIndex = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9102 if (abiIndex < 0 && abiIndex != PackageManager.NO_NATIVE_LIBRARIES) { 9103 return abiIndex; 9104 } else if (abiIndex >= 0) { 9105 final File baseLibFile = new File(codeFile, LIB_DIR_NAME); 9106 baseLibFile.mkdir(); 9107 Os.chmod(baseLibFile.getAbsolutePath(), 0755); 9108 9109 final String abi = Build.SUPPORTED_ABIS[abiIndex]; 9110 final String instructionSet = VMRuntime.getInstructionSet(abi); 9111 nativeLibraryFile = new File(baseLibFile, instructionSet); 9112 nativeLibraryFile.mkdir(); 9113 Os.chmod(nativeLibraryFile.getAbsolutePath(), 0755); 9114 9115 copyNativeLibrariesForInternalApp(handle, nativeLibraryFile, abiList); 9116 } 9117 } catch (IOException | ErrnoException e) { 9118 Slog.e(TAG, "Copying native libraries failed", e); 9119 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9120 } finally { 9121 IoUtils.closeQuietly(handle); 9122 } 9123 9124 return ret; 9125 } 9126 9127 int doPreInstall(int status) { 9128 if (status != PackageManager.INSTALL_SUCCEEDED) { 9129 cleanUp(); 9130 } 9131 return status; 9132 } 9133 9134 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9135 if (status != PackageManager.INSTALL_SUCCEEDED) { 9136 cleanUp(); 9137 return false; 9138 } else { 9139 final File beforeCodeFile = codeFile; 9140 final File afterCodeFile = new File(mAppInstallDir, 9141 getNextCodePath(oldCodePath, pkg.packageName, null)); 9142 9143 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9144 if (!beforeCodeFile.renameTo(afterCodeFile)) { 9145 return false; 9146 } 9147 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9148 return false; 9149 } 9150 9151 // Reflect the rename internally 9152 codeFile = afterCodeFile; 9153 resourceFile = afterCodeFile; 9154 nativeLibraryFile = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9155 nativeLibraryFile); 9156 9157 // Reflect the rename in scanned details 9158 pkg.codePath = afterCodeFile.getAbsolutePath(); 9159 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9160 pkg.baseCodePath); 9161 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9162 pkg.splitCodePaths); 9163 9164 // Reflect the rename in app info 9165 pkg.applicationInfo.setCodePath(pkg.codePath); 9166 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9167 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9168 pkg.applicationInfo.setResourcePath(pkg.codePath); 9169 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9170 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9171 pkg.applicationInfo.nativeLibraryDir = getNativeLibraryPath(); 9172 9173 return true; 9174 } 9175 } 9176 9177 int doPostInstall(int status, int uid) { 9178 if (status != PackageManager.INSTALL_SUCCEEDED) { 9179 cleanUp(); 9180 } 9181 return status; 9182 } 9183 9184 @Override 9185 String getCodePath() { 9186 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9187 } 9188 9189 @Override 9190 String getResourcePath() { 9191 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9192 } 9193 9194 @Override 9195 String getNativeLibraryPath() { 9196 return (nativeLibraryFile != null) ? nativeLibraryFile.getAbsolutePath() : null; 9197 } 9198 9199 private boolean cleanUp() { 9200 if (codeFile == null || !codeFile.exists()) { 9201 return false; 9202 } 9203 9204 if (codeFile.isDirectory()) { 9205 FileUtils.deleteContents(codeFile); 9206 } 9207 codeFile.delete(); 9208 9209 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9210 resourceFile.delete(); 9211 } 9212 9213 if (nativeLibraryFile != null && !FileUtils.contains(codeFile, nativeLibraryFile)) { 9214 FileUtils.deleteContents(nativeLibraryFile); 9215 nativeLibraryFile.delete(); 9216 } 9217 9218 return true; 9219 } 9220 9221 void cleanUpResourcesLI() { 9222 // Try enumerating all code paths before deleting 9223 List<String> allCodePaths = Collections.EMPTY_LIST; 9224 if (codeFile != null && codeFile.exists()) { 9225 try { 9226 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9227 allCodePaths = pkg.getAllCodePaths(); 9228 } catch (PackageParserException e) { 9229 // Ignored; we tried our best 9230 } 9231 } 9232 9233 cleanUp(); 9234 9235 if (!allCodePaths.isEmpty()) { 9236 if (instructionSet == null) { 9237 throw new IllegalStateException("instructionSet == null"); 9238 } 9239 9240 for (String codePath : allCodePaths) { 9241 int retCode = mInstaller.rmdex(codePath, instructionSet); 9242 if (retCode < 0) { 9243 Slog.w(TAG, "Couldn't remove dex file for package: " 9244 + " at location " + codePath + ", retcode=" + retCode); 9245 // we don't consider this to be a failure of the core package deletion 9246 } 9247 } 9248 } 9249 } 9250 9251 boolean doPostDeleteLI(boolean delete) { 9252 // XXX err, shouldn't we respect the delete flag? 9253 cleanUpResourcesLI(); 9254 return true; 9255 } 9256 } 9257 9258 private boolean isAsecExternal(String cid) { 9259 final String asecPath = PackageHelper.getSdFilesystem(cid); 9260 return !asecPath.startsWith(mAsecInternalPath); 9261 } 9262 9263 /** 9264 * Extract the MountService "container ID" from the full code path of an 9265 * .apk. 9266 */ 9267 static String cidFromCodePath(String fullCodePath) { 9268 int eidx = fullCodePath.lastIndexOf("/"); 9269 String subStr1 = fullCodePath.substring(0, eidx); 9270 int sidx = subStr1.lastIndexOf("/"); 9271 return subStr1.substring(sidx+1, eidx); 9272 } 9273 9274 /** 9275 * Logic to handle installation of ASEC applications, including copying and 9276 * renaming logic. 9277 */ 9278 class AsecInstallArgs extends InstallArgs { 9279 // TODO: teach about handling cluster directories 9280 9281 static final String RES_FILE_NAME = "pkg.apk"; 9282 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9283 9284 String cid; 9285 String packagePath; 9286 String resourcePath; 9287 String libraryPath; 9288 9289 /** New install */ 9290 AsecInstallArgs(InstallParams params) { 9291 super(params.originFile, params.originTrusted, params.observer, params.flags, 9292 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9293 params.packageInstructionSetOverride, params.packageAbiOverride); 9294 } 9295 9296 /** Existing install */ 9297 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 9298 String instructionSet, boolean isExternal, boolean isForwardLocked) { 9299 super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9300 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9301 instructionSet, null); 9302 // Extract cid from fullCodePath 9303 int eidx = fullCodePath.lastIndexOf("/"); 9304 String subStr1 = fullCodePath.substring(0, eidx); 9305 int sidx = subStr1.lastIndexOf("/"); 9306 cid = subStr1.substring(sidx+1, eidx); 9307 setCachePath(subStr1); 9308 } 9309 9310 AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) { 9311 super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9312 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9313 instructionSet, null); 9314 this.cid = cid; 9315 setCachePath(PackageHelper.getSdDir(cid)); 9316 } 9317 9318 /** New install from existing */ 9319 AsecInstallArgs(File originPackageFile, String cid, String instructionSet, 9320 boolean isExternal, boolean isForwardLocked) { 9321 super(originPackageFile, true, null, (isExternal ? INSTALL_EXTERNAL : 0) 9322 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9323 instructionSet, null); 9324 this.cid = cid; 9325 } 9326 9327 void createCopyFile() { 9328 cid = getTempContainerId(); 9329 } 9330 9331 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9332 return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9333 abiOverride); 9334 } 9335 9336 private final boolean isExternal() { 9337 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9338 } 9339 9340 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9341 if (temp) { 9342 createCopyFile(); 9343 } else { 9344 /* 9345 * Pre-emptively destroy the container since it's destroyed if 9346 * copying fails due to it existing anyway. 9347 */ 9348 PackageHelper.destroySdDir(cid); 9349 } 9350 9351 final String newCachePath = imcs.copyPackageToContainer( 9352 originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9353 isFwdLocked(), abiOverride); 9354 9355 if (newCachePath != null) { 9356 setCachePath(newCachePath); 9357 return PackageManager.INSTALL_SUCCEEDED; 9358 } else { 9359 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9360 } 9361 } 9362 9363 @Override 9364 String getCodePath() { 9365 return packagePath; 9366 } 9367 9368 @Override 9369 String getResourcePath() { 9370 return resourcePath; 9371 } 9372 9373 @Override 9374 String getNativeLibraryPath() { 9375 return libraryPath; 9376 } 9377 9378 int doPreInstall(int status) { 9379 if (status != PackageManager.INSTALL_SUCCEEDED) { 9380 // Destroy container 9381 PackageHelper.destroySdDir(cid); 9382 } else { 9383 boolean mounted = PackageHelper.isContainerMounted(cid); 9384 if (!mounted) { 9385 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9386 Process.SYSTEM_UID); 9387 if (newCachePath != null) { 9388 setCachePath(newCachePath); 9389 } else { 9390 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9391 } 9392 } 9393 } 9394 return status; 9395 } 9396 9397 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9398 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9399 String newCachePath = null; 9400 if (PackageHelper.isContainerMounted(cid)) { 9401 // Unmount the container 9402 if (!PackageHelper.unMountSdDir(cid)) { 9403 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9404 return false; 9405 } 9406 } 9407 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9408 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9409 " which might be stale. Will try to clean up."); 9410 // Clean up the stale container and proceed to recreate. 9411 if (!PackageHelper.destroySdDir(newCacheId)) { 9412 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9413 return false; 9414 } 9415 // Successfully cleaned up stale container. Try to rename again. 9416 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9417 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9418 + " inspite of cleaning it up."); 9419 return false; 9420 } 9421 } 9422 if (!PackageHelper.isContainerMounted(newCacheId)) { 9423 Slog.w(TAG, "Mounting container " + newCacheId); 9424 newCachePath = PackageHelper.mountSdDir(newCacheId, 9425 getEncryptKey(), Process.SYSTEM_UID); 9426 } else { 9427 newCachePath = PackageHelper.getSdDir(newCacheId); 9428 } 9429 if (newCachePath == null) { 9430 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9431 return false; 9432 } 9433 Log.i(TAG, "Succesfully renamed " + cid + 9434 " to " + newCacheId + 9435 " at new path: " + newCachePath); 9436 cid = newCacheId; 9437 setCachePath(newCachePath); 9438 9439 // TODO: extend to support split APKs 9440 pkg.codePath = getCodePath(); 9441 pkg.baseCodePath = getCodePath(); 9442 pkg.splitCodePaths = null; 9443 9444 pkg.applicationInfo.setCodePath(getCodePath()); 9445 pkg.applicationInfo.setBaseCodePath(getCodePath()); 9446 pkg.applicationInfo.setSplitCodePaths(null); 9447 pkg.applicationInfo.setResourcePath(getResourcePath()); 9448 pkg.applicationInfo.setBaseResourcePath(getResourcePath()); 9449 pkg.applicationInfo.setSplitResourcePaths(null); 9450 pkg.applicationInfo.nativeLibraryDir = getNativeLibraryPath(); 9451 9452 return true; 9453 } 9454 9455 private void setCachePath(String newCachePath) { 9456 File cachePath = new File(newCachePath); 9457 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath(); 9458 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9459 9460 if (isFwdLocked()) { 9461 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9462 } else { 9463 resourcePath = packagePath; 9464 } 9465 } 9466 9467 int doPostInstall(int status, int uid) { 9468 if (status != PackageManager.INSTALL_SUCCEEDED) { 9469 cleanUp(); 9470 } else { 9471 final int groupOwner; 9472 final String protectedFile; 9473 if (isFwdLocked()) { 9474 groupOwner = UserHandle.getSharedAppGid(uid); 9475 protectedFile = RES_FILE_NAME; 9476 } else { 9477 groupOwner = -1; 9478 protectedFile = null; 9479 } 9480 9481 if (uid < Process.FIRST_APPLICATION_UID 9482 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9483 Slog.e(TAG, "Failed to finalize " + cid); 9484 PackageHelper.destroySdDir(cid); 9485 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9486 } 9487 9488 boolean mounted = PackageHelper.isContainerMounted(cid); 9489 if (!mounted) { 9490 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9491 } 9492 } 9493 return status; 9494 } 9495 9496 private void cleanUp() { 9497 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9498 9499 // Destroy secure container 9500 PackageHelper.destroySdDir(cid); 9501 } 9502 9503 void cleanUpResourcesLI() { 9504 String sourceFile = getCodePath(); 9505 // Remove dex file 9506 if (instructionSet == null) { 9507 throw new IllegalStateException("instructionSet == null"); 9508 } 9509 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9510 if (retCode < 0) { 9511 Slog.w(TAG, "Couldn't remove dex file for package: " 9512 + " at location " 9513 + sourceFile.toString() + ", retcode=" + retCode); 9514 // we don't consider this to be a failure of the core package deletion 9515 } 9516 cleanUp(); 9517 } 9518 9519 boolean matchContainer(String app) { 9520 if (cid.startsWith(app)) { 9521 return true; 9522 } 9523 return false; 9524 } 9525 9526 String getPackageName() { 9527 return getAsecPackageName(cid); 9528 } 9529 9530 boolean doPostDeleteLI(boolean delete) { 9531 boolean ret = false; 9532 boolean mounted = PackageHelper.isContainerMounted(cid); 9533 if (mounted) { 9534 // Unmount first 9535 ret = PackageHelper.unMountSdDir(cid); 9536 } 9537 if (ret && delete) { 9538 cleanUpResourcesLI(); 9539 } 9540 return ret; 9541 } 9542 9543 @Override 9544 int doPreCopy() { 9545 if (isFwdLocked()) { 9546 if (!PackageHelper.fixSdPermissions(cid, 9547 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9548 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9549 } 9550 } 9551 9552 return PackageManager.INSTALL_SUCCEEDED; 9553 } 9554 9555 @Override 9556 int doPostCopy(int uid) { 9557 if (isFwdLocked()) { 9558 if (uid < Process.FIRST_APPLICATION_UID 9559 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9560 RES_FILE_NAME)) { 9561 Slog.e(TAG, "Failed to finalize " + cid); 9562 PackageHelper.destroySdDir(cid); 9563 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9564 } 9565 } 9566 9567 return PackageManager.INSTALL_SUCCEEDED; 9568 } 9569 } 9570 9571 static String getAsecPackageName(String packageCid) { 9572 int idx = packageCid.lastIndexOf("-"); 9573 if (idx == -1) { 9574 return packageCid; 9575 } 9576 return packageCid.substring(0, idx); 9577 } 9578 9579 // Utility method used to create code paths based on package name and available index. 9580 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9581 String idxStr = ""; 9582 int idx = 1; 9583 // Fall back to default value of idx=1 if prefix is not 9584 // part of oldCodePath 9585 if (oldCodePath != null) { 9586 String subStr = oldCodePath; 9587 // Drop the suffix right away 9588 if (suffix != null && subStr.endsWith(suffix)) { 9589 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9590 } 9591 // If oldCodePath already contains prefix find out the 9592 // ending index to either increment or decrement. 9593 int sidx = subStr.lastIndexOf(prefix); 9594 if (sidx != -1) { 9595 subStr = subStr.substring(sidx + prefix.length()); 9596 if (subStr != null) { 9597 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9598 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9599 } 9600 try { 9601 idx = Integer.parseInt(subStr); 9602 if (idx <= 1) { 9603 idx++; 9604 } else { 9605 idx--; 9606 } 9607 } catch(NumberFormatException e) { 9608 } 9609 } 9610 } 9611 } 9612 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9613 return prefix + idxStr; 9614 } 9615 9616 // Utility method used to ignore ADD/REMOVE events 9617 // by directory observer. 9618 private static boolean ignoreCodePath(String fullPathStr) { 9619 String apkName = deriveCodePathName(fullPathStr); 9620 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9621 if (idx != -1 && ((idx+1) < apkName.length())) { 9622 // Make sure the package ends with a numeral 9623 String version = apkName.substring(idx+1); 9624 try { 9625 Integer.parseInt(version); 9626 return true; 9627 } catch (NumberFormatException e) {} 9628 } 9629 return false; 9630 } 9631 9632 // Utility method that returns the relative package path with respect 9633 // to the installation directory. Like say for /data/data/com.test-1.apk 9634 // string com.test-1 is returned. 9635 static String deriveCodePathName(String codePath) { 9636 if (codePath == null) { 9637 return null; 9638 } 9639 final File codeFile = new File(codePath); 9640 final String name = codeFile.getName(); 9641 if (codeFile.isDirectory()) { 9642 return name; 9643 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9644 final int lastDot = name.lastIndexOf('.'); 9645 return name.substring(0, lastDot); 9646 } else { 9647 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9648 return null; 9649 } 9650 } 9651 9652 class PackageInstalledInfo { 9653 String name; 9654 int uid; 9655 // The set of users that originally had this package installed. 9656 int[] origUsers; 9657 // The set of users that now have this package installed. 9658 int[] newUsers; 9659 PackageParser.Package pkg; 9660 int returnCode; 9661 PackageRemovedInfo removedInfo; 9662 9663 // In some error cases we want to convey more info back to the observer 9664 String origPackage; 9665 String origPermission; 9666 } 9667 9668 /* 9669 * Install a non-existing package. 9670 */ 9671 private void installNewPackageLI(PackageParser.Package pkg, 9672 int parseFlags, int scanMode, UserHandle user, 9673 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9674 // Remember this for later, in case we need to rollback this install 9675 String pkgName = pkg.packageName; 9676 9677 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9678 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9679 synchronized(mPackages) { 9680 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9681 // A package with the same name is already installed, though 9682 // it has been renamed to an older name. The package we 9683 // are trying to install should be installed as an update to 9684 // the existing one, but that has not been requested, so bail. 9685 Slog.w(TAG, "Attempt to re-install " + pkgName 9686 + " without first uninstalling package running as " 9687 + mSettings.mRenamedPackages.get(pkgName)); 9688 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9689 return; 9690 } 9691 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9692 // Don't allow installation over an existing package with the same name. 9693 Slog.w(TAG, "Attempt to re-install " + pkgName 9694 + " without first uninstalling."); 9695 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9696 return; 9697 } 9698 } 9699 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9700 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9701 System.currentTimeMillis(), user, abiOverride); 9702 if (newPackage == null) { 9703 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 9704 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9705 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9706 } 9707 } else { 9708 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9709 // delete the partially installed application. the data directory will have to be 9710 // restored if it was already existing 9711 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9712 // remove package from internal structures. Note that we want deletePackageX to 9713 // delete the package data and cache directories that it created in 9714 // scanPackageLocked, unless those directories existed before we even tried to 9715 // install. 9716 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9717 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9718 res.removedInfo, true); 9719 } 9720 } 9721 } 9722 9723 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9724 // Upgrade keysets are being used. Determine if new package has a superset of the 9725 // required keys. 9726 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9727 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9728 Set<Long> newSigningKeyIds = new ArraySet<Long>(); 9729 for (PublicKey pk : newPkg.mSigningKeys) { 9730 newSigningKeyIds.add(ksms.getIdForPublicKey(pk)); 9731 } 9732 //remove PUBLIC_KEY_NOT_FOUND, although not necessary 9733 newSigningKeyIds.remove(ksms.PUBLIC_KEY_NOT_FOUND); 9734 for (int i = 0; i < upgradeKeySets.length; i++) { 9735 if (newSigningKeyIds.containsAll(ksms.mKeySetMapping.get(upgradeKeySets[i]))) { 9736 return true; 9737 } 9738 } 9739 return false; 9740 } 9741 9742 private void replacePackageLI(PackageParser.Package pkg, 9743 int parseFlags, int scanMode, UserHandle user, 9744 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9745 PackageParser.Package oldPackage; 9746 String pkgName = pkg.packageName; 9747 int[] allUsers; 9748 boolean[] perUserInstalled; 9749 9750 // First find the old package info and check signatures 9751 synchronized(mPackages) { 9752 oldPackage = mPackages.get(pkgName); 9753 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9754 PackageSetting ps = mSettings.mPackages.get(pkgName); 9755 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9756 // default to original signature matching 9757 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9758 != PackageManager.SIGNATURE_MATCH) { 9759 Slog.w(TAG, "New package has a different signature: " + pkgName); 9760 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9761 return; 9762 } 9763 } else { 9764 if(!checkUpgradeKeySetLP(ps, pkg)) { 9765 Slog.w(TAG, "New package not signed by keys specified by upgrade-keysets: " 9766 + pkgName); 9767 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9768 return; 9769 } 9770 } 9771 9772 // In case of rollback, remember per-user/profile install state 9773 allUsers = sUserManager.getUserIds(); 9774 perUserInstalled = new boolean[allUsers.length]; 9775 for (int i = 0; i < allUsers.length; i++) { 9776 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9777 } 9778 } 9779 boolean sysPkg = (isSystemApp(oldPackage)); 9780 if (sysPkg) { 9781 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9782 user, allUsers, perUserInstalled, installerPackageName, res, 9783 abiOverride); 9784 } else { 9785 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9786 user, allUsers, perUserInstalled, installerPackageName, res, 9787 abiOverride); 9788 } 9789 } 9790 9791 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9792 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9793 int[] allUsers, boolean[] perUserInstalled, 9794 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9795 PackageParser.Package newPackage = null; 9796 String pkgName = deletedPackage.packageName; 9797 boolean deletedPkg = true; 9798 boolean updatedSettings = false; 9799 9800 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9801 + deletedPackage); 9802 long origUpdateTime; 9803 if (pkg.mExtras != null) { 9804 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9805 } else { 9806 origUpdateTime = 0; 9807 } 9808 9809 // First delete the existing package while retaining the data directory 9810 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9811 res.removedInfo, true)) { 9812 // If the existing package wasn't successfully deleted 9813 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9814 deletedPkg = false; 9815 } else { 9816 // Successfully deleted the old package. Now proceed with re-installation 9817 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9818 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 9819 System.currentTimeMillis(), user, abiOverride); 9820 if (newPackage == null) { 9821 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 9822 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9823 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9824 } 9825 } else { 9826 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9827 updatedSettings = true; 9828 } 9829 } 9830 9831 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9832 // remove package from internal structures. Note that we want deletePackageX to 9833 // delete the package data and cache directories that it created in 9834 // scanPackageLocked, unless those directories existed before we even tried to 9835 // install. 9836 if(updatedSettings) { 9837 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9838 deletePackageLI( 9839 pkgName, null, true, allUsers, perUserInstalled, 9840 PackageManager.DELETE_KEEP_DATA, 9841 res.removedInfo, true); 9842 } 9843 // Since we failed to install the new package we need to restore the old 9844 // package that we deleted. 9845 if (deletedPkg) { 9846 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 9847 File restoreFile = new File(deletedPackage.codePath); 9848 // Parse old package 9849 boolean oldOnSd = isExternal(deletedPackage); 9850 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 9851 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 9852 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 9853 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 9854 | SCAN_UPDATE_TIME; 9855 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 9856 origUpdateTime, null, null) == null) { 9857 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 9858 return; 9859 } 9860 // Restore of old package succeeded. Update permissions. 9861 // writer 9862 synchronized (mPackages) { 9863 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 9864 UPDATE_PERMISSIONS_ALL); 9865 // can downgrade to reader 9866 mSettings.writeLPr(); 9867 } 9868 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 9869 } 9870 } 9871 } 9872 9873 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 9874 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9875 int[] allUsers, boolean[] perUserInstalled, 9876 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9877 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 9878 + ", old=" + deletedPackage); 9879 PackageParser.Package newPackage = null; 9880 boolean updatedSettings = false; 9881 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 9882 PackageParser.PARSE_IS_SYSTEM; 9883 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 9884 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9885 } 9886 String packageName = deletedPackage.packageName; 9887 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9888 if (packageName == null) { 9889 Slog.w(TAG, "Attempt to delete null packageName."); 9890 return; 9891 } 9892 PackageParser.Package oldPkg; 9893 PackageSetting oldPkgSetting; 9894 // reader 9895 synchronized (mPackages) { 9896 oldPkg = mPackages.get(packageName); 9897 oldPkgSetting = mSettings.mPackages.get(packageName); 9898 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 9899 (oldPkgSetting == null)) { 9900 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 9901 return; 9902 } 9903 } 9904 9905 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 9906 9907 res.removedInfo.uid = oldPkg.applicationInfo.uid; 9908 res.removedInfo.removedPackage = packageName; 9909 // Remove existing system package 9910 removePackageLI(oldPkgSetting, true); 9911 // writer 9912 synchronized (mPackages) { 9913 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 9914 // We didn't need to disable the .apk as a current system package, 9915 // which means we are replacing another update that is already 9916 // installed. We need to make sure to delete the older one's .apk. 9917 res.removedInfo.args = createInstallArgsForExisting(0, 9918 deletedPackage.applicationInfo.getCodePath(), 9919 deletedPackage.applicationInfo.getResourcePath(), 9920 deletedPackage.applicationInfo.nativeLibraryDir, 9921 getAppInstructionSet(deletedPackage.applicationInfo)); 9922 } else { 9923 res.removedInfo.args = null; 9924 } 9925 } 9926 9927 // Successfully disabled the old package. Now proceed with re-installation 9928 res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9929 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9930 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride); 9931 if (newPackage == null) { 9932 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 9933 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9934 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9935 } 9936 } else { 9937 if (newPackage.mExtras != null) { 9938 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 9939 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 9940 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 9941 9942 // is the update attempting to change shared user? that isn't going to work... 9943 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 9944 Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser 9945 + " to " + newPkgSetting.sharedUser); 9946 res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 9947 updatedSettings = true; 9948 } 9949 } 9950 9951 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9952 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9953 updatedSettings = true; 9954 } 9955 } 9956 9957 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9958 // Re installation failed. Restore old information 9959 // Remove new pkg information 9960 if (newPackage != null) { 9961 removeInstalledPackageLI(newPackage, true); 9962 } 9963 // Add back the old system package 9964 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null); 9965 // Restore the old system information in Settings 9966 synchronized(mPackages) { 9967 if (updatedSettings) { 9968 mSettings.enableSystemPackageLPw(packageName); 9969 mSettings.setInstallerPackageName(packageName, 9970 oldPkgSetting.installerPackageName); 9971 } 9972 mSettings.writeLPr(); 9973 } 9974 } 9975 } 9976 9977 // Utility method used to move dex files during install. 9978 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 9979 // TODO: extend to move split APK dex files 9980 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 9981 final String instructionSet = getAppInstructionSet(newPackage.applicationInfo); 9982 int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath, 9983 instructionSet); 9984 if (retCode != 0) { 9985 /* 9986 * Programs may be lazily run through dexopt, so the 9987 * source may not exist. However, something seems to 9988 * have gone wrong, so note that dexopt needs to be 9989 * run again and remove the source file. In addition, 9990 * remove the target to make sure there isn't a stale 9991 * file from a previous version of the package. 9992 */ 9993 newPackage.mDexOptNeeded = true; 9994 mInstaller.rmdex(oldCodePath, instructionSet); 9995 mInstaller.rmdex(newPackage.baseCodePath, instructionSet); 9996 } 9997 } 9998 return PackageManager.INSTALL_SUCCEEDED; 9999 } 10000 10001 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10002 int[] allUsers, boolean[] perUserInstalled, 10003 PackageInstalledInfo res) { 10004 String pkgName = newPackage.packageName; 10005 synchronized (mPackages) { 10006 //write settings. the installStatus will be incomplete at this stage. 10007 //note that the new package setting would have already been 10008 //added to mPackages. It hasn't been persisted yet. 10009 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10010 mSettings.writeLPr(); 10011 } 10012 10013 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10014 10015 synchronized (mPackages) { 10016 updatePermissionsLPw(newPackage.packageName, newPackage, 10017 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10018 ? UPDATE_PERMISSIONS_ALL : 0)); 10019 // For system-bundled packages, we assume that installing an upgraded version 10020 // of the package implies that the user actually wants to run that new code, 10021 // so we enable the package. 10022 if (isSystemApp(newPackage)) { 10023 // NB: implicit assumption that system package upgrades apply to all users 10024 if (DEBUG_INSTALL) { 10025 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10026 } 10027 PackageSetting ps = mSettings.mPackages.get(pkgName); 10028 if (ps != null) { 10029 if (res.origUsers != null) { 10030 for (int userHandle : res.origUsers) { 10031 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10032 userHandle, installerPackageName); 10033 } 10034 } 10035 // Also convey the prior install/uninstall state 10036 if (allUsers != null && perUserInstalled != null) { 10037 for (int i = 0; i < allUsers.length; i++) { 10038 if (DEBUG_INSTALL) { 10039 Slog.d(TAG, " user " + allUsers[i] 10040 + " => " + perUserInstalled[i]); 10041 } 10042 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10043 } 10044 // these install state changes will be persisted in the 10045 // upcoming call to mSettings.writeLPr(). 10046 } 10047 } 10048 } 10049 res.name = pkgName; 10050 res.uid = newPackage.applicationInfo.uid; 10051 res.pkg = newPackage; 10052 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10053 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10054 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10055 //to update install status 10056 mSettings.writeLPr(); 10057 } 10058 } 10059 10060 private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) { 10061 int pFlags = args.flags; 10062 String installerPackageName = args.installerPackageName; 10063 File tmpPackageFile = new File(args.getCodePath()); 10064 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10065 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10066 boolean replace = false; 10067 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10068 | (newInstall ? SCAN_NEW_INSTALL : 0); 10069 // Result object to be returned 10070 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10071 10072 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10073 // Retrieve PackageSettings and parse package 10074 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10075 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10076 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10077 PackageParser pp = new PackageParser(); 10078 pp.setSeparateProcesses(mSeparateProcesses); 10079 pp.setDisplayMetrics(mMetrics); 10080 10081 final PackageParser.Package pkg; 10082 try { 10083 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10084 } catch (PackageParserException e) { 10085 res.returnCode = e.error; 10086 return; 10087 } 10088 10089 String pkgName = res.name = pkg.packageName; 10090 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10091 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10092 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 10093 return; 10094 } 10095 } 10096 10097 try { 10098 pp.collectCertificates(pkg, parseFlags); 10099 pp.collectManifestDigest(pkg); 10100 } catch (PackageParserException e) { 10101 res.returnCode = e.error; 10102 return; 10103 } 10104 10105 /* If the installer passed in a manifest digest, compare it now. */ 10106 if (args.manifestDigest != null) { 10107 if (DEBUG_INSTALL) { 10108 final String parsedManifest = pkg.manifestDigest == null ? "null" 10109 : pkg.manifestDigest.toString(); 10110 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10111 + parsedManifest); 10112 } 10113 10114 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10115 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 10116 return; 10117 } 10118 } else if (DEBUG_INSTALL) { 10119 final String parsedManifest = pkg.manifestDigest == null 10120 ? "null" : pkg.manifestDigest.toString(); 10121 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10122 } 10123 10124 // Get rid of all references to package scan path via parser. 10125 pp = null; 10126 String oldCodePath = null; 10127 boolean systemApp = false; 10128 synchronized (mPackages) { 10129 // Check whether the newly-scanned package wants to define an already-defined perm 10130 int N = pkg.permissions.size(); 10131 for (int i = N-1; i >= 0; i--) { 10132 PackageParser.Permission perm = pkg.permissions.get(i); 10133 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10134 if (bp != null) { 10135 // If the defining package is signed with our cert, it's okay. This 10136 // also includes the "updating the same package" case, of course. 10137 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10138 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10139 // If the owning package is the system itself, we log but allow 10140 // install to proceed; we fail the install on all other permission 10141 // redefinitions. 10142 if (!bp.sourcePackage.equals("android")) { 10143 Slog.w(TAG, "Package " + pkg.packageName 10144 + " attempting to redeclare permission " + perm.info.name 10145 + " already owned by " + bp.sourcePackage); 10146 res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 10147 res.origPermission = perm.info.name; 10148 res.origPackage = bp.sourcePackage; 10149 return; 10150 } else { 10151 Slog.w(TAG, "Package " + pkg.packageName 10152 + " attempting to redeclare system permission " 10153 + perm.info.name + "; ignoring new declaration"); 10154 pkg.permissions.remove(i); 10155 } 10156 } 10157 } 10158 } 10159 10160 // Check if installing already existing package 10161 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10162 String oldName = mSettings.mRenamedPackages.get(pkgName); 10163 if (pkg.mOriginalPackages != null 10164 && pkg.mOriginalPackages.contains(oldName) 10165 && mPackages.containsKey(oldName)) { 10166 // This package is derived from an original package, 10167 // and this device has been updating from that original 10168 // name. We must continue using the original name, so 10169 // rename the new package here. 10170 pkg.setPackageName(oldName); 10171 pkgName = pkg.packageName; 10172 replace = true; 10173 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10174 + oldName + " pkgName=" + pkgName); 10175 } else if (mPackages.containsKey(pkgName)) { 10176 // This package, under its official name, already exists 10177 // on the device; we should replace it. 10178 replace = true; 10179 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10180 } 10181 } 10182 PackageSetting ps = mSettings.mPackages.get(pkgName); 10183 if (ps != null) { 10184 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10185 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10186 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10187 systemApp = (ps.pkg.applicationInfo.flags & 10188 ApplicationInfo.FLAG_SYSTEM) != 0; 10189 } 10190 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10191 } 10192 } 10193 10194 if (systemApp && onSd) { 10195 // Disable updates to system apps on sdcard 10196 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 10197 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10198 return; 10199 } 10200 10201 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10202 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10203 return; 10204 } 10205 10206 if (replace) { 10207 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10208 installerPackageName, res, args.abiOverride); 10209 } else { 10210 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10211 installerPackageName, res, args.abiOverride); 10212 } 10213 synchronized (mPackages) { 10214 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10215 if (ps != null) { 10216 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10217 } 10218 } 10219 } 10220 10221 private static boolean isForwardLocked(PackageParser.Package pkg) { 10222 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10223 } 10224 10225 10226 private boolean isForwardLocked(PackageSetting ps) { 10227 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10228 } 10229 10230 private static boolean isExternal(PackageParser.Package pkg) { 10231 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10232 } 10233 10234 private static boolean isExternal(PackageSetting ps) { 10235 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10236 } 10237 10238 private static boolean isSystemApp(PackageParser.Package pkg) { 10239 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10240 } 10241 10242 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10243 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10244 } 10245 10246 private static boolean isSystemApp(ApplicationInfo info) { 10247 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10248 } 10249 10250 private static boolean isSystemApp(PackageSetting ps) { 10251 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10252 } 10253 10254 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10255 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10256 } 10257 10258 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10259 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10260 } 10261 10262 private int packageFlagsToInstallFlags(PackageSetting ps) { 10263 int installFlags = 0; 10264 if (isExternal(ps)) { 10265 installFlags |= PackageManager.INSTALL_EXTERNAL; 10266 } 10267 if (isForwardLocked(ps)) { 10268 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10269 } 10270 return installFlags; 10271 } 10272 10273 private void deleteTempPackageFiles() { 10274 final FilenameFilter filter = new FilenameFilter() { 10275 public boolean accept(File dir, String name) { 10276 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10277 } 10278 }; 10279 deleteTempPackageFilesInDirectory(mAppInstallDir, filter); 10280 deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter); 10281 } 10282 10283 private static final void deleteTempPackageFilesInDirectory(File directory, 10284 FilenameFilter filter) { 10285 final File[] files = directory.listFiles(filter); 10286 if (!ArrayUtils.isEmpty(files)) { 10287 for (File file : files) { 10288 if (file.isDirectory()) { 10289 FileUtils.deleteContents(file); 10290 file.delete(); 10291 } else if (file.isFile()) { 10292 file.delete(); 10293 } 10294 } 10295 } 10296 } 10297 10298 private File createTempPackageDir(File installDir) throws IOException { 10299 int n = 0; 10300 while (n++ < 32) { 10301 final File file = new File(installDir, "vmdl" + mTempFileRandom.nextInt() + ".tmp"); 10302 try { 10303 Os.mkdir(file.getAbsolutePath(), 0755); 10304 Os.chmod(file.getAbsolutePath(), 0755); 10305 if (!SELinux.restorecon(file)) { 10306 throw new IOException("Failed to restorecon"); 10307 } 10308 return file; 10309 } catch (ErrnoException e) { 10310 if (e.errno == EEXIST) continue; 10311 throw e.rethrowAsIOException(); 10312 } 10313 } 10314 throw new IOException("Failed to create temp directory"); 10315 } 10316 10317 private File createTempPackageFile(File installDir) throws IOException { 10318 int n = 0; 10319 while (n++ < 32) { 10320 final File file = new File(installDir, "vmdl" + mTempFileRandom.nextInt() + ".tmp"); 10321 try { 10322 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10323 O_RDWR | O_CREAT | O_EXCL, 0644); 10324 IoUtils.closeQuietly(fd); 10325 Os.chmod(file.getAbsolutePath(), 0644); 10326 if (!SELinux.restorecon(file)) { 10327 throw new IOException("Failed to restorecon"); 10328 } 10329 return file; 10330 } catch (ErrnoException e) { 10331 if (e.errno == EEXIST) continue; 10332 throw e.rethrowAsIOException(); 10333 } 10334 } 10335 throw new IOException("Failed to create temp file"); 10336 } 10337 10338 @Override 10339 public void deletePackageAsUser(final String packageName, 10340 final IPackageDeleteObserver observer, 10341 final int userId, final int flags) { 10342 mContext.enforceCallingOrSelfPermission( 10343 android.Manifest.permission.DELETE_PACKAGES, null); 10344 final int uid = Binder.getCallingUid(); 10345 if (UserHandle.getUserId(uid) != userId) { 10346 mContext.enforceCallingPermission( 10347 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10348 "deletePackage for user " + userId); 10349 } 10350 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10351 try { 10352 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 10353 } catch (RemoteException re) { 10354 } 10355 return; 10356 } 10357 10358 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10359 // Queue up an async operation since the package deletion may take a little while. 10360 mHandler.post(new Runnable() { 10361 public void run() { 10362 mHandler.removeCallbacks(this); 10363 final int returnCode = deletePackageX(packageName, userId, flags); 10364 if (observer != null) { 10365 try { 10366 observer.packageDeleted(packageName, returnCode); 10367 } catch (RemoteException e) { 10368 Log.i(TAG, "Observer no longer exists."); 10369 } //end catch 10370 } //end if 10371 } //end run 10372 }); 10373 } 10374 10375 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10376 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10377 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10378 try { 10379 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10380 || dpm.isDeviceOwner(packageName))) { 10381 return true; 10382 } 10383 } catch (RemoteException e) { 10384 } 10385 return false; 10386 } 10387 10388 /** 10389 * This method is an internal method that could be get invoked either 10390 * to delete an installed package or to clean up a failed installation. 10391 * After deleting an installed package, a broadcast is sent to notify any 10392 * listeners that the package has been installed. For cleaning up a failed 10393 * installation, the broadcast is not necessary since the package's 10394 * installation wouldn't have sent the initial broadcast either 10395 * The key steps in deleting a package are 10396 * deleting the package information in internal structures like mPackages, 10397 * deleting the packages base directories through installd 10398 * updating mSettings to reflect current status 10399 * persisting settings for later use 10400 * sending a broadcast if necessary 10401 */ 10402 private int deletePackageX(String packageName, int userId, int flags) { 10403 final PackageRemovedInfo info = new PackageRemovedInfo(); 10404 final boolean res; 10405 10406 if (isPackageDeviceAdmin(packageName, userId)) { 10407 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10408 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10409 } 10410 10411 boolean removedForAllUsers = false; 10412 boolean systemUpdate = false; 10413 10414 // for the uninstall-updates case and restricted profiles, remember the per- 10415 // userhandle installed state 10416 int[] allUsers; 10417 boolean[] perUserInstalled; 10418 synchronized (mPackages) { 10419 PackageSetting ps = mSettings.mPackages.get(packageName); 10420 allUsers = sUserManager.getUserIds(); 10421 perUserInstalled = new boolean[allUsers.length]; 10422 for (int i = 0; i < allUsers.length; i++) { 10423 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10424 } 10425 } 10426 10427 synchronized (mInstallLock) { 10428 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10429 res = deletePackageLI(packageName, 10430 (flags & PackageManager.DELETE_ALL_USERS) != 0 10431 ? UserHandle.ALL : new UserHandle(userId), 10432 true, allUsers, perUserInstalled, 10433 flags | REMOVE_CHATTY, info, true); 10434 systemUpdate = info.isRemovedPackageSystemUpdate; 10435 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10436 removedForAllUsers = true; 10437 } 10438 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10439 + " removedForAllUsers=" + removedForAllUsers); 10440 } 10441 10442 if (res) { 10443 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10444 10445 // If the removed package was a system update, the old system package 10446 // was re-enabled; we need to broadcast this information 10447 if (systemUpdate) { 10448 Bundle extras = new Bundle(1); 10449 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10450 ? info.removedAppId : info.uid); 10451 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10452 10453 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10454 extras, null, null, null); 10455 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10456 extras, null, null, null); 10457 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10458 null, packageName, null, null); 10459 } 10460 } 10461 // Force a gc here. 10462 Runtime.getRuntime().gc(); 10463 // Delete the resources here after sending the broadcast to let 10464 // other processes clean up before deleting resources. 10465 if (info.args != null) { 10466 synchronized (mInstallLock) { 10467 info.args.doPostDeleteLI(true); 10468 } 10469 } 10470 10471 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10472 } 10473 10474 static class PackageRemovedInfo { 10475 String removedPackage; 10476 int uid = -1; 10477 int removedAppId = -1; 10478 int[] removedUsers = null; 10479 boolean isRemovedPackageSystemUpdate = false; 10480 // Clean up resources deleted packages. 10481 InstallArgs args = null; 10482 10483 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10484 Bundle extras = new Bundle(1); 10485 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10486 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10487 if (replacing) { 10488 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10489 } 10490 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10491 if (removedPackage != null) { 10492 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10493 extras, null, null, removedUsers); 10494 if (fullRemove && !replacing) { 10495 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10496 extras, null, null, removedUsers); 10497 } 10498 } 10499 if (removedAppId >= 0) { 10500 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10501 removedUsers); 10502 } 10503 } 10504 } 10505 10506 /* 10507 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10508 * flag is not set, the data directory is removed as well. 10509 * make sure this flag is set for partially installed apps. If not its meaningless to 10510 * delete a partially installed application. 10511 */ 10512 private void removePackageDataLI(PackageSetting ps, 10513 int[] allUserHandles, boolean[] perUserInstalled, 10514 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10515 String packageName = ps.name; 10516 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10517 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10518 // Retrieve object to delete permissions for shared user later on 10519 final PackageSetting deletedPs; 10520 // reader 10521 synchronized (mPackages) { 10522 deletedPs = mSettings.mPackages.get(packageName); 10523 if (outInfo != null) { 10524 outInfo.removedPackage = packageName; 10525 outInfo.removedUsers = deletedPs != null 10526 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10527 : null; 10528 } 10529 } 10530 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10531 removeDataDirsLI(packageName); 10532 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10533 } 10534 // writer 10535 synchronized (mPackages) { 10536 if (deletedPs != null) { 10537 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10538 if (outInfo != null) { 10539 mSettings.mKeySetManagerService.removeAppKeySetData(packageName); 10540 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10541 } 10542 if (deletedPs != null) { 10543 updatePermissionsLPw(deletedPs.name, null, 0); 10544 if (deletedPs.sharedUser != null) { 10545 // remove permissions associated with package 10546 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10547 } 10548 } 10549 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10550 } 10551 // make sure to preserve per-user disabled state if this removal was just 10552 // a downgrade of a system app to the factory package 10553 if (allUserHandles != null && perUserInstalled != null) { 10554 if (DEBUG_REMOVE) { 10555 Slog.d(TAG, "Propagating install state across downgrade"); 10556 } 10557 for (int i = 0; i < allUserHandles.length; i++) { 10558 if (DEBUG_REMOVE) { 10559 Slog.d(TAG, " user " + allUserHandles[i] 10560 + " => " + perUserInstalled[i]); 10561 } 10562 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10563 } 10564 } 10565 } 10566 // can downgrade to reader 10567 if (writeSettings) { 10568 // Save settings now 10569 mSettings.writeLPr(); 10570 } 10571 } 10572 if (outInfo != null) { 10573 // A user ID was deleted here. Go through all users and remove it 10574 // from KeyStore. 10575 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10576 } 10577 } 10578 10579 static boolean locationIsPrivileged(File path) { 10580 try { 10581 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10582 .getCanonicalPath(); 10583 return path.getCanonicalPath().startsWith(privilegedAppDir); 10584 } catch (IOException e) { 10585 Slog.e(TAG, "Unable to access code path " + path); 10586 } 10587 return false; 10588 } 10589 10590 /* 10591 * Tries to delete system package. 10592 */ 10593 private boolean deleteSystemPackageLI(PackageSetting newPs, 10594 int[] allUserHandles, boolean[] perUserInstalled, 10595 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10596 final boolean applyUserRestrictions 10597 = (allUserHandles != null) && (perUserInstalled != null); 10598 PackageSetting disabledPs = null; 10599 // Confirm if the system package has been updated 10600 // An updated system app can be deleted. This will also have to restore 10601 // the system pkg from system partition 10602 // reader 10603 synchronized (mPackages) { 10604 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10605 } 10606 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10607 + " disabledPs=" + disabledPs); 10608 if (disabledPs == null) { 10609 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10610 return false; 10611 } else if (DEBUG_REMOVE) { 10612 Slog.d(TAG, "Deleting system pkg from data partition"); 10613 } 10614 if (DEBUG_REMOVE) { 10615 if (applyUserRestrictions) { 10616 Slog.d(TAG, "Remembering install states:"); 10617 for (int i = 0; i < allUserHandles.length; i++) { 10618 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10619 } 10620 } 10621 } 10622 // Delete the updated package 10623 outInfo.isRemovedPackageSystemUpdate = true; 10624 if (disabledPs.versionCode < newPs.versionCode) { 10625 // Delete data for downgrades 10626 flags &= ~PackageManager.DELETE_KEEP_DATA; 10627 } else { 10628 // Preserve data by setting flag 10629 flags |= PackageManager.DELETE_KEEP_DATA; 10630 } 10631 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10632 allUserHandles, perUserInstalled, outInfo, writeSettings); 10633 if (!ret) { 10634 return false; 10635 } 10636 // writer 10637 synchronized (mPackages) { 10638 // Reinstate the old system package 10639 mSettings.enableSystemPackageLPw(newPs.name); 10640 // Remove any native libraries from the upgraded package. 10641 NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString); 10642 } 10643 // Install the system package 10644 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10645 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10646 if (locationIsPrivileged(disabledPs.codePath)) { 10647 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10648 } 10649 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath, 10650 parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null); 10651 10652 if (newPkg == null) { 10653 Slog.w(TAG, "Failed to restore system package:" + newPs.name 10654 + " with error:" + mLastScanError); 10655 return false; 10656 } 10657 // writer 10658 synchronized (mPackages) { 10659 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10660 setInternalAppNativeLibraryPath(newPkg, ps); 10661 updatePermissionsLPw(newPkg.packageName, newPkg, 10662 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10663 if (applyUserRestrictions) { 10664 if (DEBUG_REMOVE) { 10665 Slog.d(TAG, "Propagating install state across reinstall"); 10666 } 10667 for (int i = 0; i < allUserHandles.length; i++) { 10668 if (DEBUG_REMOVE) { 10669 Slog.d(TAG, " user " + allUserHandles[i] 10670 + " => " + perUserInstalled[i]); 10671 } 10672 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10673 } 10674 // Regardless of writeSettings we need to ensure that this restriction 10675 // state propagation is persisted 10676 mSettings.writeAllUsersPackageRestrictionsLPr(); 10677 } 10678 // can downgrade to reader here 10679 if (writeSettings) { 10680 mSettings.writeLPr(); 10681 } 10682 } 10683 return true; 10684 } 10685 10686 private boolean deleteInstalledPackageLI(PackageSetting ps, 10687 boolean deleteCodeAndResources, int flags, 10688 int[] allUserHandles, boolean[] perUserInstalled, 10689 PackageRemovedInfo outInfo, boolean writeSettings) { 10690 if (outInfo != null) { 10691 outInfo.uid = ps.appId; 10692 } 10693 10694 // Delete package data from internal structures and also remove data if flag is set 10695 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10696 10697 // Delete application code and resources 10698 if (deleteCodeAndResources && (outInfo != null)) { 10699 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10700 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 10701 getAppInstructionSetFromSettings(ps)); 10702 } 10703 return true; 10704 } 10705 10706 @Override 10707 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10708 int userId) { 10709 mContext.enforceCallingOrSelfPermission( 10710 android.Manifest.permission.DELETE_PACKAGES, null); 10711 synchronized (mPackages) { 10712 PackageSetting ps = mSettings.mPackages.get(packageName); 10713 if (ps == null) { 10714 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10715 return false; 10716 } 10717 if (!ps.getInstalled(userId)) { 10718 // Can't block uninstall for an app that is not installed or enabled. 10719 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10720 return false; 10721 } 10722 ps.setBlockUninstall(blockUninstall, userId); 10723 mSettings.writePackageRestrictionsLPr(userId); 10724 } 10725 return true; 10726 } 10727 10728 @Override 10729 public boolean getBlockUninstallForUser(String packageName, int userId) { 10730 synchronized (mPackages) { 10731 PackageSetting ps = mSettings.mPackages.get(packageName); 10732 if (ps == null) { 10733 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10734 return false; 10735 } 10736 return ps.getBlockUninstall(userId); 10737 } 10738 } 10739 10740 /* 10741 * This method handles package deletion in general 10742 */ 10743 private boolean deletePackageLI(String packageName, UserHandle user, 10744 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10745 int flags, PackageRemovedInfo outInfo, 10746 boolean writeSettings) { 10747 if (packageName == null) { 10748 Slog.w(TAG, "Attempt to delete null packageName."); 10749 return false; 10750 } 10751 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10752 PackageSetting ps; 10753 boolean dataOnly = false; 10754 int removeUser = -1; 10755 int appId = -1; 10756 synchronized (mPackages) { 10757 ps = mSettings.mPackages.get(packageName); 10758 if (ps == null) { 10759 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10760 return false; 10761 } 10762 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10763 && user.getIdentifier() != UserHandle.USER_ALL) { 10764 // The caller is asking that the package only be deleted for a single 10765 // user. To do this, we just mark its uninstalled state and delete 10766 // its data. If this is a system app, we only allow this to happen if 10767 // they have set the special DELETE_SYSTEM_APP which requests different 10768 // semantics than normal for uninstalling system apps. 10769 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10770 ps.setUserState(user.getIdentifier(), 10771 COMPONENT_ENABLED_STATE_DEFAULT, 10772 false, //installed 10773 true, //stopped 10774 true, //notLaunched 10775 false, //blocked 10776 null, null, null, 10777 false // blockUninstall 10778 ); 10779 if (!isSystemApp(ps)) { 10780 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10781 // Other user still have this package installed, so all 10782 // we need to do is clear this user's data and save that 10783 // it is uninstalled. 10784 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10785 removeUser = user.getIdentifier(); 10786 appId = ps.appId; 10787 mSettings.writePackageRestrictionsLPr(removeUser); 10788 } else { 10789 // We need to set it back to 'installed' so the uninstall 10790 // broadcasts will be sent correctly. 10791 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10792 ps.setInstalled(true, user.getIdentifier()); 10793 } 10794 } else { 10795 // This is a system app, so we assume that the 10796 // other users still have this package installed, so all 10797 // we need to do is clear this user's data and save that 10798 // it is uninstalled. 10799 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10800 removeUser = user.getIdentifier(); 10801 appId = ps.appId; 10802 mSettings.writePackageRestrictionsLPr(removeUser); 10803 } 10804 } 10805 } 10806 10807 if (removeUser >= 0) { 10808 // From above, we determined that we are deleting this only 10809 // for a single user. Continue the work here. 10810 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10811 if (outInfo != null) { 10812 outInfo.removedPackage = packageName; 10813 outInfo.removedAppId = appId; 10814 outInfo.removedUsers = new int[] {removeUser}; 10815 } 10816 mInstaller.clearUserData(packageName, removeUser); 10817 removeKeystoreDataIfNeeded(removeUser, appId); 10818 schedulePackageCleaning(packageName, removeUser, false); 10819 return true; 10820 } 10821 10822 if (dataOnly) { 10823 // Delete application data first 10824 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10825 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10826 return true; 10827 } 10828 10829 boolean ret = false; 10830 if (isSystemApp(ps)) { 10831 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10832 // When an updated system application is deleted we delete the existing resources as well and 10833 // fall back to existing code in system partition 10834 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10835 flags, outInfo, writeSettings); 10836 } else { 10837 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10838 // Kill application pre-emptively especially for apps on sd. 10839 killApplication(packageName, ps.appId, "uninstall pkg"); 10840 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10841 allUserHandles, perUserInstalled, 10842 outInfo, writeSettings); 10843 } 10844 10845 return ret; 10846 } 10847 10848 private final class ClearStorageConnection implements ServiceConnection { 10849 IMediaContainerService mContainerService; 10850 10851 @Override 10852 public void onServiceConnected(ComponentName name, IBinder service) { 10853 synchronized (this) { 10854 mContainerService = IMediaContainerService.Stub.asInterface(service); 10855 notifyAll(); 10856 } 10857 } 10858 10859 @Override 10860 public void onServiceDisconnected(ComponentName name) { 10861 } 10862 } 10863 10864 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10865 final boolean mounted; 10866 if (Environment.isExternalStorageEmulated()) { 10867 mounted = true; 10868 } else { 10869 final String status = Environment.getExternalStorageState(); 10870 10871 mounted = status.equals(Environment.MEDIA_MOUNTED) 10872 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 10873 } 10874 10875 if (!mounted) { 10876 return; 10877 } 10878 10879 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 10880 int[] users; 10881 if (userId == UserHandle.USER_ALL) { 10882 users = sUserManager.getUserIds(); 10883 } else { 10884 users = new int[] { userId }; 10885 } 10886 final ClearStorageConnection conn = new ClearStorageConnection(); 10887 if (mContext.bindServiceAsUser( 10888 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 10889 try { 10890 for (int curUser : users) { 10891 long timeout = SystemClock.uptimeMillis() + 5000; 10892 synchronized (conn) { 10893 long now = SystemClock.uptimeMillis(); 10894 while (conn.mContainerService == null && now < timeout) { 10895 try { 10896 conn.wait(timeout - now); 10897 } catch (InterruptedException e) { 10898 } 10899 } 10900 } 10901 if (conn.mContainerService == null) { 10902 return; 10903 } 10904 10905 final UserEnvironment userEnv = new UserEnvironment(curUser); 10906 clearDirectory(conn.mContainerService, 10907 userEnv.buildExternalStorageAppCacheDirs(packageName)); 10908 if (allData) { 10909 clearDirectory(conn.mContainerService, 10910 userEnv.buildExternalStorageAppDataDirs(packageName)); 10911 clearDirectory(conn.mContainerService, 10912 userEnv.buildExternalStorageAppMediaDirs(packageName)); 10913 } 10914 } 10915 } finally { 10916 mContext.unbindService(conn); 10917 } 10918 } 10919 } 10920 10921 @Override 10922 public void clearApplicationUserData(final String packageName, 10923 final IPackageDataObserver observer, final int userId) { 10924 mContext.enforceCallingOrSelfPermission( 10925 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 10926 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 10927 // Queue up an async operation since the package deletion may take a little while. 10928 mHandler.post(new Runnable() { 10929 public void run() { 10930 mHandler.removeCallbacks(this); 10931 final boolean succeeded; 10932 synchronized (mInstallLock) { 10933 succeeded = clearApplicationUserDataLI(packageName, userId); 10934 } 10935 clearExternalStorageDataSync(packageName, userId, true); 10936 if (succeeded) { 10937 // invoke DeviceStorageMonitor's update method to clear any notifications 10938 DeviceStorageMonitorInternal 10939 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 10940 if (dsm != null) { 10941 dsm.checkMemory(); 10942 } 10943 } 10944 if(observer != null) { 10945 try { 10946 observer.onRemoveCompleted(packageName, succeeded); 10947 } catch (RemoteException e) { 10948 Log.i(TAG, "Observer no longer exists."); 10949 } 10950 } //end if observer 10951 } //end run 10952 }); 10953 } 10954 10955 private boolean clearApplicationUserDataLI(String packageName, int userId) { 10956 if (packageName == null) { 10957 Slog.w(TAG, "Attempt to delete null packageName."); 10958 return false; 10959 } 10960 PackageParser.Package p; 10961 boolean dataOnly = false; 10962 final int appId; 10963 synchronized (mPackages) { 10964 p = mPackages.get(packageName); 10965 if (p == null) { 10966 dataOnly = true; 10967 PackageSetting ps = mSettings.mPackages.get(packageName); 10968 if ((ps == null) || (ps.pkg == null)) { 10969 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10970 return false; 10971 } 10972 p = ps.pkg; 10973 } 10974 if (!dataOnly) { 10975 // need to check this only for fully installed applications 10976 if (p == null) { 10977 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10978 return false; 10979 } 10980 final ApplicationInfo applicationInfo = p.applicationInfo; 10981 if (applicationInfo == null) { 10982 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 10983 return false; 10984 } 10985 } 10986 if (p != null && p.applicationInfo != null) { 10987 appId = p.applicationInfo.uid; 10988 } else { 10989 appId = -1; 10990 } 10991 } 10992 int retCode = mInstaller.clearUserData(packageName, userId); 10993 if (retCode < 0) { 10994 Slog.w(TAG, "Couldn't remove cache files for package: " 10995 + packageName); 10996 return false; 10997 } 10998 removeKeystoreDataIfNeeded(userId, appId); 10999 return true; 11000 } 11001 11002 /** 11003 * Remove entries from the keystore daemon. Will only remove it if the 11004 * {@code appId} is valid. 11005 */ 11006 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11007 if (appId < 0) { 11008 return; 11009 } 11010 11011 final KeyStore keyStore = KeyStore.getInstance(); 11012 if (keyStore != null) { 11013 if (userId == UserHandle.USER_ALL) { 11014 for (final int individual : sUserManager.getUserIds()) { 11015 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11016 } 11017 } else { 11018 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11019 } 11020 } else { 11021 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11022 } 11023 } 11024 11025 @Override 11026 public void deleteApplicationCacheFiles(final String packageName, 11027 final IPackageDataObserver observer) { 11028 mContext.enforceCallingOrSelfPermission( 11029 android.Manifest.permission.DELETE_CACHE_FILES, null); 11030 // Queue up an async operation since the package deletion may take a little while. 11031 final int userId = UserHandle.getCallingUserId(); 11032 mHandler.post(new Runnable() { 11033 public void run() { 11034 mHandler.removeCallbacks(this); 11035 final boolean succeded; 11036 synchronized (mInstallLock) { 11037 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11038 } 11039 clearExternalStorageDataSync(packageName, userId, false); 11040 if(observer != null) { 11041 try { 11042 observer.onRemoveCompleted(packageName, succeded); 11043 } catch (RemoteException e) { 11044 Log.i(TAG, "Observer no longer exists."); 11045 } 11046 } //end if observer 11047 } //end run 11048 }); 11049 } 11050 11051 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11052 if (packageName == null) { 11053 Slog.w(TAG, "Attempt to delete null packageName."); 11054 return false; 11055 } 11056 PackageParser.Package p; 11057 synchronized (mPackages) { 11058 p = mPackages.get(packageName); 11059 } 11060 if (p == null) { 11061 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11062 return false; 11063 } 11064 final ApplicationInfo applicationInfo = p.applicationInfo; 11065 if (applicationInfo == null) { 11066 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11067 return false; 11068 } 11069 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11070 if (retCode < 0) { 11071 Slog.w(TAG, "Couldn't remove cache files for package: " 11072 + packageName + " u" + userId); 11073 return false; 11074 } 11075 return true; 11076 } 11077 11078 @Override 11079 public void getPackageSizeInfo(final String packageName, int userHandle, 11080 final IPackageStatsObserver observer) { 11081 mContext.enforceCallingOrSelfPermission( 11082 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11083 if (packageName == null) { 11084 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11085 } 11086 11087 PackageStats stats = new PackageStats(packageName, userHandle); 11088 11089 /* 11090 * Queue up an async operation since the package measurement may take a 11091 * little while. 11092 */ 11093 Message msg = mHandler.obtainMessage(INIT_COPY); 11094 msg.obj = new MeasureParams(stats, observer); 11095 mHandler.sendMessage(msg); 11096 } 11097 11098 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11099 PackageStats pStats) { 11100 if (packageName == null) { 11101 Slog.w(TAG, "Attempt to get size of null packageName."); 11102 return false; 11103 } 11104 PackageParser.Package p; 11105 boolean dataOnly = false; 11106 String libDirPath = null; 11107 String asecPath = null; 11108 PackageSetting ps = null; 11109 synchronized (mPackages) { 11110 p = mPackages.get(packageName); 11111 ps = mSettings.mPackages.get(packageName); 11112 if(p == null) { 11113 dataOnly = true; 11114 if((ps == null) || (ps.pkg == null)) { 11115 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11116 return false; 11117 } 11118 p = ps.pkg; 11119 } 11120 if (ps != null) { 11121 libDirPath = ps.nativeLibraryPathString; 11122 } 11123 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11124 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11125 if (secureContainerId != null) { 11126 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11127 } 11128 } 11129 } 11130 String publicSrcDir = null; 11131 if(!dataOnly) { 11132 final ApplicationInfo applicationInfo = p.applicationInfo; 11133 if (applicationInfo == null) { 11134 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11135 return false; 11136 } 11137 if (isForwardLocked(p)) { 11138 publicSrcDir = applicationInfo.getBaseResourcePath(); 11139 } 11140 } 11141 // TODO: extend to measure size of split APKs 11142 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirPath, 11143 publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps), 11144 pStats); 11145 if (res < 0) { 11146 return false; 11147 } 11148 11149 // Fix-up for forward-locked applications in ASEC containers. 11150 if (!isExternal(p)) { 11151 pStats.codeSize += pStats.externalCodeSize; 11152 pStats.externalCodeSize = 0L; 11153 } 11154 11155 return true; 11156 } 11157 11158 11159 @Override 11160 public void addPackageToPreferred(String packageName) { 11161 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11162 } 11163 11164 @Override 11165 public void removePackageFromPreferred(String packageName) { 11166 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11167 } 11168 11169 @Override 11170 public List<PackageInfo> getPreferredPackages(int flags) { 11171 return new ArrayList<PackageInfo>(); 11172 } 11173 11174 private int getUidTargetSdkVersionLockedLPr(int uid) { 11175 Object obj = mSettings.getUserIdLPr(uid); 11176 if (obj instanceof SharedUserSetting) { 11177 final SharedUserSetting sus = (SharedUserSetting) obj; 11178 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11179 final Iterator<PackageSetting> it = sus.packages.iterator(); 11180 while (it.hasNext()) { 11181 final PackageSetting ps = it.next(); 11182 if (ps.pkg != null) { 11183 int v = ps.pkg.applicationInfo.targetSdkVersion; 11184 if (v < vers) vers = v; 11185 } 11186 } 11187 return vers; 11188 } else if (obj instanceof PackageSetting) { 11189 final PackageSetting ps = (PackageSetting) obj; 11190 if (ps.pkg != null) { 11191 return ps.pkg.applicationInfo.targetSdkVersion; 11192 } 11193 } 11194 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11195 } 11196 11197 @Override 11198 public void addPreferredActivity(IntentFilter filter, int match, 11199 ComponentName[] set, ComponentName activity, int userId) { 11200 addPreferredActivityInternal(filter, match, set, activity, true, userId); 11201 } 11202 11203 private void addPreferredActivityInternal(IntentFilter filter, int match, 11204 ComponentName[] set, ComponentName activity, boolean always, int userId) { 11205 // writer 11206 int callingUid = Binder.getCallingUid(); 11207 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11208 if (filter.countActions() == 0) { 11209 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11210 return; 11211 } 11212 synchronized (mPackages) { 11213 if (mContext.checkCallingOrSelfPermission( 11214 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11215 != PackageManager.PERMISSION_GRANTED) { 11216 if (getUidTargetSdkVersionLockedLPr(callingUid) 11217 < Build.VERSION_CODES.FROYO) { 11218 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11219 + callingUid); 11220 return; 11221 } 11222 mContext.enforceCallingOrSelfPermission( 11223 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11224 } 11225 11226 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 11227 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11228 mSettings.editPreferredActivitiesLPw(userId).addFilter( 11229 new PreferredActivity(filter, match, set, activity, always)); 11230 mSettings.writePackageRestrictionsLPr(userId); 11231 } 11232 } 11233 11234 @Override 11235 public void replacePreferredActivity(IntentFilter filter, int match, 11236 ComponentName[] set, ComponentName activity) { 11237 if (filter.countActions() != 1) { 11238 throw new IllegalArgumentException( 11239 "replacePreferredActivity expects filter to have only 1 action."); 11240 } 11241 if (filter.countDataAuthorities() != 0 11242 || filter.countDataPaths() != 0 11243 || filter.countDataSchemes() > 1 11244 || filter.countDataTypes() != 0) { 11245 throw new IllegalArgumentException( 11246 "replacePreferredActivity expects filter to have no data authorities, " + 11247 "paths, or types; and at most one scheme."); 11248 } 11249 synchronized (mPackages) { 11250 if (mContext.checkCallingOrSelfPermission( 11251 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11252 != PackageManager.PERMISSION_GRANTED) { 11253 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11254 < Build.VERSION_CODES.FROYO) { 11255 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11256 + Binder.getCallingUid()); 11257 return; 11258 } 11259 mContext.enforceCallingOrSelfPermission( 11260 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11261 } 11262 11263 final int callingUserId = UserHandle.getCallingUserId(); 11264 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 11265 if (pir != null) { 11266 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 11267 if (filter.countDataSchemes() == 1) { 11268 Uri.Builder builder = new Uri.Builder(); 11269 builder.scheme(filter.getDataScheme(0)); 11270 intent.setData(builder.build()); 11271 } 11272 List<PreferredActivity> matches = pir.queryIntent( 11273 intent, null, true, callingUserId); 11274 if (DEBUG_PREFERRED) { 11275 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 11276 } 11277 for (int i = 0; i < matches.size(); i++) { 11278 PreferredActivity pa = matches.get(i); 11279 if (DEBUG_PREFERRED) { 11280 Slog.i(TAG, "Removing preferred activity " 11281 + pa.mPref.mComponent + ":"); 11282 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11283 } 11284 pir.removeFilter(pa); 11285 } 11286 } 11287 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 11288 } 11289 } 11290 11291 @Override 11292 public void clearPackagePreferredActivities(String packageName) { 11293 final int uid = Binder.getCallingUid(); 11294 // writer 11295 synchronized (mPackages) { 11296 PackageParser.Package pkg = mPackages.get(packageName); 11297 if (pkg == null || pkg.applicationInfo.uid != uid) { 11298 if (mContext.checkCallingOrSelfPermission( 11299 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11300 != PackageManager.PERMISSION_GRANTED) { 11301 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11302 < Build.VERSION_CODES.FROYO) { 11303 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11304 + Binder.getCallingUid()); 11305 return; 11306 } 11307 mContext.enforceCallingOrSelfPermission( 11308 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11309 } 11310 } 11311 11312 int user = UserHandle.getCallingUserId(); 11313 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11314 mSettings.writePackageRestrictionsLPr(user); 11315 scheduleWriteSettingsLocked(); 11316 } 11317 } 11318 } 11319 11320 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11321 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11322 ArrayList<PreferredActivity> removed = null; 11323 boolean changed = false; 11324 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11325 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11326 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11327 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11328 continue; 11329 } 11330 Iterator<PreferredActivity> it = pir.filterIterator(); 11331 while (it.hasNext()) { 11332 PreferredActivity pa = it.next(); 11333 // Mark entry for removal only if it matches the package name 11334 // and the entry is of type "always". 11335 if (packageName == null || 11336 (pa.mPref.mComponent.getPackageName().equals(packageName) 11337 && pa.mPref.mAlways)) { 11338 if (removed == null) { 11339 removed = new ArrayList<PreferredActivity>(); 11340 } 11341 removed.add(pa); 11342 } 11343 } 11344 if (removed != null) { 11345 for (int j=0; j<removed.size(); j++) { 11346 PreferredActivity pa = removed.get(j); 11347 pir.removeFilter(pa); 11348 } 11349 changed = true; 11350 } 11351 } 11352 return changed; 11353 } 11354 11355 @Override 11356 public void resetPreferredActivities(int userId) { 11357 mContext.enforceCallingOrSelfPermission( 11358 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11359 // writer 11360 synchronized (mPackages) { 11361 int user = UserHandle.getCallingUserId(); 11362 clearPackagePreferredActivitiesLPw(null, user); 11363 mSettings.readDefaultPreferredAppsLPw(this, user); 11364 mSettings.writePackageRestrictionsLPr(user); 11365 scheduleWriteSettingsLocked(); 11366 } 11367 } 11368 11369 @Override 11370 public int getPreferredActivities(List<IntentFilter> outFilters, 11371 List<ComponentName> outActivities, String packageName) { 11372 11373 int num = 0; 11374 final int userId = UserHandle.getCallingUserId(); 11375 // reader 11376 synchronized (mPackages) { 11377 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11378 if (pir != null) { 11379 final Iterator<PreferredActivity> it = pir.filterIterator(); 11380 while (it.hasNext()) { 11381 final PreferredActivity pa = it.next(); 11382 if (packageName == null 11383 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11384 && pa.mPref.mAlways)) { 11385 if (outFilters != null) { 11386 outFilters.add(new IntentFilter(pa)); 11387 } 11388 if (outActivities != null) { 11389 outActivities.add(pa.mPref.mComponent); 11390 } 11391 } 11392 } 11393 } 11394 } 11395 11396 return num; 11397 } 11398 11399 @Override 11400 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11401 int userId) { 11402 int callingUid = Binder.getCallingUid(); 11403 if (callingUid != Process.SYSTEM_UID) { 11404 throw new SecurityException( 11405 "addPersistentPreferredActivity can only be run by the system"); 11406 } 11407 if (filter.countActions() == 0) { 11408 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11409 return; 11410 } 11411 synchronized (mPackages) { 11412 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11413 " :"); 11414 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11415 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11416 new PersistentPreferredActivity(filter, activity)); 11417 mSettings.writePackageRestrictionsLPr(userId); 11418 } 11419 } 11420 11421 @Override 11422 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11423 int callingUid = Binder.getCallingUid(); 11424 if (callingUid != Process.SYSTEM_UID) { 11425 throw new SecurityException( 11426 "clearPackagePersistentPreferredActivities can only be run by the system"); 11427 } 11428 ArrayList<PersistentPreferredActivity> removed = null; 11429 boolean changed = false; 11430 synchronized (mPackages) { 11431 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11432 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11433 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11434 .valueAt(i); 11435 if (userId != thisUserId) { 11436 continue; 11437 } 11438 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11439 while (it.hasNext()) { 11440 PersistentPreferredActivity ppa = it.next(); 11441 // Mark entry for removal only if it matches the package name. 11442 if (ppa.mComponent.getPackageName().equals(packageName)) { 11443 if (removed == null) { 11444 removed = new ArrayList<PersistentPreferredActivity>(); 11445 } 11446 removed.add(ppa); 11447 } 11448 } 11449 if (removed != null) { 11450 for (int j=0; j<removed.size(); j++) { 11451 PersistentPreferredActivity ppa = removed.get(j); 11452 ppir.removeFilter(ppa); 11453 } 11454 changed = true; 11455 } 11456 } 11457 11458 if (changed) { 11459 mSettings.writePackageRestrictionsLPr(userId); 11460 } 11461 } 11462 } 11463 11464 @Override 11465 public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId, 11466 int targetUserId, int flags) { 11467 mContext.enforceCallingOrSelfPermission( 11468 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11469 if (intentFilter.countActions() == 0) { 11470 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11471 return; 11472 } 11473 synchronized (mPackages) { 11474 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11475 targetUserId, flags); 11476 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11477 mSettings.writePackageRestrictionsLPr(sourceUserId); 11478 } 11479 } 11480 11481 public void addCrossProfileIntentsForPackage(String packageName, 11482 int sourceUserId, int targetUserId) { 11483 mContext.enforceCallingOrSelfPermission( 11484 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11485 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11486 mSettings.writePackageRestrictionsLPr(sourceUserId); 11487 } 11488 11489 public void removeCrossProfileIntentsForPackage(String packageName, 11490 int sourceUserId, int targetUserId) { 11491 mContext.enforceCallingOrSelfPermission( 11492 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11493 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11494 mSettings.writePackageRestrictionsLPr(sourceUserId); 11495 } 11496 11497 @Override 11498 public void clearCrossProfileIntentFilters(int sourceUserId) { 11499 mContext.enforceCallingOrSelfPermission( 11500 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11501 synchronized (mPackages) { 11502 CrossProfileIntentResolver resolver = 11503 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11504 HashSet<CrossProfileIntentFilter> set = 11505 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11506 for (CrossProfileIntentFilter filter : set) { 11507 if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) { 11508 resolver.removeFilter(filter); 11509 } 11510 } 11511 mSettings.writePackageRestrictionsLPr(sourceUserId); 11512 } 11513 } 11514 11515 @Override 11516 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11517 Intent intent = new Intent(Intent.ACTION_MAIN); 11518 intent.addCategory(Intent.CATEGORY_HOME); 11519 11520 final int callingUserId = UserHandle.getCallingUserId(); 11521 List<ResolveInfo> list = queryIntentActivities(intent, null, 11522 PackageManager.GET_META_DATA, callingUserId); 11523 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11524 true, false, false, callingUserId); 11525 11526 allHomeCandidates.clear(); 11527 if (list != null) { 11528 for (ResolveInfo ri : list) { 11529 allHomeCandidates.add(ri); 11530 } 11531 } 11532 return (preferred == null || preferred.activityInfo == null) 11533 ? null 11534 : new ComponentName(preferred.activityInfo.packageName, 11535 preferred.activityInfo.name); 11536 } 11537 11538 @Override 11539 public void setApplicationEnabledSetting(String appPackageName, 11540 int newState, int flags, int userId, String callingPackage) { 11541 if (!sUserManager.exists(userId)) return; 11542 if (callingPackage == null) { 11543 callingPackage = Integer.toString(Binder.getCallingUid()); 11544 } 11545 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11546 } 11547 11548 @Override 11549 public void setComponentEnabledSetting(ComponentName componentName, 11550 int newState, int flags, int userId) { 11551 if (!sUserManager.exists(userId)) return; 11552 setEnabledSetting(componentName.getPackageName(), 11553 componentName.getClassName(), newState, flags, userId, null); 11554 } 11555 11556 private void setEnabledSetting(final String packageName, String className, int newState, 11557 final int flags, int userId, String callingPackage) { 11558 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11559 || newState == COMPONENT_ENABLED_STATE_ENABLED 11560 || newState == COMPONENT_ENABLED_STATE_DISABLED 11561 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11562 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11563 throw new IllegalArgumentException("Invalid new component state: " 11564 + newState); 11565 } 11566 PackageSetting pkgSetting; 11567 final int uid = Binder.getCallingUid(); 11568 final int permission = mContext.checkCallingOrSelfPermission( 11569 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11570 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11571 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11572 boolean sendNow = false; 11573 boolean isApp = (className == null); 11574 String componentName = isApp ? packageName : className; 11575 int packageUid = -1; 11576 ArrayList<String> components; 11577 11578 // writer 11579 synchronized (mPackages) { 11580 pkgSetting = mSettings.mPackages.get(packageName); 11581 if (pkgSetting == null) { 11582 if (className == null) { 11583 throw new IllegalArgumentException( 11584 "Unknown package: " + packageName); 11585 } 11586 throw new IllegalArgumentException( 11587 "Unknown component: " + packageName 11588 + "/" + className); 11589 } 11590 // Allow root and verify that userId is not being specified by a different user 11591 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11592 throw new SecurityException( 11593 "Permission Denial: attempt to change component state from pid=" 11594 + Binder.getCallingPid() 11595 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11596 } 11597 if (className == null) { 11598 // We're dealing with an application/package level state change 11599 if (pkgSetting.getEnabled(userId) == newState) { 11600 // Nothing to do 11601 return; 11602 } 11603 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11604 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11605 // Don't care about who enables an app. 11606 callingPackage = null; 11607 } 11608 pkgSetting.setEnabled(newState, userId, callingPackage); 11609 // pkgSetting.pkg.mSetEnabled = newState; 11610 } else { 11611 // We're dealing with a component level state change 11612 // First, verify that this is a valid class name. 11613 PackageParser.Package pkg = pkgSetting.pkg; 11614 if (pkg == null || !pkg.hasComponentClassName(className)) { 11615 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11616 throw new IllegalArgumentException("Component class " + className 11617 + " does not exist in " + packageName); 11618 } else { 11619 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11620 + className + " does not exist in " + packageName); 11621 } 11622 } 11623 switch (newState) { 11624 case COMPONENT_ENABLED_STATE_ENABLED: 11625 if (!pkgSetting.enableComponentLPw(className, userId)) { 11626 return; 11627 } 11628 break; 11629 case COMPONENT_ENABLED_STATE_DISABLED: 11630 if (!pkgSetting.disableComponentLPw(className, userId)) { 11631 return; 11632 } 11633 break; 11634 case COMPONENT_ENABLED_STATE_DEFAULT: 11635 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11636 return; 11637 } 11638 break; 11639 default: 11640 Slog.e(TAG, "Invalid new component state: " + newState); 11641 return; 11642 } 11643 } 11644 mSettings.writePackageRestrictionsLPr(userId); 11645 components = mPendingBroadcasts.get(userId, packageName); 11646 final boolean newPackage = components == null; 11647 if (newPackage) { 11648 components = new ArrayList<String>(); 11649 } 11650 if (!components.contains(componentName)) { 11651 components.add(componentName); 11652 } 11653 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11654 sendNow = true; 11655 // Purge entry from pending broadcast list if another one exists already 11656 // since we are sending one right away. 11657 mPendingBroadcasts.remove(userId, packageName); 11658 } else { 11659 if (newPackage) { 11660 mPendingBroadcasts.put(userId, packageName, components); 11661 } 11662 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11663 // Schedule a message 11664 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11665 } 11666 } 11667 } 11668 11669 long callingId = Binder.clearCallingIdentity(); 11670 try { 11671 if (sendNow) { 11672 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11673 sendPackageChangedBroadcast(packageName, 11674 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11675 } 11676 } finally { 11677 Binder.restoreCallingIdentity(callingId); 11678 } 11679 } 11680 11681 private void sendPackageChangedBroadcast(String packageName, 11682 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11683 if (DEBUG_INSTALL) 11684 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11685 + componentNames); 11686 Bundle extras = new Bundle(4); 11687 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11688 String nameList[] = new String[componentNames.size()]; 11689 componentNames.toArray(nameList); 11690 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11691 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11692 extras.putInt(Intent.EXTRA_UID, packageUid); 11693 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11694 new int[] {UserHandle.getUserId(packageUid)}); 11695 } 11696 11697 @Override 11698 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11699 if (!sUserManager.exists(userId)) return; 11700 final int uid = Binder.getCallingUid(); 11701 final int permission = mContext.checkCallingOrSelfPermission( 11702 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11703 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11704 enforceCrossUserPermission(uid, userId, true, "stop package"); 11705 // writer 11706 synchronized (mPackages) { 11707 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11708 uid, userId)) { 11709 scheduleWritePackageRestrictionsLocked(userId); 11710 } 11711 } 11712 } 11713 11714 @Override 11715 public String getInstallerPackageName(String packageName) { 11716 // reader 11717 synchronized (mPackages) { 11718 return mSettings.getInstallerPackageNameLPr(packageName); 11719 } 11720 } 11721 11722 @Override 11723 public int getApplicationEnabledSetting(String packageName, int userId) { 11724 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11725 int uid = Binder.getCallingUid(); 11726 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11727 // reader 11728 synchronized (mPackages) { 11729 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11730 } 11731 } 11732 11733 @Override 11734 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11735 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11736 int uid = Binder.getCallingUid(); 11737 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11738 // reader 11739 synchronized (mPackages) { 11740 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11741 } 11742 } 11743 11744 @Override 11745 public void enterSafeMode() { 11746 enforceSystemOrRoot("Only the system can request entering safe mode"); 11747 11748 if (!mSystemReady) { 11749 mSafeMode = true; 11750 } 11751 } 11752 11753 @Override 11754 public void systemReady() { 11755 mSystemReady = true; 11756 11757 // Read the compatibilty setting when the system is ready. 11758 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11759 mContext.getContentResolver(), 11760 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11761 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11762 if (DEBUG_SETTINGS) { 11763 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11764 } 11765 11766 synchronized (mPackages) { 11767 // Verify that all of the preferred activity components actually 11768 // exist. It is possible for applications to be updated and at 11769 // that point remove a previously declared activity component that 11770 // had been set as a preferred activity. We try to clean this up 11771 // the next time we encounter that preferred activity, but it is 11772 // possible for the user flow to never be able to return to that 11773 // situation so here we do a sanity check to make sure we haven't 11774 // left any junk around. 11775 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11776 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11777 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11778 removed.clear(); 11779 for (PreferredActivity pa : pir.filterSet()) { 11780 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11781 removed.add(pa); 11782 } 11783 } 11784 if (removed.size() > 0) { 11785 for (int r=0; r<removed.size(); r++) { 11786 PreferredActivity pa = removed.get(r); 11787 Slog.w(TAG, "Removing dangling preferred activity: " 11788 + pa.mPref.mComponent); 11789 pir.removeFilter(pa); 11790 } 11791 mSettings.writePackageRestrictionsLPr( 11792 mSettings.mPreferredActivities.keyAt(i)); 11793 } 11794 } 11795 } 11796 sUserManager.systemReady(); 11797 } 11798 11799 @Override 11800 public boolean isSafeMode() { 11801 return mSafeMode; 11802 } 11803 11804 @Override 11805 public boolean hasSystemUidErrors() { 11806 return mHasSystemUidErrors; 11807 } 11808 11809 static String arrayToString(int[] array) { 11810 StringBuffer buf = new StringBuffer(128); 11811 buf.append('['); 11812 if (array != null) { 11813 for (int i=0; i<array.length; i++) { 11814 if (i > 0) buf.append(", "); 11815 buf.append(array[i]); 11816 } 11817 } 11818 buf.append(']'); 11819 return buf.toString(); 11820 } 11821 11822 static class DumpState { 11823 public static final int DUMP_LIBS = 1 << 0; 11824 11825 public static final int DUMP_FEATURES = 1 << 1; 11826 11827 public static final int DUMP_RESOLVERS = 1 << 2; 11828 11829 public static final int DUMP_PERMISSIONS = 1 << 3; 11830 11831 public static final int DUMP_PACKAGES = 1 << 4; 11832 11833 public static final int DUMP_SHARED_USERS = 1 << 5; 11834 11835 public static final int DUMP_MESSAGES = 1 << 6; 11836 11837 public static final int DUMP_PROVIDERS = 1 << 7; 11838 11839 public static final int DUMP_VERIFIERS = 1 << 8; 11840 11841 public static final int DUMP_PREFERRED = 1 << 9; 11842 11843 public static final int DUMP_PREFERRED_XML = 1 << 10; 11844 11845 public static final int DUMP_KEYSETS = 1 << 11; 11846 11847 public static final int DUMP_VERSION = 1 << 12; 11848 11849 public static final int OPTION_SHOW_FILTERS = 1 << 0; 11850 11851 private int mTypes; 11852 11853 private int mOptions; 11854 11855 private boolean mTitlePrinted; 11856 11857 private SharedUserSetting mSharedUser; 11858 11859 public boolean isDumping(int type) { 11860 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 11861 return true; 11862 } 11863 11864 return (mTypes & type) != 0; 11865 } 11866 11867 public void setDump(int type) { 11868 mTypes |= type; 11869 } 11870 11871 public boolean isOptionEnabled(int option) { 11872 return (mOptions & option) != 0; 11873 } 11874 11875 public void setOptionEnabled(int option) { 11876 mOptions |= option; 11877 } 11878 11879 public boolean onTitlePrinted() { 11880 final boolean printed = mTitlePrinted; 11881 mTitlePrinted = true; 11882 return printed; 11883 } 11884 11885 public boolean getTitlePrinted() { 11886 return mTitlePrinted; 11887 } 11888 11889 public void setTitlePrinted(boolean enabled) { 11890 mTitlePrinted = enabled; 11891 } 11892 11893 public SharedUserSetting getSharedUser() { 11894 return mSharedUser; 11895 } 11896 11897 public void setSharedUser(SharedUserSetting user) { 11898 mSharedUser = user; 11899 } 11900 } 11901 11902 @Override 11903 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 11904 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 11905 != PackageManager.PERMISSION_GRANTED) { 11906 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 11907 + Binder.getCallingPid() 11908 + ", uid=" + Binder.getCallingUid() 11909 + " without permission " 11910 + android.Manifest.permission.DUMP); 11911 return; 11912 } 11913 11914 DumpState dumpState = new DumpState(); 11915 boolean fullPreferred = false; 11916 boolean checkin = false; 11917 11918 String packageName = null; 11919 11920 int opti = 0; 11921 while (opti < args.length) { 11922 String opt = args[opti]; 11923 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 11924 break; 11925 } 11926 opti++; 11927 if ("-a".equals(opt)) { 11928 // Right now we only know how to print all. 11929 } else if ("-h".equals(opt)) { 11930 pw.println("Package manager dump options:"); 11931 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 11932 pw.println(" --checkin: dump for a checkin"); 11933 pw.println(" -f: print details of intent filters"); 11934 pw.println(" -h: print this help"); 11935 pw.println(" cmd may be one of:"); 11936 pw.println(" l[ibraries]: list known shared libraries"); 11937 pw.println(" f[ibraries]: list device features"); 11938 pw.println(" k[eysets]: print known keysets"); 11939 pw.println(" r[esolvers]: dump intent resolvers"); 11940 pw.println(" perm[issions]: dump permissions"); 11941 pw.println(" pref[erred]: print preferred package settings"); 11942 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 11943 pw.println(" prov[iders]: dump content providers"); 11944 pw.println(" p[ackages]: dump installed packages"); 11945 pw.println(" s[hared-users]: dump shared user IDs"); 11946 pw.println(" m[essages]: print collected runtime messages"); 11947 pw.println(" v[erifiers]: print package verifier info"); 11948 pw.println(" version: print database version info"); 11949 pw.println(" write: write current settings now"); 11950 pw.println(" <package.name>: info about given package"); 11951 return; 11952 } else if ("--checkin".equals(opt)) { 11953 checkin = true; 11954 } else if ("-f".equals(opt)) { 11955 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 11956 } else { 11957 pw.println("Unknown argument: " + opt + "; use -h for help"); 11958 } 11959 } 11960 11961 // Is the caller requesting to dump a particular piece of data? 11962 if (opti < args.length) { 11963 String cmd = args[opti]; 11964 opti++; 11965 // Is this a package name? 11966 if ("android".equals(cmd) || cmd.contains(".")) { 11967 packageName = cmd; 11968 // When dumping a single package, we always dump all of its 11969 // filter information since the amount of data will be reasonable. 11970 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 11971 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 11972 dumpState.setDump(DumpState.DUMP_LIBS); 11973 } else if ("f".equals(cmd) || "features".equals(cmd)) { 11974 dumpState.setDump(DumpState.DUMP_FEATURES); 11975 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 11976 dumpState.setDump(DumpState.DUMP_RESOLVERS); 11977 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 11978 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 11979 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 11980 dumpState.setDump(DumpState.DUMP_PREFERRED); 11981 } else if ("preferred-xml".equals(cmd)) { 11982 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 11983 if (opti < args.length && "--full".equals(args[opti])) { 11984 fullPreferred = true; 11985 opti++; 11986 } 11987 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 11988 dumpState.setDump(DumpState.DUMP_PACKAGES); 11989 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 11990 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 11991 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 11992 dumpState.setDump(DumpState.DUMP_PROVIDERS); 11993 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 11994 dumpState.setDump(DumpState.DUMP_MESSAGES); 11995 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 11996 dumpState.setDump(DumpState.DUMP_VERIFIERS); 11997 } else if ("version".equals(cmd)) { 11998 dumpState.setDump(DumpState.DUMP_VERSION); 11999 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12000 dumpState.setDump(DumpState.DUMP_KEYSETS); 12001 } else if ("write".equals(cmd)) { 12002 synchronized (mPackages) { 12003 mSettings.writeLPr(); 12004 pw.println("Settings written."); 12005 return; 12006 } 12007 } 12008 } 12009 12010 if (checkin) { 12011 pw.println("vers,1"); 12012 } 12013 12014 // reader 12015 synchronized (mPackages) { 12016 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12017 if (!checkin) { 12018 if (dumpState.onTitlePrinted()) 12019 pw.println(); 12020 pw.println("Database versions:"); 12021 pw.print(" SDK Version:"); 12022 pw.print(" internal="); 12023 pw.print(mSettings.mInternalSdkPlatform); 12024 pw.print(" external="); 12025 pw.println(mSettings.mExternalSdkPlatform); 12026 pw.print(" DB Version:"); 12027 pw.print(" internal="); 12028 pw.print(mSettings.mInternalDatabaseVersion); 12029 pw.print(" external="); 12030 pw.println(mSettings.mExternalDatabaseVersion); 12031 } 12032 } 12033 12034 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12035 if (!checkin) { 12036 if (dumpState.onTitlePrinted()) 12037 pw.println(); 12038 pw.println("Verifiers:"); 12039 pw.print(" Required: "); 12040 pw.print(mRequiredVerifierPackage); 12041 pw.print(" (uid="); 12042 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12043 pw.println(")"); 12044 } else if (mRequiredVerifierPackage != null) { 12045 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12046 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12047 } 12048 } 12049 12050 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12051 boolean printedHeader = false; 12052 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12053 while (it.hasNext()) { 12054 String name = it.next(); 12055 SharedLibraryEntry ent = mSharedLibraries.get(name); 12056 if (!checkin) { 12057 if (!printedHeader) { 12058 if (dumpState.onTitlePrinted()) 12059 pw.println(); 12060 pw.println("Libraries:"); 12061 printedHeader = true; 12062 } 12063 pw.print(" "); 12064 } else { 12065 pw.print("lib,"); 12066 } 12067 pw.print(name); 12068 if (!checkin) { 12069 pw.print(" -> "); 12070 } 12071 if (ent.path != null) { 12072 if (!checkin) { 12073 pw.print("(jar) "); 12074 pw.print(ent.path); 12075 } else { 12076 pw.print(",jar,"); 12077 pw.print(ent.path); 12078 } 12079 } else { 12080 if (!checkin) { 12081 pw.print("(apk) "); 12082 pw.print(ent.apk); 12083 } else { 12084 pw.print(",apk,"); 12085 pw.print(ent.apk); 12086 } 12087 } 12088 pw.println(); 12089 } 12090 } 12091 12092 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12093 if (dumpState.onTitlePrinted()) 12094 pw.println(); 12095 if (!checkin) { 12096 pw.println("Features:"); 12097 } 12098 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12099 while (it.hasNext()) { 12100 String name = it.next(); 12101 if (!checkin) { 12102 pw.print(" "); 12103 } else { 12104 pw.print("feat,"); 12105 } 12106 pw.println(name); 12107 } 12108 } 12109 12110 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12111 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12112 : "Activity Resolver Table:", " ", packageName, 12113 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12114 dumpState.setTitlePrinted(true); 12115 } 12116 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12117 : "Receiver Resolver Table:", " ", packageName, 12118 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12119 dumpState.setTitlePrinted(true); 12120 } 12121 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12122 : "Service Resolver Table:", " ", packageName, 12123 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12124 dumpState.setTitlePrinted(true); 12125 } 12126 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12127 : "Provider Resolver Table:", " ", packageName, 12128 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12129 dumpState.setTitlePrinted(true); 12130 } 12131 } 12132 12133 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12134 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12135 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12136 int user = mSettings.mPreferredActivities.keyAt(i); 12137 if (pir.dump(pw, 12138 dumpState.getTitlePrinted() 12139 ? "\nPreferred Activities User " + user + ":" 12140 : "Preferred Activities User " + user + ":", " ", 12141 packageName, true)) { 12142 dumpState.setTitlePrinted(true); 12143 } 12144 } 12145 } 12146 12147 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12148 pw.flush(); 12149 FileOutputStream fout = new FileOutputStream(fd); 12150 BufferedOutputStream str = new BufferedOutputStream(fout); 12151 XmlSerializer serializer = new FastXmlSerializer(); 12152 try { 12153 serializer.setOutput(str, "utf-8"); 12154 serializer.startDocument(null, true); 12155 serializer.setFeature( 12156 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12157 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12158 serializer.endDocument(); 12159 serializer.flush(); 12160 } catch (IllegalArgumentException e) { 12161 pw.println("Failed writing: " + e); 12162 } catch (IllegalStateException e) { 12163 pw.println("Failed writing: " + e); 12164 } catch (IOException e) { 12165 pw.println("Failed writing: " + e); 12166 } 12167 } 12168 12169 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12170 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12171 } 12172 12173 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12174 boolean printedSomething = false; 12175 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12176 if (packageName != null && !packageName.equals(p.info.packageName)) { 12177 continue; 12178 } 12179 if (!printedSomething) { 12180 if (dumpState.onTitlePrinted()) 12181 pw.println(); 12182 pw.println("Registered ContentProviders:"); 12183 printedSomething = true; 12184 } 12185 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12186 pw.print(" "); pw.println(p.toString()); 12187 } 12188 printedSomething = false; 12189 for (Map.Entry<String, PackageParser.Provider> entry : 12190 mProvidersByAuthority.entrySet()) { 12191 PackageParser.Provider p = entry.getValue(); 12192 if (packageName != null && !packageName.equals(p.info.packageName)) { 12193 continue; 12194 } 12195 if (!printedSomething) { 12196 if (dumpState.onTitlePrinted()) 12197 pw.println(); 12198 pw.println("ContentProvider Authorities:"); 12199 printedSomething = true; 12200 } 12201 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12202 pw.print(" "); pw.println(p.toString()); 12203 if (p.info != null && p.info.applicationInfo != null) { 12204 final String appInfo = p.info.applicationInfo.toString(); 12205 pw.print(" applicationInfo="); pw.println(appInfo); 12206 } 12207 } 12208 } 12209 12210 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12211 mSettings.mKeySetManagerService.dump(pw, packageName, dumpState); 12212 } 12213 12214 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12215 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12216 } 12217 12218 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12219 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12220 } 12221 12222 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12223 if (dumpState.onTitlePrinted()) 12224 pw.println(); 12225 mSettings.dumpReadMessagesLPr(pw, dumpState); 12226 12227 pw.println(); 12228 pw.println("Package warning messages:"); 12229 final File fname = getSettingsProblemFile(); 12230 FileInputStream in = null; 12231 try { 12232 in = new FileInputStream(fname); 12233 final int avail = in.available(); 12234 final byte[] data = new byte[avail]; 12235 in.read(data); 12236 pw.print(new String(data)); 12237 } catch (FileNotFoundException e) { 12238 } catch (IOException e) { 12239 } finally { 12240 if (in != null) { 12241 try { 12242 in.close(); 12243 } catch (IOException e) { 12244 } 12245 } 12246 } 12247 } 12248 } 12249 } 12250 12251 // ------- apps on sdcard specific code ------- 12252 static final boolean DEBUG_SD_INSTALL = false; 12253 12254 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12255 12256 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12257 12258 private boolean mMediaMounted = false; 12259 12260 private String getEncryptKey() { 12261 try { 12262 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12263 SD_ENCRYPTION_KEYSTORE_NAME); 12264 if (sdEncKey == null) { 12265 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12266 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12267 if (sdEncKey == null) { 12268 Slog.e(TAG, "Failed to create encryption keys"); 12269 return null; 12270 } 12271 } 12272 return sdEncKey; 12273 } catch (NoSuchAlgorithmException nsae) { 12274 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12275 return null; 12276 } catch (IOException ioe) { 12277 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12278 return null; 12279 } 12280 12281 } 12282 12283 /* package */static String getTempContainerId() { 12284 int tmpIdx = 1; 12285 String list[] = PackageHelper.getSecureContainerList(); 12286 if (list != null) { 12287 for (final String name : list) { 12288 // Ignore null and non-temporary container entries 12289 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12290 continue; 12291 } 12292 12293 String subStr = name.substring(mTempContainerPrefix.length()); 12294 try { 12295 int cid = Integer.parseInt(subStr); 12296 if (cid >= tmpIdx) { 12297 tmpIdx = cid + 1; 12298 } 12299 } catch (NumberFormatException e) { 12300 } 12301 } 12302 } 12303 return mTempContainerPrefix + tmpIdx; 12304 } 12305 12306 /* 12307 * Update media status on PackageManager. 12308 */ 12309 @Override 12310 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12311 int callingUid = Binder.getCallingUid(); 12312 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12313 throw new SecurityException("Media status can only be updated by the system"); 12314 } 12315 // reader; this apparently protects mMediaMounted, but should probably 12316 // be a different lock in that case. 12317 synchronized (mPackages) { 12318 Log.i(TAG, "Updating external media status from " 12319 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12320 + (mediaStatus ? "mounted" : "unmounted")); 12321 if (DEBUG_SD_INSTALL) 12322 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12323 + ", mMediaMounted=" + mMediaMounted); 12324 if (mediaStatus == mMediaMounted) { 12325 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12326 : 0, -1); 12327 mHandler.sendMessage(msg); 12328 return; 12329 } 12330 mMediaMounted = mediaStatus; 12331 } 12332 // Queue up an async operation since the package installation may take a 12333 // little while. 12334 mHandler.post(new Runnable() { 12335 public void run() { 12336 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12337 } 12338 }); 12339 } 12340 12341 /** 12342 * Called by MountService when the initial ASECs to scan are available. 12343 * Should block until all the ASEC containers are finished being scanned. 12344 */ 12345 public void scanAvailableAsecs() { 12346 updateExternalMediaStatusInner(true, false, false); 12347 if (mShouldRestoreconData) { 12348 SELinuxMMAC.setRestoreconDone(); 12349 mShouldRestoreconData = false; 12350 } 12351 } 12352 12353 /* 12354 * Collect information of applications on external media, map them against 12355 * existing containers and update information based on current mount status. 12356 * Please note that we always have to report status if reportStatus has been 12357 * set to true especially when unloading packages. 12358 */ 12359 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12360 boolean externalStorage) { 12361 // Collection of uids 12362 int uidArr[] = null; 12363 // Collection of stale containers 12364 HashSet<String> removeCids = new HashSet<String>(); 12365 // Collection of packages on external media with valid containers. 12366 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12367 // Get list of secure containers. 12368 final String list[] = PackageHelper.getSecureContainerList(); 12369 if (list == null || list.length == 0) { 12370 Log.i(TAG, "No secure containers on sdcard"); 12371 } else { 12372 // Process list of secure containers and categorize them 12373 // as active or stale based on their package internal state. 12374 int uidList[] = new int[list.length]; 12375 int num = 0; 12376 // reader 12377 synchronized (mPackages) { 12378 for (String cid : list) { 12379 if (DEBUG_SD_INSTALL) 12380 Log.i(TAG, "Processing container " + cid); 12381 String pkgName = getAsecPackageName(cid); 12382 if (pkgName == null) { 12383 if (DEBUG_SD_INSTALL) 12384 Log.i(TAG, "Container : " + cid + " stale"); 12385 removeCids.add(cid); 12386 continue; 12387 } 12388 if (DEBUG_SD_INSTALL) 12389 Log.i(TAG, "Looking for pkg : " + pkgName); 12390 12391 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12392 if (ps == null) { 12393 Log.i(TAG, "Deleting container with no matching settings " + cid); 12394 removeCids.add(cid); 12395 continue; 12396 } 12397 12398 /* 12399 * Skip packages that are not external if we're unmounting 12400 * external storage. 12401 */ 12402 if (externalStorage && !isMounted && !isExternal(ps)) { 12403 continue; 12404 } 12405 12406 final AsecInstallArgs args = new AsecInstallArgs(cid, 12407 getAppInstructionSetFromSettings(ps), 12408 isForwardLocked(ps)); 12409 // The package status is changed only if the code path 12410 // matches between settings and the container id. 12411 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12412 if (DEBUG_SD_INSTALL) { 12413 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12414 + " at code path: " + ps.codePathString); 12415 } 12416 12417 // We do have a valid package installed on sdcard 12418 processCids.put(args, ps.codePathString); 12419 final int uid = ps.appId; 12420 if (uid != -1) { 12421 uidList[num++] = uid; 12422 } 12423 } else { 12424 Log.i(TAG, "Deleting stale container for " + cid); 12425 removeCids.add(cid); 12426 } 12427 } 12428 } 12429 12430 if (num > 0) { 12431 // Sort uid list 12432 Arrays.sort(uidList, 0, num); 12433 // Throw away duplicates 12434 uidArr = new int[num]; 12435 uidArr[0] = uidList[0]; 12436 int di = 0; 12437 for (int i = 1; i < num; i++) { 12438 if (uidList[i - 1] != uidList[i]) { 12439 uidArr[di++] = uidList[i]; 12440 } 12441 } 12442 } 12443 } 12444 // Process packages with valid entries. 12445 if (isMounted) { 12446 if (DEBUG_SD_INSTALL) 12447 Log.i(TAG, "Loading packages"); 12448 loadMediaPackages(processCids, uidArr, removeCids); 12449 startCleaningPackages(); 12450 } else { 12451 if (DEBUG_SD_INSTALL) 12452 Log.i(TAG, "Unloading packages"); 12453 unloadMediaPackages(processCids, uidArr, reportStatus); 12454 } 12455 } 12456 12457 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12458 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12459 int size = pkgList.size(); 12460 if (size > 0) { 12461 // Send broadcasts here 12462 Bundle extras = new Bundle(); 12463 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12464 .toArray(new String[size])); 12465 if (uidArr != null) { 12466 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12467 } 12468 if (replacing) { 12469 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12470 } 12471 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12472 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12473 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12474 } 12475 } 12476 12477 /* 12478 * Look at potentially valid container ids from processCids If package 12479 * information doesn't match the one on record or package scanning fails, 12480 * the cid is added to list of removeCids. We currently don't delete stale 12481 * containers. 12482 */ 12483 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12484 HashSet<String> removeCids) { 12485 ArrayList<String> pkgList = new ArrayList<String>(); 12486 Set<AsecInstallArgs> keys = processCids.keySet(); 12487 boolean doGc = false; 12488 for (AsecInstallArgs args : keys) { 12489 String codePath = processCids.get(args); 12490 if (DEBUG_SD_INSTALL) 12491 Log.i(TAG, "Loading container : " + args.cid); 12492 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12493 try { 12494 // Make sure there are no container errors first. 12495 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12496 Slog.e(TAG, "Failed to mount cid : " + args.cid 12497 + " when installing from sdcard"); 12498 continue; 12499 } 12500 // Check code path here. 12501 if (codePath == null || !codePath.equals(args.getCodePath())) { 12502 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12503 + " does not match one in settings " + codePath); 12504 continue; 12505 } 12506 // Parse package 12507 int parseFlags = mDefParseFlags; 12508 if (args.isExternal()) { 12509 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12510 } 12511 if (args.isFwdLocked()) { 12512 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12513 } 12514 12515 doGc = true; 12516 synchronized (mInstallLock) { 12517 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 12518 0, 0, null, null); 12519 // Scan the package 12520 if (pkg != null) { 12521 /* 12522 * TODO why is the lock being held? doPostInstall is 12523 * called in other places without the lock. This needs 12524 * to be straightened out. 12525 */ 12526 // writer 12527 synchronized (mPackages) { 12528 retCode = PackageManager.INSTALL_SUCCEEDED; 12529 pkgList.add(pkg.packageName); 12530 // Post process args 12531 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12532 pkg.applicationInfo.uid); 12533 } 12534 } else { 12535 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12536 } 12537 } 12538 12539 } finally { 12540 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12541 // Don't destroy container here. Wait till gc clears things 12542 // up. 12543 removeCids.add(args.cid); 12544 } 12545 } 12546 } 12547 // writer 12548 synchronized (mPackages) { 12549 // If the platform SDK has changed since the last time we booted, 12550 // we need to re-grant app permission to catch any new ones that 12551 // appear. This is really a hack, and means that apps can in some 12552 // cases get permissions that the user didn't initially explicitly 12553 // allow... it would be nice to have some better way to handle 12554 // this situation. 12555 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12556 if (regrantPermissions) 12557 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12558 + mSdkVersion + "; regranting permissions for external storage"); 12559 mSettings.mExternalSdkPlatform = mSdkVersion; 12560 12561 // Make sure group IDs have been assigned, and any permission 12562 // changes in other apps are accounted for 12563 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12564 | (regrantPermissions 12565 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12566 : 0)); 12567 12568 mSettings.updateExternalDatabaseVersion(); 12569 12570 // can downgrade to reader 12571 // Persist settings 12572 mSettings.writeLPr(); 12573 } 12574 // Send a broadcast to let everyone know we are done processing 12575 if (pkgList.size() > 0) { 12576 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12577 } 12578 // Force gc to avoid any stale parser references that we might have. 12579 if (doGc) { 12580 Runtime.getRuntime().gc(); 12581 } 12582 // List stale containers and destroy stale temporary containers. 12583 if (removeCids != null) { 12584 for (String cid : removeCids) { 12585 if (cid.startsWith(mTempContainerPrefix)) { 12586 Log.i(TAG, "Destroying stale temporary container " + cid); 12587 PackageHelper.destroySdDir(cid); 12588 } else { 12589 Log.w(TAG, "Container " + cid + " is stale"); 12590 } 12591 } 12592 } 12593 } 12594 12595 /* 12596 * Utility method to unload a list of specified containers 12597 */ 12598 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12599 // Just unmount all valid containers. 12600 for (AsecInstallArgs arg : cidArgs) { 12601 synchronized (mInstallLock) { 12602 arg.doPostDeleteLI(false); 12603 } 12604 } 12605 } 12606 12607 /* 12608 * Unload packages mounted on external media. This involves deleting package 12609 * data from internal structures, sending broadcasts about diabled packages, 12610 * gc'ing to free up references, unmounting all secure containers 12611 * corresponding to packages on external media, and posting a 12612 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12613 * that we always have to post this message if status has been requested no 12614 * matter what. 12615 */ 12616 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12617 final boolean reportStatus) { 12618 if (DEBUG_SD_INSTALL) 12619 Log.i(TAG, "unloading media packages"); 12620 ArrayList<String> pkgList = new ArrayList<String>(); 12621 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12622 final Set<AsecInstallArgs> keys = processCids.keySet(); 12623 for (AsecInstallArgs args : keys) { 12624 String pkgName = args.getPackageName(); 12625 if (DEBUG_SD_INSTALL) 12626 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12627 // Delete package internally 12628 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12629 synchronized (mInstallLock) { 12630 boolean res = deletePackageLI(pkgName, null, false, null, null, 12631 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12632 if (res) { 12633 pkgList.add(pkgName); 12634 } else { 12635 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12636 failedList.add(args); 12637 } 12638 } 12639 } 12640 12641 // reader 12642 synchronized (mPackages) { 12643 // We didn't update the settings after removing each package; 12644 // write them now for all packages. 12645 mSettings.writeLPr(); 12646 } 12647 12648 // We have to absolutely send UPDATED_MEDIA_STATUS only 12649 // after confirming that all the receivers processed the ordered 12650 // broadcast when packages get disabled, force a gc to clean things up. 12651 // and unload all the containers. 12652 if (pkgList.size() > 0) { 12653 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12654 new IIntentReceiver.Stub() { 12655 public void performReceive(Intent intent, int resultCode, String data, 12656 Bundle extras, boolean ordered, boolean sticky, 12657 int sendingUser) throws RemoteException { 12658 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12659 reportStatus ? 1 : 0, 1, keys); 12660 mHandler.sendMessage(msg); 12661 } 12662 }); 12663 } else { 12664 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12665 keys); 12666 mHandler.sendMessage(msg); 12667 } 12668 } 12669 12670 /** Binder call */ 12671 @Override 12672 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12673 final int flags) { 12674 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12675 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12676 int returnCode = PackageManager.MOVE_SUCCEEDED; 12677 int currFlags = 0; 12678 int newFlags = 0; 12679 // reader 12680 synchronized (mPackages) { 12681 PackageParser.Package pkg = mPackages.get(packageName); 12682 if (pkg == null) { 12683 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12684 } else { 12685 // Disable moving fwd locked apps and system packages 12686 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12687 Slog.w(TAG, "Cannot move system application"); 12688 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12689 } else if (pkg.mOperationPending) { 12690 Slog.w(TAG, "Attempt to move package which has pending operations"); 12691 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12692 } else { 12693 // Find install location first 12694 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12695 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12696 Slog.w(TAG, "Ambigous flags specified for move location."); 12697 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12698 } else { 12699 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12700 : PackageManager.INSTALL_INTERNAL; 12701 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12702 : PackageManager.INSTALL_INTERNAL; 12703 12704 if (newFlags == currFlags) { 12705 Slog.w(TAG, "No move required. Trying to move to same location"); 12706 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12707 } else { 12708 if (isForwardLocked(pkg)) { 12709 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12710 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12711 } 12712 } 12713 } 12714 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12715 pkg.mOperationPending = true; 12716 } 12717 } 12718 } 12719 12720 /* 12721 * TODO this next block probably shouldn't be inside the lock. We 12722 * can't guarantee these won't change after this is fired off 12723 * anyway. 12724 */ 12725 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12726 processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user), 12727 returnCode); 12728 } else { 12729 Message msg = mHandler.obtainMessage(INIT_COPY); 12730 final String instructionSet = getAppInstructionSet(pkg.applicationInfo); 12731 InstallArgs srcArgs = createInstallArgsForExisting(currFlags, 12732 pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(), 12733 pkg.applicationInfo.nativeLibraryDir, instructionSet); 12734 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 12735 instructionSet, pkg.applicationInfo.uid, user); 12736 msg.obj = mp; 12737 mHandler.sendMessage(msg); 12738 } 12739 } 12740 } 12741 12742 private void processPendingMove(final MoveParams mp, final int currentStatus) { 12743 // Queue up an async operation since the package deletion may take a 12744 // little while. 12745 mHandler.post(new Runnable() { 12746 public void run() { 12747 // TODO fix this; this does nothing. 12748 mHandler.removeCallbacks(this); 12749 int returnCode = currentStatus; 12750 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 12751 int uidArr[] = null; 12752 ArrayList<String> pkgList = null; 12753 synchronized (mPackages) { 12754 PackageParser.Package pkg = mPackages.get(mp.packageName); 12755 if (pkg == null) { 12756 Slog.w(TAG, " Package " + mp.packageName 12757 + " doesn't exist. Aborting move"); 12758 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12759 } else if (!mp.srcArgs.getCodePath().equals( 12760 pkg.applicationInfo.getCodePath())) { 12761 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 12762 + mp.srcArgs.getCodePath() + " to " 12763 + pkg.applicationInfo.getCodePath() 12764 + " Aborting move and returning error"); 12765 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12766 } else { 12767 uidArr = new int[] { 12768 pkg.applicationInfo.uid 12769 }; 12770 pkgList = new ArrayList<String>(); 12771 pkgList.add(mp.packageName); 12772 } 12773 } 12774 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12775 // Send resources unavailable broadcast 12776 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 12777 // Update package code and resource paths 12778 synchronized (mInstallLock) { 12779 synchronized (mPackages) { 12780 PackageParser.Package pkg = mPackages.get(mp.packageName); 12781 // Recheck for package again. 12782 if (pkg == null) { 12783 Slog.w(TAG, " Package " + mp.packageName 12784 + " doesn't exist. Aborting move"); 12785 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12786 } else if (!mp.srcArgs.getCodePath().equals( 12787 pkg.applicationInfo.getCodePath())) { 12788 Slog.w(TAG, "Package " + mp.packageName 12789 + " code path changed from " + mp.srcArgs.getCodePath() 12790 + " to " + pkg.applicationInfo.getCodePath() 12791 + " Aborting move and returning error"); 12792 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12793 } else { 12794 final String oldCodePath = pkg.codePath; 12795 final String newCodePath = mp.targetArgs.getCodePath(); 12796 final String newResPath = mp.targetArgs.getResourcePath(); 12797 final String newNativePath = mp.targetArgs 12798 .getNativeLibraryPath(); 12799 12800 final File newNativeDir = new File(newNativePath); 12801 12802 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 12803 NativeLibraryHelper.Handle handle = null; 12804 try { 12805 handle = NativeLibraryHelper.Handle.create( 12806 new File(newCodePath)); 12807 final int abi = NativeLibraryHelper.findSupportedAbi( 12808 handle, Build.SUPPORTED_ABIS); 12809 if (abi >= 0) { 12810 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 12811 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 12812 } 12813 } catch (IOException ioe) { 12814 Slog.w(TAG, "Unable to extract native libs for package :" 12815 + mp.packageName, ioe); 12816 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12817 } finally { 12818 IoUtils.closeQuietly(handle); 12819 } 12820 } 12821 final int[] users = sUserManager.getUserIds(); 12822 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12823 for (int user : users) { 12824 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 12825 newNativePath, user) < 0) { 12826 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12827 } 12828 } 12829 } 12830 12831 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12832 pkg.codePath = newCodePath; 12833 pkg.baseCodePath = newCodePath; 12834 // Move dex files around 12835 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 12836 // Moving of dex files failed. Set 12837 // error code and abort move. 12838 pkg.codePath = oldCodePath; 12839 pkg.baseCodePath = oldCodePath; 12840 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12841 } 12842 } 12843 12844 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12845 pkg.applicationInfo.setCodePath(newCodePath); 12846 pkg.applicationInfo.setBaseCodePath(newCodePath); 12847 pkg.applicationInfo.setSplitCodePaths(null); 12848 pkg.applicationInfo.setResourcePath(newResPath); 12849 pkg.applicationInfo.setBaseResourcePath(newResPath); 12850 pkg.applicationInfo.setSplitResourcePaths(null); 12851 pkg.applicationInfo.nativeLibraryDir = newNativePath; 12852 12853 PackageSetting ps = (PackageSetting) pkg.mExtras; 12854 ps.codePath = new File(pkg.applicationInfo.getCodePath()); 12855 ps.codePathString = ps.codePath.getPath(); 12856 ps.resourcePath = new File( 12857 pkg.applicationInfo.getResourcePath()); 12858 ps.resourcePathString = ps.resourcePath.getPath(); 12859 ps.nativeLibraryPathString = newNativePath; 12860 // Set the application info flag 12861 // correctly. 12862 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 12863 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12864 } else { 12865 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12866 } 12867 ps.setFlags(pkg.applicationInfo.flags); 12868 mAppDirs.remove(oldCodePath); 12869 mAppDirs.put(newCodePath, pkg); 12870 // Persist settings 12871 mSettings.writeLPr(); 12872 } 12873 } 12874 } 12875 } 12876 // Send resources available broadcast 12877 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12878 } 12879 } 12880 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12881 // Clean up failed installation 12882 if (mp.targetArgs != null) { 12883 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 12884 -1); 12885 } 12886 } else { 12887 // Force a gc to clear things up. 12888 Runtime.getRuntime().gc(); 12889 // Delete older code 12890 synchronized (mInstallLock) { 12891 mp.srcArgs.doPostDeleteLI(true); 12892 } 12893 } 12894 12895 // Allow more operations on this file if we didn't fail because 12896 // an operation was already pending for this package. 12897 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 12898 synchronized (mPackages) { 12899 PackageParser.Package pkg = mPackages.get(mp.packageName); 12900 if (pkg != null) { 12901 pkg.mOperationPending = false; 12902 } 12903 } 12904 } 12905 12906 IPackageMoveObserver observer = mp.observer; 12907 if (observer != null) { 12908 try { 12909 observer.packageMoved(mp.packageName, returnCode); 12910 } catch (RemoteException e) { 12911 Log.i(TAG, "Observer no longer exists."); 12912 } 12913 } 12914 } 12915 }); 12916 } 12917 12918 @Override 12919 public boolean setInstallLocation(int loc) { 12920 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 12921 null); 12922 if (getInstallLocation() == loc) { 12923 return true; 12924 } 12925 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 12926 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 12927 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 12928 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 12929 return true; 12930 } 12931 return false; 12932 } 12933 12934 @Override 12935 public int getInstallLocation() { 12936 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12937 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 12938 PackageHelper.APP_INSTALL_AUTO); 12939 } 12940 12941 /** Called by UserManagerService */ 12942 void cleanUpUserLILPw(int userHandle) { 12943 mDirtyUsers.remove(userHandle); 12944 mSettings.removeUserLPw(userHandle); 12945 mPendingBroadcasts.remove(userHandle); 12946 if (mInstaller != null) { 12947 // Technically, we shouldn't be doing this with the package lock 12948 // held. However, this is very rare, and there is already so much 12949 // other disk I/O going on, that we'll let it slide for now. 12950 mInstaller.removeUserDataDirs(userHandle); 12951 } 12952 mUserNeedsBadging.delete(userHandle); 12953 } 12954 12955 /** Called by UserManagerService */ 12956 void createNewUserLILPw(int userHandle, File path) { 12957 if (mInstaller != null) { 12958 mInstaller.createUserConfig(userHandle); 12959 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 12960 } 12961 } 12962 12963 @Override 12964 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 12965 mContext.enforceCallingOrSelfPermission( 12966 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12967 "Only package verification agents can read the verifier device identity"); 12968 12969 synchronized (mPackages) { 12970 return mSettings.getVerifierDeviceIdentityLPw(); 12971 } 12972 } 12973 12974 @Override 12975 public void setPermissionEnforced(String permission, boolean enforced) { 12976 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 12977 if (READ_EXTERNAL_STORAGE.equals(permission)) { 12978 synchronized (mPackages) { 12979 if (mSettings.mReadExternalStorageEnforced == null 12980 || mSettings.mReadExternalStorageEnforced != enforced) { 12981 mSettings.mReadExternalStorageEnforced = enforced; 12982 mSettings.writeLPr(); 12983 } 12984 } 12985 // kill any non-foreground processes so we restart them and 12986 // grant/revoke the GID. 12987 final IActivityManager am = ActivityManagerNative.getDefault(); 12988 if (am != null) { 12989 final long token = Binder.clearCallingIdentity(); 12990 try { 12991 am.killProcessesBelowForeground("setPermissionEnforcement"); 12992 } catch (RemoteException e) { 12993 } finally { 12994 Binder.restoreCallingIdentity(token); 12995 } 12996 } 12997 } else { 12998 throw new IllegalArgumentException("No selective enforcement for " + permission); 12999 } 13000 } 13001 13002 @Override 13003 @Deprecated 13004 public boolean isPermissionEnforced(String permission) { 13005 return true; 13006 } 13007 13008 @Override 13009 public boolean isStorageLow() { 13010 final long token = Binder.clearCallingIdentity(); 13011 try { 13012 final DeviceStorageMonitorInternal 13013 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13014 if (dsm != null) { 13015 return dsm.isMemoryLow(); 13016 } else { 13017 return false; 13018 } 13019 } finally { 13020 Binder.restoreCallingIdentity(token); 13021 } 13022 } 13023 13024 @Override 13025 public IPackageInstaller getPackageInstaller() { 13026 return mInstallerService; 13027 } 13028 13029 private boolean userNeedsBadging(int userId) { 13030 int index = mUserNeedsBadging.indexOfKey(userId); 13031 if (index < 0) { 13032 final UserInfo userInfo; 13033 final long token = Binder.clearCallingIdentity(); 13034 try { 13035 userInfo = sUserManager.getUserInfo(userId); 13036 } finally { 13037 Binder.restoreCallingIdentity(token); 13038 } 13039 final boolean b; 13040 if (userInfo != null && userInfo.isManagedProfile()) { 13041 b = true; 13042 } else { 13043 b = false; 13044 } 13045 mUserNeedsBadging.put(userId, b); 13046 return b; 13047 } 13048 return mUserNeedsBadging.valueAt(index); 13049 } 13050} 13051