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