PackageManagerService.java revision a25dc2bbe70b7449dc57e9619778ba592c198003
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.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 45import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 46import static android.content.pm.PackageParser.isApkFile; 47import static android.os.Process.PACKAGE_INFO_GID; 48import static android.os.Process.SYSTEM_UID; 49import static android.system.OsConstants.O_CREAT; 50import static android.system.OsConstants.O_RDWR; 51import static android.system.OsConstants.S_IRGRP; 52import static android.system.OsConstants.S_IROTH; 53import static android.system.OsConstants.S_IRWXU; 54import static android.system.OsConstants.S_IXGRP; 55import static android.system.OsConstants.S_IXOTH; 56import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 57import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 58import static com.android.internal.util.ArrayUtils.appendInt; 59import static com.android.internal.util.ArrayUtils.removeInt; 60 61import android.util.ArrayMap; 62 63import com.android.internal.R; 64import com.android.internal.app.IMediaContainerService; 65import com.android.internal.app.ResolverActivity; 66import com.android.internal.content.NativeLibraryHelper; 67import com.android.internal.content.PackageHelper; 68import com.android.internal.os.IParcelFileDescriptorFactory; 69import com.android.internal.util.ArrayUtils; 70import com.android.internal.util.FastPrintWriter; 71import com.android.internal.util.FastXmlSerializer; 72import com.android.internal.util.IndentingPrintWriter; 73import com.android.internal.util.Preconditions; 74import com.android.server.EventLogTags; 75import com.android.server.IntentResolver; 76import com.android.server.LocalServices; 77import com.android.server.ServiceThread; 78import com.android.server.SystemConfig; 79import com.android.server.Watchdog; 80import com.android.server.pm.Settings.DatabaseVersion; 81import com.android.server.storage.DeviceStorageMonitorInternal; 82 83import org.xmlpull.v1.XmlSerializer; 84 85import android.app.ActivityManager; 86import android.app.ActivityManagerNative; 87import android.app.IActivityManager; 88import android.app.PackageDeleteObserver; 89import android.app.admin.IDevicePolicyManager; 90import android.app.backup.IBackupManager; 91import android.content.BroadcastReceiver; 92import android.content.ComponentName; 93import android.content.Context; 94import android.content.IIntentReceiver; 95import android.content.Intent; 96import android.content.IntentFilter; 97import android.content.IntentSender; 98import android.content.IntentSender.SendIntentException; 99import android.content.ServiceConnection; 100import android.content.pm.ActivityInfo; 101import android.content.pm.ApplicationInfo; 102import android.content.pm.FeatureInfo; 103import android.content.pm.IPackageDataObserver; 104import android.content.pm.IPackageDeleteObserver; 105import android.content.pm.IPackageDeleteObserver2; 106import android.content.pm.IPackageInstallObserver2; 107import android.content.pm.IPackageInstaller; 108import android.content.pm.IPackageManager; 109import android.content.pm.IPackageMoveObserver; 110import android.content.pm.IPackageStatsObserver; 111import android.content.pm.InstallSessionParams; 112import android.content.pm.InstrumentationInfo; 113import android.content.pm.ManifestDigest; 114import android.content.pm.PackageCleanItem; 115import android.content.pm.PackageInfo; 116import android.content.pm.PackageInfoLite; 117import android.content.pm.PackageManager; 118import android.content.pm.PackageParser.ActivityIntentInfo; 119import android.content.pm.PackageParser.PackageLite; 120import android.content.pm.PackageParser.PackageParserException; 121import android.content.pm.PackageParser; 122import android.content.pm.PackageStats; 123import android.content.pm.PackageUserState; 124import android.content.pm.ParceledListSlice; 125import android.content.pm.PermissionGroupInfo; 126import android.content.pm.PermissionInfo; 127import android.content.pm.ProviderInfo; 128import android.content.pm.ResolveInfo; 129import android.content.pm.ServiceInfo; 130import android.content.pm.Signature; 131import android.content.pm.UserInfo; 132import android.content.pm.VerificationParams; 133import android.content.pm.VerifierDeviceIdentity; 134import android.content.pm.VerifierInfo; 135import android.content.res.Resources; 136import android.hardware.display.DisplayManager; 137import android.net.Uri; 138import android.os.Binder; 139import android.os.Build; 140import android.os.Bundle; 141import android.os.Environment; 142import android.os.Environment.UserEnvironment; 143import android.os.FileUtils; 144import android.os.Handler; 145import android.os.IBinder; 146import android.os.Looper; 147import android.os.Message; 148import android.os.Parcel; 149import android.os.ParcelFileDescriptor; 150import android.os.Process; 151import android.os.RemoteException; 152import android.os.SELinux; 153import android.os.ServiceManager; 154import android.os.SystemClock; 155import android.os.SystemProperties; 156import android.os.UserHandle; 157import android.os.UserManager; 158import android.security.KeyStore; 159import android.security.SystemKeyStore; 160import android.system.ErrnoException; 161import android.system.Os; 162import android.system.StructStat; 163import android.text.TextUtils; 164import android.util.ArraySet; 165import android.util.AtomicFile; 166import android.util.DisplayMetrics; 167import android.util.EventLog; 168import android.util.ExceptionUtils; 169import android.util.Log; 170import android.util.LogPrinter; 171import android.util.PrintStreamPrinter; 172import android.util.Slog; 173import android.util.SparseArray; 174import android.util.SparseBooleanArray; 175import android.view.Display; 176 177import java.io.BufferedInputStream; 178import java.io.BufferedOutputStream; 179import java.io.File; 180import java.io.FileDescriptor; 181import java.io.FileInputStream; 182import java.io.FileNotFoundException; 183import java.io.FileOutputStream; 184import java.io.FilenameFilter; 185import java.io.IOException; 186import java.io.InputStream; 187import java.io.PrintWriter; 188import java.nio.charset.StandardCharsets; 189import java.security.NoSuchAlgorithmException; 190import java.security.PublicKey; 191import java.security.cert.CertificateEncodingException; 192import java.security.cert.CertificateException; 193import java.text.SimpleDateFormat; 194import java.util.ArrayList; 195import java.util.Arrays; 196import java.util.Collection; 197import java.util.Collections; 198import java.util.Comparator; 199import java.util.Date; 200import java.util.HashMap; 201import java.util.HashSet; 202import java.util.Iterator; 203import java.util.List; 204import java.util.Map; 205import java.util.Set; 206import java.util.concurrent.atomic.AtomicBoolean; 207import java.util.concurrent.atomic.AtomicLong; 208 209import dalvik.system.DexFile; 210import dalvik.system.StaleDexCacheError; 211import dalvik.system.VMRuntime; 212 213import libcore.io.IoUtils; 214 215/** 216 * Keep track of all those .apks everywhere. 217 * 218 * This is very central to the platform's security; please run the unit 219 * tests whenever making modifications here: 220 * 221mmm frameworks/base/tests/AndroidTests 222adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 223adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 224 * 225 * {@hide} 226 */ 227public class PackageManagerService extends IPackageManager.Stub { 228 static final String TAG = "PackageManager"; 229 static final boolean DEBUG_SETTINGS = false; 230 static final boolean DEBUG_PREFERRED = false; 231 static final boolean DEBUG_UPGRADE = false; 232 private static final boolean DEBUG_INSTALL = false; 233 private static final boolean DEBUG_REMOVE = false; 234 private static final boolean DEBUG_BROADCASTS = false; 235 private static final boolean DEBUG_SHOW_INFO = false; 236 private static final boolean DEBUG_PACKAGE_INFO = false; 237 private static final boolean DEBUG_INTENT_MATCHING = false; 238 private static final boolean DEBUG_PACKAGE_SCANNING = false; 239 private static final boolean DEBUG_VERIFY = false; 240 private static final boolean DEBUG_DEXOPT = false; 241 private static final boolean DEBUG_ABI_SELECTION = false; 242 243 private static final int RADIO_UID = Process.PHONE_UID; 244 private static final int LOG_UID = Process.LOG_UID; 245 private static final int NFC_UID = Process.NFC_UID; 246 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 247 private static final int SHELL_UID = Process.SHELL_UID; 248 249 // Cap the size of permission trees that 3rd party apps can define 250 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 251 252 // Suffix used during package installation when copying/moving 253 // package apks to install directory. 254 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 255 256 static final int SCAN_MONITOR = 1<<0; 257 static final int SCAN_NO_DEX = 1<<1; 258 static final int SCAN_FORCE_DEX = 1<<2; 259 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 260 static final int SCAN_NEW_INSTALL = 1<<4; 261 static final int SCAN_NO_PATHS = 1<<5; 262 static final int SCAN_UPDATE_TIME = 1<<6; 263 static final int SCAN_DEFER_DEX = 1<<7; 264 static final int SCAN_BOOTING = 1<<8; 265 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 266 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 267 268 static final int REMOVE_CHATTY = 1<<16; 269 270 /** 271 * Timeout (in milliseconds) after which the watchdog should declare that 272 * our handler thread is wedged. The usual default for such things is one 273 * minute but we sometimes do very lengthy I/O operations on this thread, 274 * such as installing multi-gigabyte applications, so ours needs to be longer. 275 */ 276 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 277 278 /** 279 * Whether verification is enabled by default. 280 */ 281 private static final boolean DEFAULT_VERIFY_ENABLE = true; 282 283 /** 284 * The default maximum time to wait for the verification agent to return in 285 * milliseconds. 286 */ 287 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 288 289 /** 290 * The default response for package verification timeout. 291 * 292 * This can be either PackageManager.VERIFICATION_ALLOW or 293 * PackageManager.VERIFICATION_REJECT. 294 */ 295 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 296 297 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 298 299 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 300 DEFAULT_CONTAINER_PACKAGE, 301 "com.android.defcontainer.DefaultContainerService"); 302 303 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 304 305 private static final String LIB_DIR_NAME = "lib"; 306 private static final String LIB64_DIR_NAME = "lib64"; 307 308 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 309 310 static final String mTempContainerPrefix = "smdl2tmp"; 311 312 private static String sPreferredInstructionSet; 313 314 final ServiceThread mHandlerThread; 315 316 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 317 private static final String IDMAP_SUFFIX = "@idmap"; 318 319 final PackageHandler mHandler; 320 321 final int mSdkVersion = Build.VERSION.SDK_INT; 322 323 final Context mContext; 324 final boolean mFactoryTest; 325 final boolean mOnlyCore; 326 final DisplayMetrics mMetrics; 327 final int mDefParseFlags; 328 final String[] mSeparateProcesses; 329 330 // This is where all application persistent data goes. 331 final File mAppDataDir; 332 333 // This is where all application persistent data goes for secondary users. 334 final File mUserAppDataDir; 335 336 /** The location for ASEC container files on internal storage. */ 337 final String mAsecInternalPath; 338 339 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 340 // LOCK HELD. Can be called with mInstallLock held. 341 final Installer mInstaller; 342 343 /** Directory where installed third-party apps stored */ 344 final File mAppInstallDir; 345 346 /** 347 * Directory to which applications installed internally have their 348 * 32 bit native libraries copied. 349 */ 350 private File mAppLib32InstallDir; 351 352 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 353 // apps. 354 final File mDrmAppPrivateInstallDir; 355 356 // ---------------------------------------------------------------- 357 358 // Lock for state used when installing and doing other long running 359 // operations. Methods that must be called with this lock held have 360 // the suffix "LI". 361 final Object mInstallLock = new Object(); 362 363 // These are the directories in the 3rd party applications installed dir 364 // that we have currently loaded packages from. Keys are the application's 365 // installed zip file (absolute codePath), and values are Package. 366 final HashMap<String, PackageParser.Package> mAppDirs = 367 new HashMap<String, PackageParser.Package>(); 368 369 // ---------------------------------------------------------------- 370 371 // Keys are String (package name), values are Package. This also serves 372 // as the lock for the global state. Methods that must be called with 373 // this lock held have the prefix "LP". 374 final HashMap<String, PackageParser.Package> mPackages = 375 new HashMap<String, PackageParser.Package>(); 376 377 // Tracks available target package names -> overlay package paths. 378 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 379 new HashMap<String, HashMap<String, PackageParser.Package>>(); 380 381 final Settings mSettings; 382 boolean mRestoredSettings; 383 384 // System configuration read by SystemConfig. 385 final int[] mGlobalGids; 386 final SparseArray<HashSet<String>> mSystemPermissions; 387 final HashMap<String, FeatureInfo> mAvailableFeatures; 388 389 // If mac_permissions.xml was found for seinfo labeling. 390 boolean mFoundPolicyFile; 391 392 // If a recursive restorecon of /data/data/<pkg> is needed. 393 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 394 395 public static final class SharedLibraryEntry { 396 public final String path; 397 public final String apk; 398 399 SharedLibraryEntry(String _path, String _apk) { 400 path = _path; 401 apk = _apk; 402 } 403 } 404 405 // Currently known shared libraries. 406 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 407 new HashMap<String, SharedLibraryEntry>(); 408 409 // All available activities, for your resolving pleasure. 410 final ActivityIntentResolver mActivities = 411 new ActivityIntentResolver(); 412 413 // All available receivers, for your resolving pleasure. 414 final ActivityIntentResolver mReceivers = 415 new ActivityIntentResolver(); 416 417 // All available services, for your resolving pleasure. 418 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 419 420 // All available providers, for your resolving pleasure. 421 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 422 423 // Mapping from provider base names (first directory in content URI codePath) 424 // to the provider information. 425 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 426 new HashMap<String, PackageParser.Provider>(); 427 428 // Mapping from instrumentation class names to info about them. 429 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 430 new HashMap<ComponentName, PackageParser.Instrumentation>(); 431 432 // Mapping from permission names to info about them. 433 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 434 new HashMap<String, PackageParser.PermissionGroup>(); 435 436 // Packages whose data we have transfered into another package, thus 437 // should no longer exist. 438 final HashSet<String> mTransferedPackages = new HashSet<String>(); 439 440 // Broadcast actions that are only available to the system. 441 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 442 443 /** List of packages waiting for verification. */ 444 final SparseArray<PackageVerificationState> mPendingVerification 445 = new SparseArray<PackageVerificationState>(); 446 447 /** Set of packages associated with each app op permission. */ 448 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 449 450 final PackageInstallerService mInstallerService; 451 452 HashSet<PackageParser.Package> mDeferredDexOpt = null; 453 454 // Cache of users who need badging. 455 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 456 457 /** Token for keys in mPendingVerification. */ 458 private int mPendingVerificationToken = 0; 459 460 boolean mSystemReady; 461 boolean mSafeMode; 462 boolean mHasSystemUidErrors; 463 464 ApplicationInfo mAndroidApplication; 465 final ActivityInfo mResolveActivity = new ActivityInfo(); 466 final ResolveInfo mResolveInfo = new ResolveInfo(); 467 ComponentName mResolveComponentName; 468 PackageParser.Package mPlatformPackage; 469 ComponentName mCustomResolverComponentName; 470 471 boolean mResolverReplaced = false; 472 473 // Set of pending broadcasts for aggregating enable/disable of components. 474 static class PendingPackageBroadcasts { 475 // for each user id, a map of <package name -> components within that package> 476 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 477 478 public PendingPackageBroadcasts() { 479 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 480 } 481 482 public ArrayList<String> get(int userId, String packageName) { 483 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 484 return packages.get(packageName); 485 } 486 487 public void put(int userId, String packageName, ArrayList<String> components) { 488 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 489 packages.put(packageName, components); 490 } 491 492 public void remove(int userId, String packageName) { 493 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 494 if (packages != null) { 495 packages.remove(packageName); 496 } 497 } 498 499 public void remove(int userId) { 500 mUidMap.remove(userId); 501 } 502 503 public int userIdCount() { 504 return mUidMap.size(); 505 } 506 507 public int userIdAt(int n) { 508 return mUidMap.keyAt(n); 509 } 510 511 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 512 return mUidMap.get(userId); 513 } 514 515 public int size() { 516 // total number of pending broadcast entries across all userIds 517 int num = 0; 518 for (int i = 0; i< mUidMap.size(); i++) { 519 num += mUidMap.valueAt(i).size(); 520 } 521 return num; 522 } 523 524 public void clear() { 525 mUidMap.clear(); 526 } 527 528 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 529 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 530 if (map == null) { 531 map = new HashMap<String, ArrayList<String>>(); 532 mUidMap.put(userId, map); 533 } 534 return map; 535 } 536 } 537 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 538 539 // Service Connection to remote media container service to copy 540 // package uri's from external media onto secure containers 541 // or internal storage. 542 private IMediaContainerService mContainerService = null; 543 544 static final int SEND_PENDING_BROADCAST = 1; 545 static final int MCS_BOUND = 3; 546 static final int END_COPY = 4; 547 static final int INIT_COPY = 5; 548 static final int MCS_UNBIND = 6; 549 static final int START_CLEANING_PACKAGE = 7; 550 static final int FIND_INSTALL_LOC = 8; 551 static final int POST_INSTALL = 9; 552 static final int MCS_RECONNECT = 10; 553 static final int MCS_GIVE_UP = 11; 554 static final int UPDATED_MEDIA_STATUS = 12; 555 static final int WRITE_SETTINGS = 13; 556 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 557 static final int PACKAGE_VERIFIED = 15; 558 static final int CHECK_PENDING_VERIFICATION = 16; 559 560 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 561 562 // Delay time in millisecs 563 static final int BROADCAST_DELAY = 10 * 1000; 564 565 static UserManagerService sUserManager; 566 567 // Stores a list of users whose package restrictions file needs to be updated 568 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 569 570 final private DefaultContainerConnection mDefContainerConn = 571 new DefaultContainerConnection(); 572 class DefaultContainerConnection implements ServiceConnection { 573 public void onServiceConnected(ComponentName name, IBinder service) { 574 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 575 IMediaContainerService imcs = 576 IMediaContainerService.Stub.asInterface(service); 577 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 578 } 579 580 public void onServiceDisconnected(ComponentName name) { 581 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 582 } 583 }; 584 585 // Recordkeeping of restore-after-install operations that are currently in flight 586 // between the Package Manager and the Backup Manager 587 class PostInstallData { 588 public InstallArgs args; 589 public PackageInstalledInfo res; 590 591 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 592 args = _a; 593 res = _r; 594 } 595 }; 596 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 597 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 598 599 private final String mRequiredVerifierPackage; 600 601 private final PackageUsage mPackageUsage = new PackageUsage(); 602 603 private class PackageUsage { 604 private static final int WRITE_INTERVAL 605 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 606 607 private final Object mFileLock = new Object(); 608 private final AtomicLong mLastWritten = new AtomicLong(0); 609 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 610 611 private boolean mIsHistoricalPackageUsageAvailable = true; 612 613 boolean isHistoricalPackageUsageAvailable() { 614 return mIsHistoricalPackageUsageAvailable; 615 } 616 617 void write(boolean force) { 618 if (force) { 619 writeInternal(); 620 return; 621 } 622 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 623 && !DEBUG_DEXOPT) { 624 return; 625 } 626 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 627 new Thread("PackageUsage_DiskWriter") { 628 @Override 629 public void run() { 630 try { 631 writeInternal(); 632 } finally { 633 mBackgroundWriteRunning.set(false); 634 } 635 } 636 }.start(); 637 } 638 } 639 640 private void writeInternal() { 641 synchronized (mPackages) { 642 synchronized (mFileLock) { 643 AtomicFile file = getFile(); 644 FileOutputStream f = null; 645 try { 646 f = file.startWrite(); 647 BufferedOutputStream out = new BufferedOutputStream(f); 648 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 649 StringBuilder sb = new StringBuilder(); 650 for (PackageParser.Package pkg : mPackages.values()) { 651 if (pkg.mLastPackageUsageTimeInMills == 0) { 652 continue; 653 } 654 sb.setLength(0); 655 sb.append(pkg.packageName); 656 sb.append(' '); 657 sb.append((long)pkg.mLastPackageUsageTimeInMills); 658 sb.append('\n'); 659 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 660 } 661 out.flush(); 662 file.finishWrite(f); 663 } catch (IOException e) { 664 if (f != null) { 665 file.failWrite(f); 666 } 667 Log.e(TAG, "Failed to write package usage times", e); 668 } 669 } 670 } 671 mLastWritten.set(SystemClock.elapsedRealtime()); 672 } 673 674 void readLP() { 675 synchronized (mFileLock) { 676 AtomicFile file = getFile(); 677 BufferedInputStream in = null; 678 try { 679 in = new BufferedInputStream(file.openRead()); 680 StringBuffer sb = new StringBuffer(); 681 while (true) { 682 String packageName = readToken(in, sb, ' '); 683 if (packageName == null) { 684 break; 685 } 686 String timeInMillisString = readToken(in, sb, '\n'); 687 if (timeInMillisString == null) { 688 throw new IOException("Failed to find last usage time for package " 689 + packageName); 690 } 691 PackageParser.Package pkg = mPackages.get(packageName); 692 if (pkg == null) { 693 continue; 694 } 695 long timeInMillis; 696 try { 697 timeInMillis = Long.parseLong(timeInMillisString.toString()); 698 } catch (NumberFormatException e) { 699 throw new IOException("Failed to parse " + timeInMillisString 700 + " as a long.", e); 701 } 702 pkg.mLastPackageUsageTimeInMills = timeInMillis; 703 } 704 } catch (FileNotFoundException expected) { 705 mIsHistoricalPackageUsageAvailable = false; 706 } catch (IOException e) { 707 Log.w(TAG, "Failed to read package usage times", e); 708 } finally { 709 IoUtils.closeQuietly(in); 710 } 711 } 712 mLastWritten.set(SystemClock.elapsedRealtime()); 713 } 714 715 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 716 throws IOException { 717 sb.setLength(0); 718 while (true) { 719 int ch = in.read(); 720 if (ch == -1) { 721 if (sb.length() == 0) { 722 return null; 723 } 724 throw new IOException("Unexpected EOF"); 725 } 726 if (ch == endOfToken) { 727 return sb.toString(); 728 } 729 sb.append((char)ch); 730 } 731 } 732 733 private AtomicFile getFile() { 734 File dataDir = Environment.getDataDirectory(); 735 File systemDir = new File(dataDir, "system"); 736 File fname = new File(systemDir, "package-usage.list"); 737 return new AtomicFile(fname); 738 } 739 } 740 741 class PackageHandler extends Handler { 742 private boolean mBound = false; 743 final ArrayList<HandlerParams> mPendingInstalls = 744 new ArrayList<HandlerParams>(); 745 746 private boolean connectToService() { 747 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 748 " DefaultContainerService"); 749 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 750 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 751 if (mContext.bindServiceAsUser(service, mDefContainerConn, 752 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 753 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 754 mBound = true; 755 return true; 756 } 757 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 758 return false; 759 } 760 761 private void disconnectService() { 762 mContainerService = null; 763 mBound = false; 764 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 765 mContext.unbindService(mDefContainerConn); 766 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 767 } 768 769 PackageHandler(Looper looper) { 770 super(looper); 771 } 772 773 public void handleMessage(Message msg) { 774 try { 775 doHandleMessage(msg); 776 } finally { 777 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 778 } 779 } 780 781 void doHandleMessage(Message msg) { 782 switch (msg.what) { 783 case INIT_COPY: { 784 HandlerParams params = (HandlerParams) msg.obj; 785 int idx = mPendingInstalls.size(); 786 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 787 // If a bind was already initiated we dont really 788 // need to do anything. The pending install 789 // will be processed later on. 790 if (!mBound) { 791 // If this is the only one pending we might 792 // have to bind to the service again. 793 if (!connectToService()) { 794 Slog.e(TAG, "Failed to bind to media container service"); 795 params.serviceError(); 796 return; 797 } else { 798 // Once we bind to the service, the first 799 // pending request will be processed. 800 mPendingInstalls.add(idx, params); 801 } 802 } else { 803 mPendingInstalls.add(idx, params); 804 // Already bound to the service. Just make 805 // sure we trigger off processing the first request. 806 if (idx == 0) { 807 mHandler.sendEmptyMessage(MCS_BOUND); 808 } 809 } 810 break; 811 } 812 case MCS_BOUND: { 813 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 814 if (msg.obj != null) { 815 mContainerService = (IMediaContainerService) msg.obj; 816 } 817 if (mContainerService == null) { 818 // Something seriously wrong. Bail out 819 Slog.e(TAG, "Cannot bind to media container service"); 820 for (HandlerParams params : mPendingInstalls) { 821 // Indicate service bind error 822 params.serviceError(); 823 } 824 mPendingInstalls.clear(); 825 } else if (mPendingInstalls.size() > 0) { 826 HandlerParams params = mPendingInstalls.get(0); 827 if (params != null) { 828 if (params.startCopy()) { 829 // We are done... look for more work or to 830 // go idle. 831 if (DEBUG_SD_INSTALL) Log.i(TAG, 832 "Checking for more work or unbind..."); 833 // Delete pending install 834 if (mPendingInstalls.size() > 0) { 835 mPendingInstalls.remove(0); 836 } 837 if (mPendingInstalls.size() == 0) { 838 if (mBound) { 839 if (DEBUG_SD_INSTALL) Log.i(TAG, 840 "Posting delayed MCS_UNBIND"); 841 removeMessages(MCS_UNBIND); 842 Message ubmsg = obtainMessage(MCS_UNBIND); 843 // Unbind after a little delay, to avoid 844 // continual thrashing. 845 sendMessageDelayed(ubmsg, 10000); 846 } 847 } else { 848 // There are more pending requests in queue. 849 // Just post MCS_BOUND message to trigger processing 850 // of next pending install. 851 if (DEBUG_SD_INSTALL) Log.i(TAG, 852 "Posting MCS_BOUND for next work"); 853 mHandler.sendEmptyMessage(MCS_BOUND); 854 } 855 } 856 } 857 } else { 858 // Should never happen ideally. 859 Slog.w(TAG, "Empty queue"); 860 } 861 break; 862 } 863 case MCS_RECONNECT: { 864 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 865 if (mPendingInstalls.size() > 0) { 866 if (mBound) { 867 disconnectService(); 868 } 869 if (!connectToService()) { 870 Slog.e(TAG, "Failed to bind to media container service"); 871 for (HandlerParams params : mPendingInstalls) { 872 // Indicate service bind error 873 params.serviceError(); 874 } 875 mPendingInstalls.clear(); 876 } 877 } 878 break; 879 } 880 case MCS_UNBIND: { 881 // If there is no actual work left, then time to unbind. 882 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 883 884 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 885 if (mBound) { 886 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 887 888 disconnectService(); 889 } 890 } else if (mPendingInstalls.size() > 0) { 891 // There are more pending requests in queue. 892 // Just post MCS_BOUND message to trigger processing 893 // of next pending install. 894 mHandler.sendEmptyMessage(MCS_BOUND); 895 } 896 897 break; 898 } 899 case MCS_GIVE_UP: { 900 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 901 mPendingInstalls.remove(0); 902 break; 903 } 904 case SEND_PENDING_BROADCAST: { 905 String packages[]; 906 ArrayList<String> components[]; 907 int size = 0; 908 int uids[]; 909 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 910 synchronized (mPackages) { 911 if (mPendingBroadcasts == null) { 912 return; 913 } 914 size = mPendingBroadcasts.size(); 915 if (size <= 0) { 916 // Nothing to be done. Just return 917 return; 918 } 919 packages = new String[size]; 920 components = new ArrayList[size]; 921 uids = new int[size]; 922 int i = 0; // filling out the above arrays 923 924 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 925 int packageUserId = mPendingBroadcasts.userIdAt(n); 926 Iterator<Map.Entry<String, ArrayList<String>>> it 927 = mPendingBroadcasts.packagesForUserId(packageUserId) 928 .entrySet().iterator(); 929 while (it.hasNext() && i < size) { 930 Map.Entry<String, ArrayList<String>> ent = it.next(); 931 packages[i] = ent.getKey(); 932 components[i] = ent.getValue(); 933 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 934 uids[i] = (ps != null) 935 ? UserHandle.getUid(packageUserId, ps.appId) 936 : -1; 937 i++; 938 } 939 } 940 size = i; 941 mPendingBroadcasts.clear(); 942 } 943 // Send broadcasts 944 for (int i = 0; i < size; i++) { 945 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 946 } 947 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 948 break; 949 } 950 case START_CLEANING_PACKAGE: { 951 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 952 final String packageName = (String)msg.obj; 953 final int userId = msg.arg1; 954 final boolean andCode = msg.arg2 != 0; 955 synchronized (mPackages) { 956 if (userId == UserHandle.USER_ALL) { 957 int[] users = sUserManager.getUserIds(); 958 for (int user : users) { 959 mSettings.addPackageToCleanLPw( 960 new PackageCleanItem(user, packageName, andCode)); 961 } 962 } else { 963 mSettings.addPackageToCleanLPw( 964 new PackageCleanItem(userId, packageName, andCode)); 965 } 966 } 967 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 968 startCleaningPackages(); 969 } break; 970 case POST_INSTALL: { 971 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 972 PostInstallData data = mRunningInstalls.get(msg.arg1); 973 mRunningInstalls.delete(msg.arg1); 974 boolean deleteOld = false; 975 976 if (data != null) { 977 InstallArgs args = data.args; 978 PackageInstalledInfo res = data.res; 979 980 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 981 res.removedInfo.sendBroadcast(false, true, false); 982 Bundle extras = new Bundle(1); 983 extras.putInt(Intent.EXTRA_UID, res.uid); 984 // Determine the set of users who are adding this 985 // package for the first time vs. those who are seeing 986 // an update. 987 int[] firstUsers; 988 int[] updateUsers = new int[0]; 989 if (res.origUsers == null || res.origUsers.length == 0) { 990 firstUsers = res.newUsers; 991 } else { 992 firstUsers = new int[0]; 993 for (int i=0; i<res.newUsers.length; i++) { 994 int user = res.newUsers[i]; 995 boolean isNew = true; 996 for (int j=0; j<res.origUsers.length; j++) { 997 if (res.origUsers[j] == user) { 998 isNew = false; 999 break; 1000 } 1001 } 1002 if (isNew) { 1003 int[] newFirst = new int[firstUsers.length+1]; 1004 System.arraycopy(firstUsers, 0, newFirst, 0, 1005 firstUsers.length); 1006 newFirst[firstUsers.length] = user; 1007 firstUsers = newFirst; 1008 } else { 1009 int[] newUpdate = new int[updateUsers.length+1]; 1010 System.arraycopy(updateUsers, 0, newUpdate, 0, 1011 updateUsers.length); 1012 newUpdate[updateUsers.length] = user; 1013 updateUsers = newUpdate; 1014 } 1015 } 1016 } 1017 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1018 res.pkg.applicationInfo.packageName, 1019 extras, null, null, firstUsers); 1020 final boolean update = res.removedInfo.removedPackage != null; 1021 if (update) { 1022 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1023 } 1024 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1025 res.pkg.applicationInfo.packageName, 1026 extras, null, null, updateUsers); 1027 if (update) { 1028 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1029 res.pkg.applicationInfo.packageName, 1030 extras, null, null, updateUsers); 1031 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1032 null, null, 1033 res.pkg.applicationInfo.packageName, null, updateUsers); 1034 1035 // treat asec-hosted packages like removable media on upgrade 1036 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1037 if (DEBUG_INSTALL) { 1038 Slog.i(TAG, "upgrading pkg " + res.pkg 1039 + " is ASEC-hosted -> AVAILABLE"); 1040 } 1041 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1042 ArrayList<String> pkgList = new ArrayList<String>(1); 1043 pkgList.add(res.pkg.applicationInfo.packageName); 1044 sendResourcesChangedBroadcast(true, true, 1045 pkgList,uidArray, null); 1046 } 1047 } 1048 if (res.removedInfo.args != null) { 1049 // Remove the replaced package's older resources safely now 1050 deleteOld = true; 1051 } 1052 1053 // Log current value of "unknown sources" setting 1054 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1055 getUnknownSourcesSettings()); 1056 } 1057 // Force a gc to clear up things 1058 Runtime.getRuntime().gc(); 1059 // We delete after a gc for applications on sdcard. 1060 if (deleteOld) { 1061 synchronized (mInstallLock) { 1062 res.removedInfo.args.doPostDeleteLI(true); 1063 } 1064 } 1065 if (args.observer != null) { 1066 try { 1067 Bundle extras = extrasForInstallResult(res); 1068 args.observer.onPackageInstalled(res.name, res.returnCode, 1069 res.returnMsg, extras); 1070 } catch (RemoteException e) { 1071 Slog.i(TAG, "Observer no longer exists."); 1072 } 1073 } 1074 } else { 1075 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1076 } 1077 } break; 1078 case UPDATED_MEDIA_STATUS: { 1079 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1080 boolean reportStatus = msg.arg1 == 1; 1081 boolean doGc = msg.arg2 == 1; 1082 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1083 if (doGc) { 1084 // Force a gc to clear up stale containers. 1085 Runtime.getRuntime().gc(); 1086 } 1087 if (msg.obj != null) { 1088 @SuppressWarnings("unchecked") 1089 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1090 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1091 // Unload containers 1092 unloadAllContainers(args); 1093 } 1094 if (reportStatus) { 1095 try { 1096 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1097 PackageHelper.getMountService().finishMediaUpdate(); 1098 } catch (RemoteException e) { 1099 Log.e(TAG, "MountService not running?"); 1100 } 1101 } 1102 } break; 1103 case WRITE_SETTINGS: { 1104 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1105 synchronized (mPackages) { 1106 removeMessages(WRITE_SETTINGS); 1107 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1108 mSettings.writeLPr(); 1109 mDirtyUsers.clear(); 1110 } 1111 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1112 } break; 1113 case WRITE_PACKAGE_RESTRICTIONS: { 1114 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1115 synchronized (mPackages) { 1116 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1117 for (int userId : mDirtyUsers) { 1118 mSettings.writePackageRestrictionsLPr(userId); 1119 } 1120 mDirtyUsers.clear(); 1121 } 1122 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1123 } break; 1124 case CHECK_PENDING_VERIFICATION: { 1125 final int verificationId = msg.arg1; 1126 final PackageVerificationState state = mPendingVerification.get(verificationId); 1127 1128 if ((state != null) && !state.timeoutExtended()) { 1129 final InstallArgs args = state.getInstallArgs(); 1130 final Uri originUri = Uri.fromFile(args.originFile); 1131 1132 Slog.i(TAG, "Verification timed out for " + originUri); 1133 mPendingVerification.remove(verificationId); 1134 1135 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1136 1137 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1138 Slog.i(TAG, "Continuing with installation of " + originUri); 1139 state.setVerifierResponse(Binder.getCallingUid(), 1140 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1141 broadcastPackageVerified(verificationId, originUri, 1142 PackageManager.VERIFICATION_ALLOW, 1143 state.getInstallArgs().getUser()); 1144 try { 1145 ret = args.copyApk(mContainerService, true); 1146 } catch (RemoteException e) { 1147 Slog.e(TAG, "Could not contact the ContainerService"); 1148 } 1149 } else { 1150 broadcastPackageVerified(verificationId, originUri, 1151 PackageManager.VERIFICATION_REJECT, 1152 state.getInstallArgs().getUser()); 1153 } 1154 1155 processPendingInstall(args, ret); 1156 mHandler.sendEmptyMessage(MCS_UNBIND); 1157 } 1158 break; 1159 } 1160 case PACKAGE_VERIFIED: { 1161 final int verificationId = msg.arg1; 1162 1163 final PackageVerificationState state = mPendingVerification.get(verificationId); 1164 if (state == null) { 1165 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1166 break; 1167 } 1168 1169 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1170 1171 state.setVerifierResponse(response.callerUid, response.code); 1172 1173 if (state.isVerificationComplete()) { 1174 mPendingVerification.remove(verificationId); 1175 1176 final InstallArgs args = state.getInstallArgs(); 1177 final Uri originUri = Uri.fromFile(args.originFile); 1178 1179 int ret; 1180 if (state.isInstallAllowed()) { 1181 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1182 broadcastPackageVerified(verificationId, originUri, 1183 response.code, state.getInstallArgs().getUser()); 1184 try { 1185 ret = args.copyApk(mContainerService, true); 1186 } catch (RemoteException e) { 1187 Slog.e(TAG, "Could not contact the ContainerService"); 1188 } 1189 } else { 1190 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1191 } 1192 1193 processPendingInstall(args, ret); 1194 1195 mHandler.sendEmptyMessage(MCS_UNBIND); 1196 } 1197 1198 break; 1199 } 1200 } 1201 } 1202 } 1203 1204 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1205 Bundle extras = null; 1206 switch (res.returnCode) { 1207 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1208 extras = new Bundle(); 1209 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1210 res.origPermission); 1211 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1212 res.origPackage); 1213 break; 1214 } 1215 } 1216 return extras; 1217 } 1218 1219 void scheduleWriteSettingsLocked() { 1220 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1221 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1222 } 1223 } 1224 1225 void scheduleWritePackageRestrictionsLocked(int userId) { 1226 if (!sUserManager.exists(userId)) return; 1227 mDirtyUsers.add(userId); 1228 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1229 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1230 } 1231 } 1232 1233 public static final PackageManagerService main(Context context, Installer installer, 1234 boolean factoryTest, boolean onlyCore) { 1235 PackageManagerService m = new PackageManagerService(context, installer, 1236 factoryTest, onlyCore); 1237 ServiceManager.addService("package", m); 1238 return m; 1239 } 1240 1241 static String[] splitString(String str, char sep) { 1242 int count = 1; 1243 int i = 0; 1244 while ((i=str.indexOf(sep, i)) >= 0) { 1245 count++; 1246 i++; 1247 } 1248 1249 String[] res = new String[count]; 1250 i=0; 1251 count = 0; 1252 int lastI=0; 1253 while ((i=str.indexOf(sep, i)) >= 0) { 1254 res[count] = str.substring(lastI, i); 1255 count++; 1256 i++; 1257 lastI = i; 1258 } 1259 res[count] = str.substring(lastI, str.length()); 1260 return res; 1261 } 1262 1263 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1264 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1265 Context.DISPLAY_SERVICE); 1266 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1267 } 1268 1269 public PackageManagerService(Context context, Installer installer, 1270 boolean factoryTest, boolean onlyCore) { 1271 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1272 SystemClock.uptimeMillis()); 1273 1274 if (mSdkVersion <= 0) { 1275 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1276 } 1277 1278 mContext = context; 1279 mFactoryTest = factoryTest; 1280 mOnlyCore = onlyCore; 1281 mMetrics = new DisplayMetrics(); 1282 mSettings = new Settings(context); 1283 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1284 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1285 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1286 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1287 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1288 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1289 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1290 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1291 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1292 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1293 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1294 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1295 1296 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1297 if (separateProcesses != null && separateProcesses.length() > 0) { 1298 if ("*".equals(separateProcesses)) { 1299 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1300 mSeparateProcesses = null; 1301 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1302 } else { 1303 mDefParseFlags = 0; 1304 mSeparateProcesses = separateProcesses.split(","); 1305 Slog.w(TAG, "Running with debug.separate_processes: " 1306 + separateProcesses); 1307 } 1308 } else { 1309 mDefParseFlags = 0; 1310 mSeparateProcesses = null; 1311 } 1312 1313 mInstaller = installer; 1314 1315 getDefaultDisplayMetrics(context, mMetrics); 1316 1317 SystemConfig systemConfig = SystemConfig.getInstance(); 1318 mGlobalGids = systemConfig.getGlobalGids(); 1319 mSystemPermissions = systemConfig.getSystemPermissions(); 1320 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1321 1322 synchronized (mInstallLock) { 1323 // writer 1324 synchronized (mPackages) { 1325 mHandlerThread = new ServiceThread(TAG, 1326 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1327 mHandlerThread.start(); 1328 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1329 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1330 1331 File dataDir = Environment.getDataDirectory(); 1332 mAppDataDir = new File(dataDir, "data"); 1333 mAppInstallDir = new File(dataDir, "app"); 1334 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1335 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1336 mUserAppDataDir = new File(dataDir, "user"); 1337 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1338 1339 sUserManager = new UserManagerService(context, this, 1340 mInstallLock, mPackages); 1341 1342 // Propagate permission configuration in to package manager. 1343 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1344 = systemConfig.getPermissions(); 1345 for (int i=0; i<permConfig.size(); i++) { 1346 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1347 BasePermission bp = mSettings.mPermissions.get(perm.name); 1348 if (bp == null) { 1349 bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN); 1350 mSettings.mPermissions.put(perm.name, bp); 1351 } 1352 if (perm.gids != null) { 1353 bp.gids = appendInts(bp.gids, perm.gids); 1354 } 1355 } 1356 1357 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1358 for (int i=0; i<libConfig.size(); i++) { 1359 mSharedLibraries.put(libConfig.keyAt(i), 1360 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1361 } 1362 1363 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1364 1365 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1366 mSdkVersion, mOnlyCore); 1367 1368 String customResolverActivity = Resources.getSystem().getString( 1369 R.string.config_customResolverActivity); 1370 if (TextUtils.isEmpty(customResolverActivity)) { 1371 customResolverActivity = null; 1372 } else { 1373 mCustomResolverComponentName = ComponentName.unflattenFromString( 1374 customResolverActivity); 1375 } 1376 1377 long startTime = SystemClock.uptimeMillis(); 1378 1379 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1380 startTime); 1381 1382 // Set flag to monitor and not change apk file paths when 1383 // scanning install directories. 1384 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1385 1386 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1387 1388 /** 1389 * Add everything in the in the boot class path to the 1390 * list of process files because dexopt will have been run 1391 * if necessary during zygote startup. 1392 */ 1393 String bootClassPath = System.getProperty("java.boot.class.path"); 1394 if (bootClassPath != null) { 1395 String[] paths = splitString(bootClassPath, ':'); 1396 for (int i=0; i<paths.length; i++) { 1397 alreadyDexOpted.add(paths[i]); 1398 } 1399 } else { 1400 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1401 } 1402 1403 boolean didDexOptLibraryOrTool = false; 1404 1405 final List<String> instructionSets = getAllInstructionSets(); 1406 1407 /** 1408 * Ensure all external libraries have had dexopt run on them. 1409 */ 1410 if (mSharedLibraries.size() > 0) { 1411 // NOTE: For now, we're compiling these system "shared libraries" 1412 // (and framework jars) into all available architectures. It's possible 1413 // to compile them only when we come across an app that uses them (there's 1414 // already logic for that in scanPackageLI) but that adds some complexity. 1415 for (String instructionSet : instructionSets) { 1416 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1417 final String lib = libEntry.path; 1418 if (lib == null) { 1419 continue; 1420 } 1421 1422 try { 1423 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1424 instructionSet, 1425 false); 1426 if (dexoptRequired != DexFile.UP_TO_DATE) { 1427 alreadyDexOpted.add(lib); 1428 1429 // The list of "shared libraries" we have at this point is 1430 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1431 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet); 1432 } else { 1433 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, instructionSet); 1434 } 1435 didDexOptLibraryOrTool = true; 1436 } 1437 } catch (FileNotFoundException e) { 1438 Slog.w(TAG, "Library not found: " + lib); 1439 } catch (IOException e) { 1440 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1441 + e.getMessage()); 1442 } 1443 } 1444 } 1445 } 1446 1447 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1448 1449 // Gross hack for now: we know this file doesn't contain any 1450 // code, so don't dexopt it to avoid the resulting log spew. 1451 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1452 1453 // Gross hack for now: we know this file is only part of 1454 // the boot class path for art, so don't dexopt it to 1455 // avoid the resulting log spew. 1456 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1457 1458 /** 1459 * And there are a number of commands implemented in Java, which 1460 * we currently need to do the dexopt on so that they can be 1461 * run from a non-root shell. 1462 */ 1463 String[] frameworkFiles = frameworkDir.list(); 1464 if (frameworkFiles != null) { 1465 // TODO: We could compile these only for the most preferred ABI. We should 1466 // first double check that the dex files for these commands are not referenced 1467 // by other system apps. 1468 for (String instructionSet : instructionSets) { 1469 for (int i=0; i<frameworkFiles.length; i++) { 1470 File libPath = new File(frameworkDir, frameworkFiles[i]); 1471 String path = libPath.getPath(); 1472 // Skip the file if we already did it. 1473 if (alreadyDexOpted.contains(path)) { 1474 continue; 1475 } 1476 // Skip the file if it is not a type we want to dexopt. 1477 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1478 continue; 1479 } 1480 try { 1481 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1482 instructionSet, 1483 false); 1484 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1485 mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet); 1486 didDexOptLibraryOrTool = true; 1487 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1488 mInstaller.patchoat(path, Process.SYSTEM_UID, true, instructionSet); 1489 didDexOptLibraryOrTool = true; 1490 } 1491 } catch (FileNotFoundException e) { 1492 Slog.w(TAG, "Jar not found: " + path); 1493 } catch (IOException e) { 1494 Slog.w(TAG, "Exception reading jar: " + path, e); 1495 } 1496 } 1497 } 1498 } 1499 1500 if (didDexOptLibraryOrTool) { 1501 // If we dexopted a library or tool, then something on the system has 1502 // changed. Consider this significant, and wipe away all other 1503 // existing dexopt files to ensure we don't leave any dangling around. 1504 // 1505 // TODO: This should be revisited because it isn't as good an indicator 1506 // as it used to be. It used to include the boot classpath but at some point 1507 // DexFile.isDexOptNeeded started returning false for the boot 1508 // class path files in all cases. It is very possible in a 1509 // small maintenance release update that the library and tool 1510 // jars may be unchanged but APK could be removed resulting in 1511 // unused dalvik-cache files. 1512 for (String instructionSet : instructionSets) { 1513 mInstaller.pruneDexCache(instructionSet); 1514 } 1515 1516 // Additionally, delete all dex files from the root directory 1517 // since there shouldn't be any there anyway, unless we're upgrading 1518 // from an older OS version or a build that contained the "old" style 1519 // flat scheme. 1520 mInstaller.pruneDexCache("."); 1521 } 1522 1523 // Collect vendor overlay packages. 1524 // (Do this before scanning any apps.) 1525 // For security and version matching reason, only consider 1526 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1527 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1528 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1529 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1530 1531 // Find base frameworks (resource packages without code). 1532 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1533 | PackageParser.PARSE_IS_SYSTEM_DIR 1534 | PackageParser.PARSE_IS_PRIVILEGED, 1535 scanMode | SCAN_NO_DEX, 0); 1536 1537 // Collected privileged system packages. 1538 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1539 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1540 | PackageParser.PARSE_IS_SYSTEM_DIR 1541 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1542 1543 // Collect ordinary system packages. 1544 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1545 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1546 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1547 1548 // Collect all vendor packages. 1549 File vendorAppDir = new File("/vendor/app"); 1550 try { 1551 vendorAppDir = vendorAppDir.getCanonicalFile(); 1552 } catch (IOException e) { 1553 // failed to look up canonical path, continue with original one 1554 } 1555 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1556 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1557 1558 // Collect all OEM packages. 1559 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1560 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1561 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1562 1563 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1564 mInstaller.moveFiles(); 1565 1566 // Prune any system packages that no longer exist. 1567 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1568 if (!mOnlyCore) { 1569 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1570 while (psit.hasNext()) { 1571 PackageSetting ps = psit.next(); 1572 1573 /* 1574 * If this is not a system app, it can't be a 1575 * disable system app. 1576 */ 1577 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1578 continue; 1579 } 1580 1581 /* 1582 * If the package is scanned, it's not erased. 1583 */ 1584 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1585 if (scannedPkg != null) { 1586 /* 1587 * If the system app is both scanned and in the 1588 * disabled packages list, then it must have been 1589 * added via OTA. Remove it from the currently 1590 * scanned package so the previously user-installed 1591 * application can be scanned. 1592 */ 1593 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1594 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1595 + "; removing system app"); 1596 removePackageLI(ps, true); 1597 } 1598 1599 continue; 1600 } 1601 1602 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1603 psit.remove(); 1604 String msg = "System package " + ps.name 1605 + " no longer exists; wiping its data"; 1606 reportSettingsProblem(Log.WARN, msg); 1607 removeDataDirsLI(ps.name); 1608 } else { 1609 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1610 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1611 possiblyDeletedUpdatedSystemApps.add(ps.name); 1612 } 1613 } 1614 } 1615 } 1616 1617 //look for any incomplete package installations 1618 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1619 //clean up list 1620 for(int i = 0; i < deletePkgsList.size(); i++) { 1621 //clean up here 1622 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1623 } 1624 //delete tmp files 1625 deleteTempPackageFiles(); 1626 1627 // Remove any shared userIDs that have no associated packages 1628 mSettings.pruneSharedUsersLPw(); 1629 1630 if (!mOnlyCore) { 1631 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1632 SystemClock.uptimeMillis()); 1633 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1634 1635 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1636 scanMode, 0); 1637 1638 /** 1639 * Remove disable package settings for any updated system 1640 * apps that were removed via an OTA. If they're not a 1641 * previously-updated app, remove them completely. 1642 * Otherwise, just revoke their system-level permissions. 1643 */ 1644 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1645 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1646 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1647 1648 String msg; 1649 if (deletedPkg == null) { 1650 msg = "Updated system package " + deletedAppName 1651 + " no longer exists; wiping its data"; 1652 removeDataDirsLI(deletedAppName); 1653 } else { 1654 msg = "Updated system app + " + deletedAppName 1655 + " no longer present; removing system privileges for " 1656 + deletedAppName; 1657 1658 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1659 1660 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1661 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1662 } 1663 reportSettingsProblem(Log.WARN, msg); 1664 } 1665 } 1666 1667 // Now that we know all of the shared libraries, update all clients to have 1668 // the correct library paths. 1669 updateAllSharedLibrariesLPw(); 1670 1671 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1672 // NOTE: We ignore potential failures here during a system scan (like 1673 // the rest of the commands above) because there's precious little we 1674 // can do about it. A settings error is reported, though. 1675 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1676 false /* force dexopt */, false /* defer dexopt */); 1677 } 1678 1679 // Now that we know all the packages we are keeping, 1680 // read and update their last usage times. 1681 mPackageUsage.readLP(); 1682 1683 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1684 SystemClock.uptimeMillis()); 1685 Slog.i(TAG, "Time to scan packages: " 1686 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1687 + " seconds"); 1688 1689 // If the platform SDK has changed since the last time we booted, 1690 // we need to re-grant app permission to catch any new ones that 1691 // appear. This is really a hack, and means that apps can in some 1692 // cases get permissions that the user didn't initially explicitly 1693 // allow... it would be nice to have some better way to handle 1694 // this situation. 1695 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1696 != mSdkVersion; 1697 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1698 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1699 + "; regranting permissions for internal storage"); 1700 mSettings.mInternalSdkPlatform = mSdkVersion; 1701 1702 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1703 | (regrantPermissions 1704 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1705 : 0)); 1706 1707 // If this is the first boot, and it is a normal boot, then 1708 // we need to initialize the default preferred apps. 1709 if (!mRestoredSettings && !onlyCore) { 1710 mSettings.readDefaultPreferredAppsLPw(this, 0); 1711 } 1712 1713 // If this is first boot after an OTA, and a normal boot, then 1714 // we need to clear code cache directories. 1715 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1716 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1717 for (String pkgName : mSettings.mPackages.keySet()) { 1718 deleteCodeCacheDirsLI(pkgName); 1719 } 1720 mSettings.mFingerprint = Build.FINGERPRINT; 1721 } 1722 1723 // All the changes are done during package scanning. 1724 mSettings.updateInternalDatabaseVersion(); 1725 1726 // can downgrade to reader 1727 mSettings.writeLPr(); 1728 1729 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1730 SystemClock.uptimeMillis()); 1731 1732 1733 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1734 } // synchronized (mPackages) 1735 } // synchronized (mInstallLock) 1736 1737 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1738 1739 // Now after opening every single application zip, make sure they 1740 // are all flushed. Not really needed, but keeps things nice and 1741 // tidy. 1742 Runtime.getRuntime().gc(); 1743 } 1744 1745 @Override 1746 public boolean isFirstBoot() { 1747 return !mRestoredSettings; 1748 } 1749 1750 @Override 1751 public boolean isOnlyCoreApps() { 1752 return mOnlyCore; 1753 } 1754 1755 private String getRequiredVerifierLPr() { 1756 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1757 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1758 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1759 1760 String requiredVerifier = null; 1761 1762 final int N = receivers.size(); 1763 for (int i = 0; i < N; i++) { 1764 final ResolveInfo info = receivers.get(i); 1765 1766 if (info.activityInfo == null) { 1767 continue; 1768 } 1769 1770 final String packageName = info.activityInfo.packageName; 1771 1772 final PackageSetting ps = mSettings.mPackages.get(packageName); 1773 if (ps == null) { 1774 continue; 1775 } 1776 1777 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1778 if (!gp.grantedPermissions 1779 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1780 continue; 1781 } 1782 1783 if (requiredVerifier != null) { 1784 throw new RuntimeException("There can be only one required verifier"); 1785 } 1786 1787 requiredVerifier = packageName; 1788 } 1789 1790 return requiredVerifier; 1791 } 1792 1793 @Override 1794 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1795 throws RemoteException { 1796 try { 1797 return super.onTransact(code, data, reply, flags); 1798 } catch (RuntimeException e) { 1799 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1800 Slog.wtf(TAG, "Package Manager Crash", e); 1801 } 1802 throw e; 1803 } 1804 } 1805 1806 void cleanupInstallFailedPackage(PackageSetting ps) { 1807 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1808 removeDataDirsLI(ps.name); 1809 1810 // TODO: try cleaning up codePath directory contents first, since it 1811 // might be a cluster 1812 1813 if (ps.codePath != null) { 1814 if (!ps.codePath.delete()) { 1815 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1816 } 1817 } 1818 if (ps.resourcePath != null) { 1819 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1820 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1821 } 1822 } 1823 mSettings.removePackageLPw(ps.name); 1824 } 1825 1826 static int[] appendInts(int[] cur, int[] add) { 1827 if (add == null) return cur; 1828 if (cur == null) return add; 1829 final int N = add.length; 1830 for (int i=0; i<N; i++) { 1831 cur = appendInt(cur, add[i]); 1832 } 1833 return cur; 1834 } 1835 1836 static int[] removeInts(int[] cur, int[] rem) { 1837 if (rem == null) return cur; 1838 if (cur == null) return cur; 1839 final int N = rem.length; 1840 for (int i=0; i<N; i++) { 1841 cur = removeInt(cur, rem[i]); 1842 } 1843 return cur; 1844 } 1845 1846 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1847 if (!sUserManager.exists(userId)) return null; 1848 final PackageSetting ps = (PackageSetting) p.mExtras; 1849 if (ps == null) { 1850 return null; 1851 } 1852 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1853 final PackageUserState state = ps.readUserState(userId); 1854 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1855 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1856 state, userId); 1857 } 1858 1859 @Override 1860 public boolean isPackageAvailable(String packageName, int userId) { 1861 if (!sUserManager.exists(userId)) return false; 1862 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1863 synchronized (mPackages) { 1864 PackageParser.Package p = mPackages.get(packageName); 1865 if (p != null) { 1866 final PackageSetting ps = (PackageSetting) p.mExtras; 1867 if (ps != null) { 1868 final PackageUserState state = ps.readUserState(userId); 1869 if (state != null) { 1870 return PackageParser.isAvailable(state); 1871 } 1872 } 1873 } 1874 } 1875 return false; 1876 } 1877 1878 @Override 1879 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1880 if (!sUserManager.exists(userId)) return null; 1881 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1882 // reader 1883 synchronized (mPackages) { 1884 PackageParser.Package p = mPackages.get(packageName); 1885 if (DEBUG_PACKAGE_INFO) 1886 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1887 if (p != null) { 1888 return generatePackageInfo(p, flags, userId); 1889 } 1890 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1891 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1892 } 1893 } 1894 return null; 1895 } 1896 1897 @Override 1898 public String[] currentToCanonicalPackageNames(String[] names) { 1899 String[] out = new String[names.length]; 1900 // reader 1901 synchronized (mPackages) { 1902 for (int i=names.length-1; i>=0; i--) { 1903 PackageSetting ps = mSettings.mPackages.get(names[i]); 1904 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1905 } 1906 } 1907 return out; 1908 } 1909 1910 @Override 1911 public String[] canonicalToCurrentPackageNames(String[] names) { 1912 String[] out = new String[names.length]; 1913 // reader 1914 synchronized (mPackages) { 1915 for (int i=names.length-1; i>=0; i--) { 1916 String cur = mSettings.mRenamedPackages.get(names[i]); 1917 out[i] = cur != null ? cur : names[i]; 1918 } 1919 } 1920 return out; 1921 } 1922 1923 @Override 1924 public int getPackageUid(String packageName, int userId) { 1925 if (!sUserManager.exists(userId)) return -1; 1926 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1927 // reader 1928 synchronized (mPackages) { 1929 PackageParser.Package p = mPackages.get(packageName); 1930 if(p != null) { 1931 return UserHandle.getUid(userId, p.applicationInfo.uid); 1932 } 1933 PackageSetting ps = mSettings.mPackages.get(packageName); 1934 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1935 return -1; 1936 } 1937 p = ps.pkg; 1938 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1939 } 1940 } 1941 1942 @Override 1943 public int[] getPackageGids(String packageName) { 1944 // reader 1945 synchronized (mPackages) { 1946 PackageParser.Package p = mPackages.get(packageName); 1947 if (DEBUG_PACKAGE_INFO) 1948 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1949 if (p != null) { 1950 final PackageSetting ps = (PackageSetting)p.mExtras; 1951 return ps.getGids(); 1952 } 1953 } 1954 // stupid thing to indicate an error. 1955 return new int[0]; 1956 } 1957 1958 static final PermissionInfo generatePermissionInfo( 1959 BasePermission bp, int flags) { 1960 if (bp.perm != null) { 1961 return PackageParser.generatePermissionInfo(bp.perm, flags); 1962 } 1963 PermissionInfo pi = new PermissionInfo(); 1964 pi.name = bp.name; 1965 pi.packageName = bp.sourcePackage; 1966 pi.nonLocalizedLabel = bp.name; 1967 pi.protectionLevel = bp.protectionLevel; 1968 return pi; 1969 } 1970 1971 @Override 1972 public PermissionInfo getPermissionInfo(String name, int flags) { 1973 // reader 1974 synchronized (mPackages) { 1975 final BasePermission p = mSettings.mPermissions.get(name); 1976 if (p != null) { 1977 return generatePermissionInfo(p, flags); 1978 } 1979 return null; 1980 } 1981 } 1982 1983 @Override 1984 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 1985 // reader 1986 synchronized (mPackages) { 1987 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 1988 for (BasePermission p : mSettings.mPermissions.values()) { 1989 if (group == null) { 1990 if (p.perm == null || p.perm.info.group == null) { 1991 out.add(generatePermissionInfo(p, flags)); 1992 } 1993 } else { 1994 if (p.perm != null && group.equals(p.perm.info.group)) { 1995 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 1996 } 1997 } 1998 } 1999 2000 if (out.size() > 0) { 2001 return out; 2002 } 2003 return mPermissionGroups.containsKey(group) ? out : null; 2004 } 2005 } 2006 2007 @Override 2008 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2009 // reader 2010 synchronized (mPackages) { 2011 return PackageParser.generatePermissionGroupInfo( 2012 mPermissionGroups.get(name), flags); 2013 } 2014 } 2015 2016 @Override 2017 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2018 // reader 2019 synchronized (mPackages) { 2020 final int N = mPermissionGroups.size(); 2021 ArrayList<PermissionGroupInfo> out 2022 = new ArrayList<PermissionGroupInfo>(N); 2023 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2024 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2025 } 2026 return out; 2027 } 2028 } 2029 2030 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2031 int userId) { 2032 if (!sUserManager.exists(userId)) return null; 2033 PackageSetting ps = mSettings.mPackages.get(packageName); 2034 if (ps != null) { 2035 if (ps.pkg == null) { 2036 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2037 flags, userId); 2038 if (pInfo != null) { 2039 return pInfo.applicationInfo; 2040 } 2041 return null; 2042 } 2043 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2044 ps.readUserState(userId), userId); 2045 } 2046 return null; 2047 } 2048 2049 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2050 int userId) { 2051 if (!sUserManager.exists(userId)) return null; 2052 PackageSetting ps = mSettings.mPackages.get(packageName); 2053 if (ps != null) { 2054 PackageParser.Package pkg = ps.pkg; 2055 if (pkg == null) { 2056 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2057 return null; 2058 } 2059 // Only data remains, so we aren't worried about code paths 2060 pkg = new PackageParser.Package(packageName); 2061 pkg.applicationInfo.packageName = packageName; 2062 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2063 pkg.applicationInfo.dataDir = 2064 getDataPathForPackage(packageName, 0).getPath(); 2065 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2066 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2067 } 2068 return generatePackageInfo(pkg, flags, userId); 2069 } 2070 return null; 2071 } 2072 2073 @Override 2074 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2075 if (!sUserManager.exists(userId)) return null; 2076 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2077 // writer 2078 synchronized (mPackages) { 2079 PackageParser.Package p = mPackages.get(packageName); 2080 if (DEBUG_PACKAGE_INFO) Log.v( 2081 TAG, "getApplicationInfo " + packageName 2082 + ": " + p); 2083 if (p != null) { 2084 PackageSetting ps = mSettings.mPackages.get(packageName); 2085 if (ps == null) return null; 2086 // Note: isEnabledLP() does not apply here - always return info 2087 return PackageParser.generateApplicationInfo( 2088 p, flags, ps.readUserState(userId), userId); 2089 } 2090 if ("android".equals(packageName)||"system".equals(packageName)) { 2091 return mAndroidApplication; 2092 } 2093 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2094 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2095 } 2096 } 2097 return null; 2098 } 2099 2100 2101 @Override 2102 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2103 mContext.enforceCallingOrSelfPermission( 2104 android.Manifest.permission.CLEAR_APP_CACHE, null); 2105 // Queue up an async operation since clearing cache may take a little while. 2106 mHandler.post(new Runnable() { 2107 public void run() { 2108 mHandler.removeCallbacks(this); 2109 int retCode = -1; 2110 synchronized (mInstallLock) { 2111 retCode = mInstaller.freeCache(freeStorageSize); 2112 if (retCode < 0) { 2113 Slog.w(TAG, "Couldn't clear application caches"); 2114 } 2115 } 2116 if (observer != null) { 2117 try { 2118 observer.onRemoveCompleted(null, (retCode >= 0)); 2119 } catch (RemoteException e) { 2120 Slog.w(TAG, "RemoveException when invoking call back"); 2121 } 2122 } 2123 } 2124 }); 2125 } 2126 2127 @Override 2128 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2129 mContext.enforceCallingOrSelfPermission( 2130 android.Manifest.permission.CLEAR_APP_CACHE, null); 2131 // Queue up an async operation since clearing cache may take a little while. 2132 mHandler.post(new Runnable() { 2133 public void run() { 2134 mHandler.removeCallbacks(this); 2135 int retCode = -1; 2136 synchronized (mInstallLock) { 2137 retCode = mInstaller.freeCache(freeStorageSize); 2138 if (retCode < 0) { 2139 Slog.w(TAG, "Couldn't clear application caches"); 2140 } 2141 } 2142 if(pi != null) { 2143 try { 2144 // Callback via pending intent 2145 int code = (retCode >= 0) ? 1 : 0; 2146 pi.sendIntent(null, code, null, 2147 null, null); 2148 } catch (SendIntentException e1) { 2149 Slog.i(TAG, "Failed to send pending intent"); 2150 } 2151 } 2152 } 2153 }); 2154 } 2155 2156 void freeStorage(long freeStorageSize) throws IOException { 2157 synchronized (mInstallLock) { 2158 if (mInstaller.freeCache(freeStorageSize) < 0) { 2159 throw new IOException("Failed to free enough space"); 2160 } 2161 } 2162 } 2163 2164 @Override 2165 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2166 if (!sUserManager.exists(userId)) return null; 2167 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2168 synchronized (mPackages) { 2169 PackageParser.Activity a = mActivities.mActivities.get(component); 2170 2171 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2172 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2173 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2174 if (ps == null) return null; 2175 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2176 userId); 2177 } 2178 if (mResolveComponentName.equals(component)) { 2179 return mResolveActivity; 2180 } 2181 } 2182 return null; 2183 } 2184 2185 @Override 2186 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2187 String resolvedType) { 2188 synchronized (mPackages) { 2189 PackageParser.Activity a = mActivities.mActivities.get(component); 2190 if (a == null) { 2191 return false; 2192 } 2193 for (int i=0; i<a.intents.size(); i++) { 2194 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2195 intent.getData(), intent.getCategories(), TAG) >= 0) { 2196 return true; 2197 } 2198 } 2199 return false; 2200 } 2201 } 2202 2203 @Override 2204 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2205 if (!sUserManager.exists(userId)) return null; 2206 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2207 synchronized (mPackages) { 2208 PackageParser.Activity a = mReceivers.mActivities.get(component); 2209 if (DEBUG_PACKAGE_INFO) Log.v( 2210 TAG, "getReceiverInfo " + component + ": " + a); 2211 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2212 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2213 if (ps == null) return null; 2214 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2215 userId); 2216 } 2217 } 2218 return null; 2219 } 2220 2221 @Override 2222 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2223 if (!sUserManager.exists(userId)) return null; 2224 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2225 synchronized (mPackages) { 2226 PackageParser.Service s = mServices.mServices.get(component); 2227 if (DEBUG_PACKAGE_INFO) Log.v( 2228 TAG, "getServiceInfo " + component + ": " + s); 2229 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2230 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2231 if (ps == null) return null; 2232 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2233 userId); 2234 } 2235 } 2236 return null; 2237 } 2238 2239 @Override 2240 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2241 if (!sUserManager.exists(userId)) return null; 2242 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2243 synchronized (mPackages) { 2244 PackageParser.Provider p = mProviders.mProviders.get(component); 2245 if (DEBUG_PACKAGE_INFO) Log.v( 2246 TAG, "getProviderInfo " + component + ": " + p); 2247 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2248 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2249 if (ps == null) return null; 2250 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2251 userId); 2252 } 2253 } 2254 return null; 2255 } 2256 2257 @Override 2258 public String[] getSystemSharedLibraryNames() { 2259 Set<String> libSet; 2260 synchronized (mPackages) { 2261 libSet = mSharedLibraries.keySet(); 2262 int size = libSet.size(); 2263 if (size > 0) { 2264 String[] libs = new String[size]; 2265 libSet.toArray(libs); 2266 return libs; 2267 } 2268 } 2269 return null; 2270 } 2271 2272 @Override 2273 public FeatureInfo[] getSystemAvailableFeatures() { 2274 Collection<FeatureInfo> featSet; 2275 synchronized (mPackages) { 2276 featSet = mAvailableFeatures.values(); 2277 int size = featSet.size(); 2278 if (size > 0) { 2279 FeatureInfo[] features = new FeatureInfo[size+1]; 2280 featSet.toArray(features); 2281 FeatureInfo fi = new FeatureInfo(); 2282 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2283 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2284 features[size] = fi; 2285 return features; 2286 } 2287 } 2288 return null; 2289 } 2290 2291 @Override 2292 public boolean hasSystemFeature(String name) { 2293 synchronized (mPackages) { 2294 return mAvailableFeatures.containsKey(name); 2295 } 2296 } 2297 2298 private void checkValidCaller(int uid, int userId) { 2299 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2300 return; 2301 2302 throw new SecurityException("Caller uid=" + uid 2303 + " is not privileged to communicate with user=" + userId); 2304 } 2305 2306 @Override 2307 public int checkPermission(String permName, String pkgName) { 2308 synchronized (mPackages) { 2309 PackageParser.Package p = mPackages.get(pkgName); 2310 if (p != null && p.mExtras != null) { 2311 PackageSetting ps = (PackageSetting)p.mExtras; 2312 if (ps.sharedUser != null) { 2313 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2314 return PackageManager.PERMISSION_GRANTED; 2315 } 2316 } else if (ps.grantedPermissions.contains(permName)) { 2317 return PackageManager.PERMISSION_GRANTED; 2318 } 2319 } 2320 } 2321 return PackageManager.PERMISSION_DENIED; 2322 } 2323 2324 @Override 2325 public int checkUidPermission(String permName, int uid) { 2326 synchronized (mPackages) { 2327 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2328 if (obj != null) { 2329 GrantedPermissions gp = (GrantedPermissions)obj; 2330 if (gp.grantedPermissions.contains(permName)) { 2331 return PackageManager.PERMISSION_GRANTED; 2332 } 2333 } else { 2334 HashSet<String> perms = mSystemPermissions.get(uid); 2335 if (perms != null && perms.contains(permName)) { 2336 return PackageManager.PERMISSION_GRANTED; 2337 } 2338 } 2339 } 2340 return PackageManager.PERMISSION_DENIED; 2341 } 2342 2343 /** 2344 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2345 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2346 * @param message the message to log on security exception 2347 */ 2348 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2349 String message) { 2350 if (userId < 0) { 2351 throw new IllegalArgumentException("Invalid userId " + userId); 2352 } 2353 if (userId == UserHandle.getUserId(callingUid)) return; 2354 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2355 if (requireFullPermission) { 2356 mContext.enforceCallingOrSelfPermission( 2357 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2358 } else { 2359 try { 2360 mContext.enforceCallingOrSelfPermission( 2361 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2362 } catch (SecurityException se) { 2363 mContext.enforceCallingOrSelfPermission( 2364 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2365 } 2366 } 2367 } 2368 } 2369 2370 private BasePermission findPermissionTreeLP(String permName) { 2371 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2372 if (permName.startsWith(bp.name) && 2373 permName.length() > bp.name.length() && 2374 permName.charAt(bp.name.length()) == '.') { 2375 return bp; 2376 } 2377 } 2378 return null; 2379 } 2380 2381 private BasePermission checkPermissionTreeLP(String permName) { 2382 if (permName != null) { 2383 BasePermission bp = findPermissionTreeLP(permName); 2384 if (bp != null) { 2385 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2386 return bp; 2387 } 2388 throw new SecurityException("Calling uid " 2389 + Binder.getCallingUid() 2390 + " is not allowed to add to permission tree " 2391 + bp.name + " owned by uid " + bp.uid); 2392 } 2393 } 2394 throw new SecurityException("No permission tree found for " + permName); 2395 } 2396 2397 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2398 if (s1 == null) { 2399 return s2 == null; 2400 } 2401 if (s2 == null) { 2402 return false; 2403 } 2404 if (s1.getClass() != s2.getClass()) { 2405 return false; 2406 } 2407 return s1.equals(s2); 2408 } 2409 2410 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2411 if (pi1.icon != pi2.icon) return false; 2412 if (pi1.logo != pi2.logo) return false; 2413 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2414 if (!compareStrings(pi1.name, pi2.name)) return false; 2415 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2416 // We'll take care of setting this one. 2417 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2418 // These are not currently stored in settings. 2419 //if (!compareStrings(pi1.group, pi2.group)) return false; 2420 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2421 //if (pi1.labelRes != pi2.labelRes) return false; 2422 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2423 return true; 2424 } 2425 2426 int permissionInfoFootprint(PermissionInfo info) { 2427 int size = info.name.length(); 2428 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2429 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2430 return size; 2431 } 2432 2433 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2434 int size = 0; 2435 for (BasePermission perm : mSettings.mPermissions.values()) { 2436 if (perm.uid == tree.uid) { 2437 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2438 } 2439 } 2440 return size; 2441 } 2442 2443 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2444 // We calculate the max size of permissions defined by this uid and throw 2445 // if that plus the size of 'info' would exceed our stated maximum. 2446 if (tree.uid != Process.SYSTEM_UID) { 2447 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2448 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2449 throw new SecurityException("Permission tree size cap exceeded"); 2450 } 2451 } 2452 } 2453 2454 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2455 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2456 throw new SecurityException("Label must be specified in permission"); 2457 } 2458 BasePermission tree = checkPermissionTreeLP(info.name); 2459 BasePermission bp = mSettings.mPermissions.get(info.name); 2460 boolean added = bp == null; 2461 boolean changed = true; 2462 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2463 if (added) { 2464 enforcePermissionCapLocked(info, tree); 2465 bp = new BasePermission(info.name, tree.sourcePackage, 2466 BasePermission.TYPE_DYNAMIC); 2467 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2468 throw new SecurityException( 2469 "Not allowed to modify non-dynamic permission " 2470 + info.name); 2471 } else { 2472 if (bp.protectionLevel == fixedLevel 2473 && bp.perm.owner.equals(tree.perm.owner) 2474 && bp.uid == tree.uid 2475 && comparePermissionInfos(bp.perm.info, info)) { 2476 changed = false; 2477 } 2478 } 2479 bp.protectionLevel = fixedLevel; 2480 info = new PermissionInfo(info); 2481 info.protectionLevel = fixedLevel; 2482 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2483 bp.perm.info.packageName = tree.perm.info.packageName; 2484 bp.uid = tree.uid; 2485 if (added) { 2486 mSettings.mPermissions.put(info.name, bp); 2487 } 2488 if (changed) { 2489 if (!async) { 2490 mSettings.writeLPr(); 2491 } else { 2492 scheduleWriteSettingsLocked(); 2493 } 2494 } 2495 return added; 2496 } 2497 2498 @Override 2499 public boolean addPermission(PermissionInfo info) { 2500 synchronized (mPackages) { 2501 return addPermissionLocked(info, false); 2502 } 2503 } 2504 2505 @Override 2506 public boolean addPermissionAsync(PermissionInfo info) { 2507 synchronized (mPackages) { 2508 return addPermissionLocked(info, true); 2509 } 2510 } 2511 2512 @Override 2513 public void removePermission(String name) { 2514 synchronized (mPackages) { 2515 checkPermissionTreeLP(name); 2516 BasePermission bp = mSettings.mPermissions.get(name); 2517 if (bp != null) { 2518 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2519 throw new SecurityException( 2520 "Not allowed to modify non-dynamic permission " 2521 + name); 2522 } 2523 mSettings.mPermissions.remove(name); 2524 mSettings.writeLPr(); 2525 } 2526 } 2527 } 2528 2529 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2530 int index = pkg.requestedPermissions.indexOf(bp.name); 2531 if (index == -1) { 2532 throw new SecurityException("Package " + pkg.packageName 2533 + " has not requested permission " + bp.name); 2534 } 2535 boolean isNormal = 2536 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2537 == PermissionInfo.PROTECTION_NORMAL); 2538 boolean isDangerous = 2539 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2540 == PermissionInfo.PROTECTION_DANGEROUS); 2541 boolean isDevelopment = 2542 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2543 2544 if (!isNormal && !isDangerous && !isDevelopment) { 2545 throw new SecurityException("Permission " + bp.name 2546 + " is not a changeable permission type"); 2547 } 2548 2549 if (isNormal || isDangerous) { 2550 if (pkg.requestedPermissionsRequired.get(index)) { 2551 throw new SecurityException("Can't change " + bp.name 2552 + ". It is required by the application"); 2553 } 2554 } 2555 } 2556 2557 @Override 2558 public void grantPermission(String packageName, String permissionName) { 2559 mContext.enforceCallingOrSelfPermission( 2560 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2561 synchronized (mPackages) { 2562 final PackageParser.Package pkg = mPackages.get(packageName); 2563 if (pkg == null) { 2564 throw new IllegalArgumentException("Unknown package: " + packageName); 2565 } 2566 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2567 if (bp == null) { 2568 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2569 } 2570 2571 checkGrantRevokePermissions(pkg, bp); 2572 2573 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2574 if (ps == null) { 2575 return; 2576 } 2577 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2578 if (gp.grantedPermissions.add(permissionName)) { 2579 if (ps.haveGids) { 2580 gp.gids = appendInts(gp.gids, bp.gids); 2581 } 2582 mSettings.writeLPr(); 2583 } 2584 } 2585 } 2586 2587 @Override 2588 public void revokePermission(String packageName, String permissionName) { 2589 int changedAppId = -1; 2590 2591 synchronized (mPackages) { 2592 final PackageParser.Package pkg = mPackages.get(packageName); 2593 if (pkg == null) { 2594 throw new IllegalArgumentException("Unknown package: " + packageName); 2595 } 2596 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2597 mContext.enforceCallingOrSelfPermission( 2598 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2599 } 2600 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2601 if (bp == null) { 2602 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2603 } 2604 2605 checkGrantRevokePermissions(pkg, bp); 2606 2607 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2608 if (ps == null) { 2609 return; 2610 } 2611 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2612 if (gp.grantedPermissions.remove(permissionName)) { 2613 gp.grantedPermissions.remove(permissionName); 2614 if (ps.haveGids) { 2615 gp.gids = removeInts(gp.gids, bp.gids); 2616 } 2617 mSettings.writeLPr(); 2618 changedAppId = ps.appId; 2619 } 2620 } 2621 2622 if (changedAppId >= 0) { 2623 // We changed the perm on someone, kill its processes. 2624 IActivityManager am = ActivityManagerNative.getDefault(); 2625 if (am != null) { 2626 final int callingUserId = UserHandle.getCallingUserId(); 2627 final long ident = Binder.clearCallingIdentity(); 2628 try { 2629 //XXX we should only revoke for the calling user's app permissions, 2630 // but for now we impact all users. 2631 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2632 // "revoke " + permissionName); 2633 int[] users = sUserManager.getUserIds(); 2634 for (int user : users) { 2635 am.killUid(UserHandle.getUid(user, changedAppId), 2636 "revoke " + permissionName); 2637 } 2638 } catch (RemoteException e) { 2639 } finally { 2640 Binder.restoreCallingIdentity(ident); 2641 } 2642 } 2643 } 2644 } 2645 2646 @Override 2647 public boolean isProtectedBroadcast(String actionName) { 2648 synchronized (mPackages) { 2649 return mProtectedBroadcasts.contains(actionName); 2650 } 2651 } 2652 2653 @Override 2654 public int checkSignatures(String pkg1, String pkg2) { 2655 synchronized (mPackages) { 2656 final PackageParser.Package p1 = mPackages.get(pkg1); 2657 final PackageParser.Package p2 = mPackages.get(pkg2); 2658 if (p1 == null || p1.mExtras == null 2659 || p2 == null || p2.mExtras == null) { 2660 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2661 } 2662 return compareSignatures(p1.mSignatures, p2.mSignatures); 2663 } 2664 } 2665 2666 @Override 2667 public int checkUidSignatures(int uid1, int uid2) { 2668 // Map to base uids. 2669 uid1 = UserHandle.getAppId(uid1); 2670 uid2 = UserHandle.getAppId(uid2); 2671 // reader 2672 synchronized (mPackages) { 2673 Signature[] s1; 2674 Signature[] s2; 2675 Object obj = mSettings.getUserIdLPr(uid1); 2676 if (obj != null) { 2677 if (obj instanceof SharedUserSetting) { 2678 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2679 } else if (obj instanceof PackageSetting) { 2680 s1 = ((PackageSetting)obj).signatures.mSignatures; 2681 } else { 2682 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2683 } 2684 } else { 2685 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2686 } 2687 obj = mSettings.getUserIdLPr(uid2); 2688 if (obj != null) { 2689 if (obj instanceof SharedUserSetting) { 2690 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2691 } else if (obj instanceof PackageSetting) { 2692 s2 = ((PackageSetting)obj).signatures.mSignatures; 2693 } else { 2694 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2695 } 2696 } else { 2697 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2698 } 2699 return compareSignatures(s1, s2); 2700 } 2701 } 2702 2703 /** 2704 * Compares two sets of signatures. Returns: 2705 * <br /> 2706 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2707 * <br /> 2708 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2709 * <br /> 2710 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2711 * <br /> 2712 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2713 * <br /> 2714 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2715 */ 2716 static int compareSignatures(Signature[] s1, Signature[] s2) { 2717 if (s1 == null) { 2718 return s2 == null 2719 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2720 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2721 } 2722 2723 if (s2 == null) { 2724 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2725 } 2726 2727 if (s1.length != s2.length) { 2728 return PackageManager.SIGNATURE_NO_MATCH; 2729 } 2730 2731 // Since both signature sets are of size 1, we can compare without HashSets. 2732 if (s1.length == 1) { 2733 return s1[0].equals(s2[0]) ? 2734 PackageManager.SIGNATURE_MATCH : 2735 PackageManager.SIGNATURE_NO_MATCH; 2736 } 2737 2738 HashSet<Signature> set1 = new HashSet<Signature>(); 2739 for (Signature sig : s1) { 2740 set1.add(sig); 2741 } 2742 HashSet<Signature> set2 = new HashSet<Signature>(); 2743 for (Signature sig : s2) { 2744 set2.add(sig); 2745 } 2746 // Make sure s2 contains all signatures in s1. 2747 if (set1.equals(set2)) { 2748 return PackageManager.SIGNATURE_MATCH; 2749 } 2750 return PackageManager.SIGNATURE_NO_MATCH; 2751 } 2752 2753 /** 2754 * If the database version for this type of package (internal storage or 2755 * external storage) is less than the version where package signatures 2756 * were updated, return true. 2757 */ 2758 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2759 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2760 DatabaseVersion.SIGNATURE_END_ENTITY)) 2761 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2762 DatabaseVersion.SIGNATURE_END_ENTITY)); 2763 } 2764 2765 /** 2766 * Used for backward compatibility to make sure any packages with 2767 * certificate chains get upgraded to the new style. {@code existingSigs} 2768 * will be in the old format (since they were stored on disk from before the 2769 * system upgrade) and {@code scannedSigs} will be in the newer format. 2770 */ 2771 private int compareSignaturesCompat(PackageSignatures existingSigs, 2772 PackageParser.Package scannedPkg) { 2773 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2774 return PackageManager.SIGNATURE_NO_MATCH; 2775 } 2776 2777 HashSet<Signature> existingSet = new HashSet<Signature>(); 2778 for (Signature sig : existingSigs.mSignatures) { 2779 existingSet.add(sig); 2780 } 2781 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2782 for (Signature sig : scannedPkg.mSignatures) { 2783 try { 2784 Signature[] chainSignatures = sig.getChainSignatures(); 2785 for (Signature chainSig : chainSignatures) { 2786 scannedCompatSet.add(chainSig); 2787 } 2788 } catch (CertificateEncodingException e) { 2789 scannedCompatSet.add(sig); 2790 } 2791 } 2792 /* 2793 * Make sure the expanded scanned set contains all signatures in the 2794 * existing one. 2795 */ 2796 if (scannedCompatSet.equals(existingSet)) { 2797 // Migrate the old signatures to the new scheme. 2798 existingSigs.assignSignatures(scannedPkg.mSignatures); 2799 // The new KeySets will be re-added later in the scanning process. 2800 synchronized (mPackages) { 2801 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2802 } 2803 return PackageManager.SIGNATURE_MATCH; 2804 } 2805 return PackageManager.SIGNATURE_NO_MATCH; 2806 } 2807 2808 @Override 2809 public String[] getPackagesForUid(int uid) { 2810 uid = UserHandle.getAppId(uid); 2811 // reader 2812 synchronized (mPackages) { 2813 Object obj = mSettings.getUserIdLPr(uid); 2814 if (obj instanceof SharedUserSetting) { 2815 final SharedUserSetting sus = (SharedUserSetting) obj; 2816 final int N = sus.packages.size(); 2817 final String[] res = new String[N]; 2818 final Iterator<PackageSetting> it = sus.packages.iterator(); 2819 int i = 0; 2820 while (it.hasNext()) { 2821 res[i++] = it.next().name; 2822 } 2823 return res; 2824 } else if (obj instanceof PackageSetting) { 2825 final PackageSetting ps = (PackageSetting) obj; 2826 return new String[] { ps.name }; 2827 } 2828 } 2829 return null; 2830 } 2831 2832 @Override 2833 public String getNameForUid(int uid) { 2834 // reader 2835 synchronized (mPackages) { 2836 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2837 if (obj instanceof SharedUserSetting) { 2838 final SharedUserSetting sus = (SharedUserSetting) obj; 2839 return sus.name + ":" + sus.userId; 2840 } else if (obj instanceof PackageSetting) { 2841 final PackageSetting ps = (PackageSetting) obj; 2842 return ps.name; 2843 } 2844 } 2845 return null; 2846 } 2847 2848 @Override 2849 public int getUidForSharedUser(String sharedUserName) { 2850 if(sharedUserName == null) { 2851 return -1; 2852 } 2853 // reader 2854 synchronized (mPackages) { 2855 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2856 if (suid == null) { 2857 return -1; 2858 } 2859 return suid.userId; 2860 } 2861 } 2862 2863 @Override 2864 public int getFlagsForUid(int uid) { 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.pkgFlags; 2870 } else if (obj instanceof PackageSetting) { 2871 final PackageSetting ps = (PackageSetting) obj; 2872 return ps.pkgFlags; 2873 } 2874 } 2875 return 0; 2876 } 2877 2878 @Override 2879 public String[] getAppOpPermissionPackages(String permissionName) { 2880 synchronized (mPackages) { 2881 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 2882 if (pkgs == null) { 2883 return null; 2884 } 2885 return pkgs.toArray(new String[pkgs.size()]); 2886 } 2887 } 2888 2889 @Override 2890 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2891 int flags, int userId) { 2892 if (!sUserManager.exists(userId)) return null; 2893 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2894 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2895 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2896 } 2897 2898 @Override 2899 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2900 IntentFilter filter, int match, ComponentName activity) { 2901 final int userId = UserHandle.getCallingUserId(); 2902 if (DEBUG_PREFERRED) { 2903 Log.v(TAG, "setLastChosenActivity intent=" + intent 2904 + " resolvedType=" + resolvedType 2905 + " flags=" + flags 2906 + " filter=" + filter 2907 + " match=" + match 2908 + " activity=" + activity); 2909 filter.dump(new PrintStreamPrinter(System.out), " "); 2910 } 2911 intent.setComponent(null); 2912 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2913 // Find any earlier preferred or last chosen entries and nuke them 2914 findPreferredActivity(intent, resolvedType, 2915 flags, query, 0, false, true, false, userId); 2916 // Add the new activity as the last chosen for this filter 2917 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2918 } 2919 2920 @Override 2921 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2922 final int userId = UserHandle.getCallingUserId(); 2923 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2924 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2925 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2926 false, false, false, userId); 2927 } 2928 2929 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2930 int flags, List<ResolveInfo> query, int userId) { 2931 if (query != null) { 2932 final int N = query.size(); 2933 if (N == 1) { 2934 return query.get(0); 2935 } else if (N > 1) { 2936 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2937 // If there is more than one activity with the same priority, 2938 // then let the user decide between them. 2939 ResolveInfo r0 = query.get(0); 2940 ResolveInfo r1 = query.get(1); 2941 if (DEBUG_INTENT_MATCHING || debug) { 2942 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2943 + r1.activityInfo.name + "=" + r1.priority); 2944 } 2945 // If the first activity has a higher priority, or a different 2946 // default, then it is always desireable to pick it. 2947 if (r0.priority != r1.priority 2948 || r0.preferredOrder != r1.preferredOrder 2949 || r0.isDefault != r1.isDefault) { 2950 return query.get(0); 2951 } 2952 // If we have saved a preference for a preferred activity for 2953 // this Intent, use that. 2954 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2955 flags, query, r0.priority, true, false, debug, userId); 2956 if (ri != null) { 2957 return ri; 2958 } 2959 if (userId != 0) { 2960 ri = new ResolveInfo(mResolveInfo); 2961 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2962 ri.activityInfo.applicationInfo = new ApplicationInfo( 2963 ri.activityInfo.applicationInfo); 2964 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2965 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2966 return ri; 2967 } 2968 return mResolveInfo; 2969 } 2970 } 2971 return null; 2972 } 2973 2974 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2975 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2976 final int N = query.size(); 2977 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2978 .get(userId); 2979 // Get the list of persistent preferred activities that handle the intent 2980 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2981 List<PersistentPreferredActivity> pprefs = ppir != null 2982 ? ppir.queryIntent(intent, resolvedType, 2983 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2984 : null; 2985 if (pprefs != null && pprefs.size() > 0) { 2986 final int M = pprefs.size(); 2987 for (int i=0; i<M; i++) { 2988 final PersistentPreferredActivity ppa = pprefs.get(i); 2989 if (DEBUG_PREFERRED || debug) { 2990 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2991 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 2992 + "\n component=" + ppa.mComponent); 2993 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2994 } 2995 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 2996 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 2997 if (DEBUG_PREFERRED || debug) { 2998 Slog.v(TAG, "Found persistent preferred activity:"); 2999 if (ai != null) { 3000 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3001 } else { 3002 Slog.v(TAG, " null"); 3003 } 3004 } 3005 if (ai == null) { 3006 // This previously registered persistent preferred activity 3007 // component is no longer known. Ignore it and do NOT remove it. 3008 continue; 3009 } 3010 for (int j=0; j<N; j++) { 3011 final ResolveInfo ri = query.get(j); 3012 if (!ri.activityInfo.applicationInfo.packageName 3013 .equals(ai.applicationInfo.packageName)) { 3014 continue; 3015 } 3016 if (!ri.activityInfo.name.equals(ai.name)) { 3017 continue; 3018 } 3019 // Found a persistent preference that can handle the intent. 3020 if (DEBUG_PREFERRED || debug) { 3021 Slog.v(TAG, "Returning persistent preferred activity: " + 3022 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3023 } 3024 return ri; 3025 } 3026 } 3027 } 3028 return null; 3029 } 3030 3031 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3032 List<ResolveInfo> query, int priority, boolean always, 3033 boolean removeMatches, boolean debug, int userId) { 3034 if (!sUserManager.exists(userId)) return null; 3035 // writer 3036 synchronized (mPackages) { 3037 if (intent.getSelector() != null) { 3038 intent = intent.getSelector(); 3039 } 3040 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3041 3042 // Try to find a matching persistent preferred activity. 3043 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3044 debug, userId); 3045 3046 // If a persistent preferred activity matched, use it. 3047 if (pri != null) { 3048 return pri; 3049 } 3050 3051 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3052 // Get the list of preferred activities that handle the intent 3053 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3054 List<PreferredActivity> prefs = pir != null 3055 ? pir.queryIntent(intent, resolvedType, 3056 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3057 : null; 3058 if (prefs != null && prefs.size() > 0) { 3059 // First figure out how good the original match set is. 3060 // We will only allow preferred activities that came 3061 // from the same match quality. 3062 int match = 0; 3063 3064 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3065 3066 final int N = query.size(); 3067 for (int j=0; j<N; j++) { 3068 final ResolveInfo ri = query.get(j); 3069 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3070 + ": 0x" + Integer.toHexString(match)); 3071 if (ri.match > match) { 3072 match = ri.match; 3073 } 3074 } 3075 3076 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3077 + Integer.toHexString(match)); 3078 3079 match &= IntentFilter.MATCH_CATEGORY_MASK; 3080 final int M = prefs.size(); 3081 for (int i=0; i<M; i++) { 3082 final PreferredActivity pa = prefs.get(i); 3083 if (DEBUG_PREFERRED || debug) { 3084 Slog.v(TAG, "Checking PreferredActivity ds=" 3085 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3086 + "\n component=" + pa.mPref.mComponent); 3087 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3088 } 3089 if (pa.mPref.mMatch != match) { 3090 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3091 + Integer.toHexString(pa.mPref.mMatch)); 3092 continue; 3093 } 3094 // If it's not an "always" type preferred activity and that's what we're 3095 // looking for, skip it. 3096 if (always && !pa.mPref.mAlways) { 3097 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3098 continue; 3099 } 3100 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3101 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3102 if (DEBUG_PREFERRED || debug) { 3103 Slog.v(TAG, "Found preferred activity:"); 3104 if (ai != null) { 3105 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3106 } else { 3107 Slog.v(TAG, " null"); 3108 } 3109 } 3110 if (ai == null) { 3111 // This previously registered preferred activity 3112 // component is no longer known. Most likely an update 3113 // to the app was installed and in the new version this 3114 // component no longer exists. Clean it up by removing 3115 // it from the preferred activities list, and skip it. 3116 Slog.w(TAG, "Removing dangling preferred activity: " 3117 + pa.mPref.mComponent); 3118 pir.removeFilter(pa); 3119 continue; 3120 } 3121 for (int j=0; j<N; j++) { 3122 final ResolveInfo ri = query.get(j); 3123 if (!ri.activityInfo.applicationInfo.packageName 3124 .equals(ai.applicationInfo.packageName)) { 3125 continue; 3126 } 3127 if (!ri.activityInfo.name.equals(ai.name)) { 3128 continue; 3129 } 3130 3131 if (removeMatches) { 3132 pir.removeFilter(pa); 3133 if (DEBUG_PREFERRED) { 3134 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3135 } 3136 break; 3137 } 3138 3139 // Okay we found a previously set preferred or last chosen app. 3140 // If the result set is different from when this 3141 // was created, we need to clear it and re-ask the 3142 // user their preference, if we're looking for an "always" type entry. 3143 if (always && !pa.mPref.sameSet(query, priority)) { 3144 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3145 + intent + " type " + resolvedType); 3146 if (DEBUG_PREFERRED) { 3147 Slog.v(TAG, "Removing preferred activity since set changed " 3148 + pa.mPref.mComponent); 3149 } 3150 pir.removeFilter(pa); 3151 // Re-add the filter as a "last chosen" entry (!always) 3152 PreferredActivity lastChosen = new PreferredActivity( 3153 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3154 pir.addFilter(lastChosen); 3155 mSettings.writePackageRestrictionsLPr(userId); 3156 return null; 3157 } 3158 3159 // Yay! Either the set matched or we're looking for the last chosen 3160 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3161 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3162 mSettings.writePackageRestrictionsLPr(userId); 3163 return ri; 3164 } 3165 } 3166 } 3167 mSettings.writePackageRestrictionsLPr(userId); 3168 } 3169 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3170 return null; 3171 } 3172 3173 /* 3174 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3175 */ 3176 @Override 3177 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3178 int targetUserId) { 3179 mContext.enforceCallingOrSelfPermission( 3180 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3181 List<CrossProfileIntentFilter> matches = 3182 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3183 if (matches != null) { 3184 int size = matches.size(); 3185 for (int i = 0; i < size; i++) { 3186 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3187 } 3188 } 3189 3190 ArrayList<String> packageNames = null; 3191 SparseArray<ArrayList<String>> fromSource = 3192 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3193 if (fromSource != null) { 3194 packageNames = fromSource.get(targetUserId); 3195 } 3196 if (packageNames.contains(intent.getPackage())) { 3197 return true; 3198 } 3199 // We need the package name, so we try to resolve with the loosest flags possible 3200 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3201 intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3202 int count = resolveInfos.size(); 3203 for (int i = 0; i < count; i++) { 3204 ResolveInfo resolveInfo = resolveInfos.get(i); 3205 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3206 return true; 3207 } 3208 } 3209 return false; 3210 } 3211 3212 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3213 String resolvedType, int userId) { 3214 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3215 if (resolver != null) { 3216 return resolver.queryIntent(intent, resolvedType, false, userId); 3217 } 3218 return null; 3219 } 3220 3221 @Override 3222 public List<ResolveInfo> queryIntentActivities(Intent intent, 3223 String resolvedType, int flags, int userId) { 3224 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3225 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3226 ComponentName comp = intent.getComponent(); 3227 if (comp == null) { 3228 if (intent.getSelector() != null) { 3229 intent = intent.getSelector(); 3230 comp = intent.getComponent(); 3231 } 3232 } 3233 3234 if (comp != null) { 3235 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3236 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3237 if (ai != null) { 3238 final ResolveInfo ri = new ResolveInfo(); 3239 ri.activityInfo = ai; 3240 list.add(ri); 3241 } 3242 return list; 3243 } 3244 3245 // reader 3246 synchronized (mPackages) { 3247 final String pkgName = intent.getPackage(); 3248 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3249 if (pkgName == null) { 3250 ResolveInfo resolveInfo = null; 3251 if (queryCrossProfile) { 3252 // Check if the intent needs to be forwarded to another user for this package 3253 ArrayList<ResolveInfo> crossProfileResult = 3254 queryIntentActivitiesCrossProfilePackage( 3255 intent, resolvedType, flags, userId); 3256 if (!crossProfileResult.isEmpty()) { 3257 // Skip the current profile 3258 return crossProfileResult; 3259 } 3260 List<CrossProfileIntentFilter> matchingFilters = 3261 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3262 // Check for results that need to skip the current profile. 3263 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3264 resolvedType, flags, userId); 3265 if (resolveInfo != null) { 3266 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3267 result.add(resolveInfo); 3268 return result; 3269 } 3270 // Check for cross profile results. 3271 resolveInfo = queryCrossProfileIntents( 3272 matchingFilters, intent, resolvedType, flags, userId); 3273 } 3274 // Check for results in the current profile. 3275 List<ResolveInfo> result = mActivities.queryIntent( 3276 intent, resolvedType, flags, userId); 3277 if (resolveInfo != null) { 3278 result.add(resolveInfo); 3279 } 3280 return result; 3281 } 3282 final PackageParser.Package pkg = mPackages.get(pkgName); 3283 if (pkg != null) { 3284 if (queryCrossProfile) { 3285 ArrayList<ResolveInfo> crossProfileResult = 3286 queryIntentActivitiesCrossProfilePackage( 3287 intent, resolvedType, flags, userId, pkg, pkgName); 3288 if (!crossProfileResult.isEmpty()) { 3289 // Skip the current profile 3290 return crossProfileResult; 3291 } 3292 } 3293 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3294 pkg.activities, userId); 3295 } 3296 return new ArrayList<ResolveInfo>(); 3297 } 3298 } 3299 3300 private ResolveInfo querySkipCurrentProfileIntents( 3301 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3302 int flags, int sourceUserId) { 3303 if (matchingFilters != null) { 3304 int size = matchingFilters.size(); 3305 for (int i = 0; i < size; i ++) { 3306 CrossProfileIntentFilter filter = matchingFilters.get(i); 3307 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3308 // Checking if there are activities in the target user that can handle the 3309 // intent. 3310 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3311 flags, sourceUserId); 3312 if (resolveInfo != null) { 3313 return resolveInfo; 3314 } 3315 } 3316 } 3317 } 3318 return null; 3319 } 3320 3321 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3322 Intent intent, String resolvedType, int flags, int userId) { 3323 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3324 SparseArray<ArrayList<String>> sourceForwardingInfo = 3325 mSettings.mCrossProfilePackageInfo.get(userId); 3326 if (sourceForwardingInfo != null) { 3327 int NI = sourceForwardingInfo.size(); 3328 for (int i = 0; i < NI; i++) { 3329 int targetUserId = sourceForwardingInfo.keyAt(i); 3330 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3331 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3332 intent, resolvedType, flags, targetUserId); 3333 int NJ = resolveInfos.size(); 3334 for (int j = 0; j < NJ; j++) { 3335 ResolveInfo resolveInfo = resolveInfos.get(j); 3336 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3337 matchingResolveInfos.add(createForwardingResolveInfo( 3338 resolveInfo.filter, userId, targetUserId)); 3339 } 3340 } 3341 } 3342 } 3343 return matchingResolveInfos; 3344 } 3345 3346 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3347 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3348 String packageName) { 3349 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3350 SparseArray<ArrayList<String>> sourceForwardingInfo = 3351 mSettings.mCrossProfilePackageInfo.get(userId); 3352 if (sourceForwardingInfo != null) { 3353 int NI = sourceForwardingInfo.size(); 3354 for (int i = 0; i < NI; i++) { 3355 int targetUserId = sourceForwardingInfo.keyAt(i); 3356 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3357 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3358 intent, resolvedType, flags, pkg.activities, targetUserId); 3359 int NJ = resolveInfos.size(); 3360 for (int j = 0; j < NJ; j++) { 3361 ResolveInfo resolveInfo = resolveInfos.get(j); 3362 matchingResolveInfos.add(createForwardingResolveInfo( 3363 resolveInfo.filter, userId, targetUserId)); 3364 } 3365 } 3366 } 3367 } 3368 return matchingResolveInfos; 3369 } 3370 3371 // Return matching ResolveInfo if any for skip current profile intent filters. 3372 private ResolveInfo queryCrossProfileIntents( 3373 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3374 int flags, int sourceUserId) { 3375 if (matchingFilters != null) { 3376 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3377 // match the same intent. For performance reasons, it is better not to 3378 // run queryIntent twice for the same userId 3379 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3380 int size = matchingFilters.size(); 3381 for (int i = 0; i < size; i++) { 3382 CrossProfileIntentFilter filter = matchingFilters.get(i); 3383 int targetUserId = filter.getTargetUserId(); 3384 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3385 && !alreadyTriedUserIds.get(targetUserId)) { 3386 // Checking if there are activities in the target user that can handle the 3387 // intent. 3388 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3389 flags, sourceUserId); 3390 if (resolveInfo != null) return resolveInfo; 3391 alreadyTriedUserIds.put(targetUserId, true); 3392 } 3393 } 3394 } 3395 return null; 3396 } 3397 3398 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3399 String resolvedType, int flags, int sourceUserId) { 3400 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3401 resolvedType, flags, filter.getTargetUserId()); 3402 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3403 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3404 } 3405 return null; 3406 } 3407 3408 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3409 int sourceUserId, int targetUserId) { 3410 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3411 String className; 3412 if (targetUserId == UserHandle.USER_OWNER) { 3413 className = FORWARD_INTENT_TO_USER_OWNER; 3414 } else { 3415 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3416 } 3417 ComponentName forwardingActivityComponentName = new ComponentName( 3418 mAndroidApplication.packageName, className); 3419 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3420 sourceUserId); 3421 if (targetUserId == UserHandle.USER_OWNER) { 3422 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3423 forwardingResolveInfo.noResourceId = true; 3424 } 3425 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3426 forwardingResolveInfo.priority = 0; 3427 forwardingResolveInfo.preferredOrder = 0; 3428 forwardingResolveInfo.match = 0; 3429 forwardingResolveInfo.isDefault = true; 3430 forwardingResolveInfo.filter = filter; 3431 forwardingResolveInfo.targetUserId = targetUserId; 3432 return forwardingResolveInfo; 3433 } 3434 3435 @Override 3436 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3437 Intent[] specifics, String[] specificTypes, Intent intent, 3438 String resolvedType, int flags, int userId) { 3439 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3440 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3441 "query intent activity options"); 3442 final String resultsAction = intent.getAction(); 3443 3444 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3445 | PackageManager.GET_RESOLVED_FILTER, userId); 3446 3447 if (DEBUG_INTENT_MATCHING) { 3448 Log.v(TAG, "Query " + intent + ": " + results); 3449 } 3450 3451 int specificsPos = 0; 3452 int N; 3453 3454 // todo: note that the algorithm used here is O(N^2). This 3455 // isn't a problem in our current environment, but if we start running 3456 // into situations where we have more than 5 or 10 matches then this 3457 // should probably be changed to something smarter... 3458 3459 // First we go through and resolve each of the specific items 3460 // that were supplied, taking care of removing any corresponding 3461 // duplicate items in the generic resolve list. 3462 if (specifics != null) { 3463 for (int i=0; i<specifics.length; i++) { 3464 final Intent sintent = specifics[i]; 3465 if (sintent == null) { 3466 continue; 3467 } 3468 3469 if (DEBUG_INTENT_MATCHING) { 3470 Log.v(TAG, "Specific #" + i + ": " + sintent); 3471 } 3472 3473 String action = sintent.getAction(); 3474 if (resultsAction != null && resultsAction.equals(action)) { 3475 // If this action was explicitly requested, then don't 3476 // remove things that have it. 3477 action = null; 3478 } 3479 3480 ResolveInfo ri = null; 3481 ActivityInfo ai = null; 3482 3483 ComponentName comp = sintent.getComponent(); 3484 if (comp == null) { 3485 ri = resolveIntent( 3486 sintent, 3487 specificTypes != null ? specificTypes[i] : null, 3488 flags, userId); 3489 if (ri == null) { 3490 continue; 3491 } 3492 if (ri == mResolveInfo) { 3493 // ACK! Must do something better with this. 3494 } 3495 ai = ri.activityInfo; 3496 comp = new ComponentName(ai.applicationInfo.packageName, 3497 ai.name); 3498 } else { 3499 ai = getActivityInfo(comp, flags, userId); 3500 if (ai == null) { 3501 continue; 3502 } 3503 } 3504 3505 // Look for any generic query activities that are duplicates 3506 // of this specific one, and remove them from the results. 3507 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3508 N = results.size(); 3509 int j; 3510 for (j=specificsPos; j<N; j++) { 3511 ResolveInfo sri = results.get(j); 3512 if ((sri.activityInfo.name.equals(comp.getClassName()) 3513 && sri.activityInfo.applicationInfo.packageName.equals( 3514 comp.getPackageName())) 3515 || (action != null && sri.filter.matchAction(action))) { 3516 results.remove(j); 3517 if (DEBUG_INTENT_MATCHING) Log.v( 3518 TAG, "Removing duplicate item from " + j 3519 + " due to specific " + specificsPos); 3520 if (ri == null) { 3521 ri = sri; 3522 } 3523 j--; 3524 N--; 3525 } 3526 } 3527 3528 // Add this specific item to its proper place. 3529 if (ri == null) { 3530 ri = new ResolveInfo(); 3531 ri.activityInfo = ai; 3532 } 3533 results.add(specificsPos, ri); 3534 ri.specificIndex = i; 3535 specificsPos++; 3536 } 3537 } 3538 3539 // Now we go through the remaining generic results and remove any 3540 // duplicate actions that are found here. 3541 N = results.size(); 3542 for (int i=specificsPos; i<N-1; i++) { 3543 final ResolveInfo rii = results.get(i); 3544 if (rii.filter == null) { 3545 continue; 3546 } 3547 3548 // Iterate over all of the actions of this result's intent 3549 // filter... typically this should be just one. 3550 final Iterator<String> it = rii.filter.actionsIterator(); 3551 if (it == null) { 3552 continue; 3553 } 3554 while (it.hasNext()) { 3555 final String action = it.next(); 3556 if (resultsAction != null && resultsAction.equals(action)) { 3557 // If this action was explicitly requested, then don't 3558 // remove things that have it. 3559 continue; 3560 } 3561 for (int j=i+1; j<N; j++) { 3562 final ResolveInfo rij = results.get(j); 3563 if (rij.filter != null && rij.filter.hasAction(action)) { 3564 results.remove(j); 3565 if (DEBUG_INTENT_MATCHING) Log.v( 3566 TAG, "Removing duplicate item from " + j 3567 + " due to action " + action + " at " + i); 3568 j--; 3569 N--; 3570 } 3571 } 3572 } 3573 3574 // If the caller didn't request filter information, drop it now 3575 // so we don't have to marshall/unmarshall it. 3576 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3577 rii.filter = null; 3578 } 3579 } 3580 3581 // Filter out the caller activity if so requested. 3582 if (caller != null) { 3583 N = results.size(); 3584 for (int i=0; i<N; i++) { 3585 ActivityInfo ainfo = results.get(i).activityInfo; 3586 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3587 && caller.getClassName().equals(ainfo.name)) { 3588 results.remove(i); 3589 break; 3590 } 3591 } 3592 } 3593 3594 // If the caller didn't request filter information, 3595 // drop them now so we don't have to 3596 // marshall/unmarshall it. 3597 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3598 N = results.size(); 3599 for (int i=0; i<N; i++) { 3600 results.get(i).filter = null; 3601 } 3602 } 3603 3604 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3605 return results; 3606 } 3607 3608 @Override 3609 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3610 int userId) { 3611 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3612 ComponentName comp = intent.getComponent(); 3613 if (comp == null) { 3614 if (intent.getSelector() != null) { 3615 intent = intent.getSelector(); 3616 comp = intent.getComponent(); 3617 } 3618 } 3619 if (comp != null) { 3620 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3621 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3622 if (ai != null) { 3623 ResolveInfo ri = new ResolveInfo(); 3624 ri.activityInfo = ai; 3625 list.add(ri); 3626 } 3627 return list; 3628 } 3629 3630 // reader 3631 synchronized (mPackages) { 3632 String pkgName = intent.getPackage(); 3633 if (pkgName == null) { 3634 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3635 } 3636 final PackageParser.Package pkg = mPackages.get(pkgName); 3637 if (pkg != null) { 3638 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3639 userId); 3640 } 3641 return null; 3642 } 3643 } 3644 3645 @Override 3646 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3647 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3648 if (!sUserManager.exists(userId)) return null; 3649 if (query != null) { 3650 if (query.size() >= 1) { 3651 // If there is more than one service with the same priority, 3652 // just arbitrarily pick the first one. 3653 return query.get(0); 3654 } 3655 } 3656 return null; 3657 } 3658 3659 @Override 3660 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3661 int userId) { 3662 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3663 ComponentName comp = intent.getComponent(); 3664 if (comp == null) { 3665 if (intent.getSelector() != null) { 3666 intent = intent.getSelector(); 3667 comp = intent.getComponent(); 3668 } 3669 } 3670 if (comp != null) { 3671 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3672 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3673 if (si != null) { 3674 final ResolveInfo ri = new ResolveInfo(); 3675 ri.serviceInfo = si; 3676 list.add(ri); 3677 } 3678 return list; 3679 } 3680 3681 // reader 3682 synchronized (mPackages) { 3683 String pkgName = intent.getPackage(); 3684 if (pkgName == null) { 3685 return mServices.queryIntent(intent, resolvedType, flags, userId); 3686 } 3687 final PackageParser.Package pkg = mPackages.get(pkgName); 3688 if (pkg != null) { 3689 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3690 userId); 3691 } 3692 return null; 3693 } 3694 } 3695 3696 @Override 3697 public List<ResolveInfo> queryIntentContentProviders( 3698 Intent intent, String resolvedType, int flags, int userId) { 3699 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3700 ComponentName comp = intent.getComponent(); 3701 if (comp == null) { 3702 if (intent.getSelector() != null) { 3703 intent = intent.getSelector(); 3704 comp = intent.getComponent(); 3705 } 3706 } 3707 if (comp != null) { 3708 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3709 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3710 if (pi != null) { 3711 final ResolveInfo ri = new ResolveInfo(); 3712 ri.providerInfo = pi; 3713 list.add(ri); 3714 } 3715 return list; 3716 } 3717 3718 // reader 3719 synchronized (mPackages) { 3720 String pkgName = intent.getPackage(); 3721 if (pkgName == null) { 3722 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3723 } 3724 final PackageParser.Package pkg = mPackages.get(pkgName); 3725 if (pkg != null) { 3726 return mProviders.queryIntentForPackage( 3727 intent, resolvedType, flags, pkg.providers, userId); 3728 } 3729 return null; 3730 } 3731 } 3732 3733 @Override 3734 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3735 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3736 3737 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3738 3739 // writer 3740 synchronized (mPackages) { 3741 ArrayList<PackageInfo> list; 3742 if (listUninstalled) { 3743 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3744 for (PackageSetting ps : mSettings.mPackages.values()) { 3745 PackageInfo pi; 3746 if (ps.pkg != null) { 3747 pi = generatePackageInfo(ps.pkg, flags, userId); 3748 } else { 3749 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3750 } 3751 if (pi != null) { 3752 list.add(pi); 3753 } 3754 } 3755 } else { 3756 list = new ArrayList<PackageInfo>(mPackages.size()); 3757 for (PackageParser.Package p : mPackages.values()) { 3758 PackageInfo pi = generatePackageInfo(p, flags, userId); 3759 if (pi != null) { 3760 list.add(pi); 3761 } 3762 } 3763 } 3764 3765 return new ParceledListSlice<PackageInfo>(list); 3766 } 3767 } 3768 3769 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3770 String[] permissions, boolean[] tmp, int flags, int userId) { 3771 int numMatch = 0; 3772 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3773 for (int i=0; i<permissions.length; i++) { 3774 if (gp.grantedPermissions.contains(permissions[i])) { 3775 tmp[i] = true; 3776 numMatch++; 3777 } else { 3778 tmp[i] = false; 3779 } 3780 } 3781 if (numMatch == 0) { 3782 return; 3783 } 3784 PackageInfo pi; 3785 if (ps.pkg != null) { 3786 pi = generatePackageInfo(ps.pkg, flags, userId); 3787 } else { 3788 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3789 } 3790 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3791 if (numMatch == permissions.length) { 3792 pi.requestedPermissions = permissions; 3793 } else { 3794 pi.requestedPermissions = new String[numMatch]; 3795 numMatch = 0; 3796 for (int i=0; i<permissions.length; i++) { 3797 if (tmp[i]) { 3798 pi.requestedPermissions[numMatch] = permissions[i]; 3799 numMatch++; 3800 } 3801 } 3802 } 3803 } 3804 list.add(pi); 3805 } 3806 3807 @Override 3808 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3809 String[] permissions, int flags, int userId) { 3810 if (!sUserManager.exists(userId)) return null; 3811 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3812 3813 // writer 3814 synchronized (mPackages) { 3815 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3816 boolean[] tmpBools = new boolean[permissions.length]; 3817 if (listUninstalled) { 3818 for (PackageSetting ps : mSettings.mPackages.values()) { 3819 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3820 } 3821 } else { 3822 for (PackageParser.Package pkg : mPackages.values()) { 3823 PackageSetting ps = (PackageSetting)pkg.mExtras; 3824 if (ps != null) { 3825 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3826 userId); 3827 } 3828 } 3829 } 3830 3831 return new ParceledListSlice<PackageInfo>(list); 3832 } 3833 } 3834 3835 @Override 3836 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3837 if (!sUserManager.exists(userId)) return null; 3838 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3839 3840 // writer 3841 synchronized (mPackages) { 3842 ArrayList<ApplicationInfo> list; 3843 if (listUninstalled) { 3844 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3845 for (PackageSetting ps : mSettings.mPackages.values()) { 3846 ApplicationInfo ai; 3847 if (ps.pkg != null) { 3848 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3849 ps.readUserState(userId), userId); 3850 } else { 3851 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3852 } 3853 if (ai != null) { 3854 list.add(ai); 3855 } 3856 } 3857 } else { 3858 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3859 for (PackageParser.Package p : mPackages.values()) { 3860 if (p.mExtras != null) { 3861 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3862 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3863 if (ai != null) { 3864 list.add(ai); 3865 } 3866 } 3867 } 3868 } 3869 3870 return new ParceledListSlice<ApplicationInfo>(list); 3871 } 3872 } 3873 3874 public List<ApplicationInfo> getPersistentApplications(int flags) { 3875 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3876 3877 // reader 3878 synchronized (mPackages) { 3879 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3880 final int userId = UserHandle.getCallingUserId(); 3881 while (i.hasNext()) { 3882 final PackageParser.Package p = i.next(); 3883 if (p.applicationInfo != null 3884 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3885 && (!mSafeMode || isSystemApp(p))) { 3886 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3887 if (ps != null) { 3888 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3889 ps.readUserState(userId), userId); 3890 if (ai != null) { 3891 finalList.add(ai); 3892 } 3893 } 3894 } 3895 } 3896 } 3897 3898 return finalList; 3899 } 3900 3901 @Override 3902 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3903 if (!sUserManager.exists(userId)) return null; 3904 // reader 3905 synchronized (mPackages) { 3906 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3907 PackageSetting ps = provider != null 3908 ? mSettings.mPackages.get(provider.owner.packageName) 3909 : null; 3910 return ps != null 3911 && mSettings.isEnabledLPr(provider.info, flags, userId) 3912 && (!mSafeMode || (provider.info.applicationInfo.flags 3913 &ApplicationInfo.FLAG_SYSTEM) != 0) 3914 ? PackageParser.generateProviderInfo(provider, flags, 3915 ps.readUserState(userId), userId) 3916 : null; 3917 } 3918 } 3919 3920 /** 3921 * @deprecated 3922 */ 3923 @Deprecated 3924 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3925 // reader 3926 synchronized (mPackages) { 3927 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3928 .entrySet().iterator(); 3929 final int userId = UserHandle.getCallingUserId(); 3930 while (i.hasNext()) { 3931 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3932 PackageParser.Provider p = entry.getValue(); 3933 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3934 3935 if (ps != null && p.syncable 3936 && (!mSafeMode || (p.info.applicationInfo.flags 3937 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3938 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3939 ps.readUserState(userId), userId); 3940 if (info != null) { 3941 outNames.add(entry.getKey()); 3942 outInfo.add(info); 3943 } 3944 } 3945 } 3946 } 3947 } 3948 3949 @Override 3950 public List<ProviderInfo> queryContentProviders(String processName, 3951 int uid, int flags) { 3952 ArrayList<ProviderInfo> finalList = null; 3953 // reader 3954 synchronized (mPackages) { 3955 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3956 final int userId = processName != null ? 3957 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3958 while (i.hasNext()) { 3959 final PackageParser.Provider p = i.next(); 3960 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3961 if (ps != null && p.info.authority != null 3962 && (processName == null 3963 || (p.info.processName.equals(processName) 3964 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3965 && mSettings.isEnabledLPr(p.info, flags, userId) 3966 && (!mSafeMode 3967 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3968 if (finalList == null) { 3969 finalList = new ArrayList<ProviderInfo>(3); 3970 } 3971 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3972 ps.readUserState(userId), userId); 3973 if (info != null) { 3974 finalList.add(info); 3975 } 3976 } 3977 } 3978 } 3979 3980 if (finalList != null) { 3981 Collections.sort(finalList, mProviderInitOrderSorter); 3982 } 3983 3984 return finalList; 3985 } 3986 3987 @Override 3988 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3989 int flags) { 3990 // reader 3991 synchronized (mPackages) { 3992 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3993 return PackageParser.generateInstrumentationInfo(i, flags); 3994 } 3995 } 3996 3997 @Override 3998 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3999 int flags) { 4000 ArrayList<InstrumentationInfo> finalList = 4001 new ArrayList<InstrumentationInfo>(); 4002 4003 // reader 4004 synchronized (mPackages) { 4005 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4006 while (i.hasNext()) { 4007 final PackageParser.Instrumentation p = i.next(); 4008 if (targetPackage == null 4009 || targetPackage.equals(p.info.targetPackage)) { 4010 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4011 flags); 4012 if (ii != null) { 4013 finalList.add(ii); 4014 } 4015 } 4016 } 4017 } 4018 4019 return finalList; 4020 } 4021 4022 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4023 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4024 if (overlays == null) { 4025 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4026 return; 4027 } 4028 for (PackageParser.Package opkg : overlays.values()) { 4029 // Not much to do if idmap fails: we already logged the error 4030 // and we certainly don't want to abort installation of pkg simply 4031 // because an overlay didn't fit properly. For these reasons, 4032 // ignore the return value of createIdmapForPackagePairLI. 4033 createIdmapForPackagePairLI(pkg, opkg); 4034 } 4035 } 4036 4037 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4038 PackageParser.Package opkg) { 4039 if (!opkg.mTrustedOverlay) { 4040 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4041 opkg.baseCodePath + ": overlay not trusted"); 4042 return false; 4043 } 4044 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4045 if (overlaySet == null) { 4046 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4047 opkg.baseCodePath + " but target package has no known overlays"); 4048 return false; 4049 } 4050 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4051 // TODO: generate idmap for split APKs 4052 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4053 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4054 + opkg.baseCodePath); 4055 return false; 4056 } 4057 PackageParser.Package[] overlayArray = 4058 overlaySet.values().toArray(new PackageParser.Package[0]); 4059 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4060 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4061 return p1.mOverlayPriority - p2.mOverlayPriority; 4062 } 4063 }; 4064 Arrays.sort(overlayArray, cmp); 4065 4066 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4067 int i = 0; 4068 for (PackageParser.Package p : overlayArray) { 4069 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4070 } 4071 return true; 4072 } 4073 4074 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4075 final File[] files = dir.listFiles(); 4076 if (ArrayUtils.isEmpty(files)) { 4077 Log.d(TAG, "No files in app dir " + dir); 4078 return; 4079 } 4080 4081 if (DEBUG_PACKAGE_SCANNING) { 4082 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4083 + " flags=0x" + Integer.toHexString(flags)); 4084 } 4085 4086 for (File file : files) { 4087 final boolean isPackage = isApkFile(file) || file.isDirectory(); 4088 if (!isPackage) { 4089 // Ignore entries which are not apk's 4090 continue; 4091 } 4092 try { 4093 scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, 4094 null, null); 4095 } catch (PackageManagerException e) { 4096 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4097 4098 // Don't mess around with apps in system partition. 4099 if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4100 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4101 // Delete the apk 4102 Slog.w(TAG, "Cleaning up failed install of " + file); 4103 file.delete(); 4104 } 4105 } 4106 } 4107 } 4108 4109 private static File getSettingsProblemFile() { 4110 File dataDir = Environment.getDataDirectory(); 4111 File systemDir = new File(dataDir, "system"); 4112 File fname = new File(systemDir, "uiderrors.txt"); 4113 return fname; 4114 } 4115 4116 static void reportSettingsProblem(int priority, String msg) { 4117 try { 4118 File fname = getSettingsProblemFile(); 4119 FileOutputStream out = new FileOutputStream(fname, true); 4120 PrintWriter pw = new FastPrintWriter(out); 4121 SimpleDateFormat formatter = new SimpleDateFormat(); 4122 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4123 pw.println(dateString + ": " + msg); 4124 pw.close(); 4125 FileUtils.setPermissions( 4126 fname.toString(), 4127 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4128 -1, -1); 4129 } catch (java.io.IOException e) { 4130 } 4131 Slog.println(priority, TAG, msg); 4132 } 4133 4134 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4135 PackageParser.Package pkg, File srcFile, int parseFlags) 4136 throws PackageManagerException { 4137 if (ps != null 4138 && ps.codePath.equals(srcFile) 4139 && ps.timeStamp == srcFile.lastModified() 4140 && !isCompatSignatureUpdateNeeded(pkg)) { 4141 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4142 if (ps.signatures.mSignatures != null 4143 && ps.signatures.mSignatures.length != 0 4144 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4145 // Optimization: reuse the existing cached certificates 4146 // if the package appears to be unchanged. 4147 pkg.mSignatures = ps.signatures.mSignatures; 4148 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4149 synchronized (mPackages) { 4150 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4151 } 4152 return; 4153 } 4154 4155 Slog.w(TAG, "PackageSetting for " + ps.name 4156 + " is missing signatures. Collecting certs again to recover them."); 4157 } else { 4158 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4159 } 4160 4161 try { 4162 pp.collectCertificates(pkg, parseFlags); 4163 pp.collectManifestDigest(pkg); 4164 } catch (PackageParserException e) { 4165 throw new PackageManagerException(e.error, "Failed to collect certificates for " 4166 + pkg.packageName + ": " + e.getMessage()); 4167 } 4168 } 4169 4170 /* 4171 * Scan a package and return the newly parsed package. 4172 * Returns null in case of errors and the error code is stored in mLastScanError 4173 */ 4174 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode, 4175 long currentTime, UserHandle user, String abiOverride) throws PackageManagerException { 4176 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4177 parseFlags |= mDefParseFlags; 4178 PackageParser pp = new PackageParser(); 4179 pp.setSeparateProcesses(mSeparateProcesses); 4180 pp.setOnlyCoreApps(mOnlyCore); 4181 pp.setDisplayMetrics(mMetrics); 4182 4183 if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) { 4184 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4185 } 4186 4187 final PackageParser.Package pkg; 4188 try { 4189 pkg = pp.parsePackage(scanFile, parseFlags); 4190 } catch (PackageParserException e) { 4191 throw new PackageManagerException(e.error, 4192 "Failed to scan " + scanFile + ": " + e.getMessage()); 4193 } 4194 4195 PackageSetting ps = null; 4196 PackageSetting updatedPkg; 4197 // reader 4198 synchronized (mPackages) { 4199 // Look to see if we already know about this package. 4200 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4201 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4202 // This package has been renamed to its original name. Let's 4203 // use that. 4204 ps = mSettings.peekPackageLPr(oldName); 4205 } 4206 // If there was no original package, see one for the real package name. 4207 if (ps == null) { 4208 ps = mSettings.peekPackageLPr(pkg.packageName); 4209 } 4210 // Check to see if this package could be hiding/updating a system 4211 // package. Must look for it either under the original or real 4212 // package name depending on our state. 4213 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4214 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4215 } 4216 boolean updatedPkgBetter = false; 4217 // First check if this is a system package that may involve an update 4218 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4219 if (ps != null && !ps.codePath.equals(scanFile)) { 4220 // The path has changed from what was last scanned... check the 4221 // version of the new path against what we have stored to determine 4222 // what to do. 4223 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4224 if (pkg.mVersionCode < ps.versionCode) { 4225 // The system package has been updated and the code path does not match 4226 // Ignore entry. Skip it. 4227 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4228 + " ignored: updated version " + ps.versionCode 4229 + " better than this " + pkg.mVersionCode); 4230 if (!updatedPkg.codePath.equals(scanFile)) { 4231 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4232 + ps.name + " changing from " + updatedPkg.codePathString 4233 + " to " + scanFile); 4234 updatedPkg.codePath = scanFile; 4235 updatedPkg.codePathString = scanFile.toString(); 4236 // This is the point at which we know that the system-disk APK 4237 // for this package has moved during a reboot (e.g. due to an OTA), 4238 // so we need to reevaluate it for privilege policy. 4239 if (locationIsPrivileged(scanFile)) { 4240 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4241 } 4242 } 4243 updatedPkg.pkg = pkg; 4244 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4245 } else { 4246 // The current app on the system partition is better than 4247 // what we have updated to on the data partition; switch 4248 // back to the system partition version. 4249 // At this point, its safely assumed that package installation for 4250 // apps in system partition will go through. If not there won't be a working 4251 // version of the app 4252 // writer 4253 synchronized (mPackages) { 4254 // Just remove the loaded entries from package lists. 4255 mPackages.remove(ps.name); 4256 } 4257 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4258 + "reverting from " + ps.codePathString 4259 + ": new version " + pkg.mVersionCode 4260 + " better than installed " + ps.versionCode); 4261 4262 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4263 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4264 getAppDexInstructionSets(ps), isMultiArch(ps)); 4265 synchronized (mInstallLock) { 4266 args.cleanUpResourcesLI(); 4267 } 4268 synchronized (mPackages) { 4269 mSettings.enableSystemPackageLPw(ps.name); 4270 } 4271 updatedPkgBetter = true; 4272 } 4273 } 4274 } 4275 4276 if (updatedPkg != null) { 4277 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4278 // initially 4279 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4280 4281 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4282 // flag set initially 4283 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4284 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4285 } 4286 } 4287 4288 // Verify certificates against what was last scanned 4289 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4290 4291 /* 4292 * A new system app appeared, but we already had a non-system one of the 4293 * same name installed earlier. 4294 */ 4295 boolean shouldHideSystemApp = false; 4296 if (updatedPkg == null && ps != null 4297 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4298 /* 4299 * Check to make sure the signatures match first. If they don't, 4300 * wipe the installed application and its data. 4301 */ 4302 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4303 != PackageManager.SIGNATURE_MATCH) { 4304 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4305 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4306 ps = null; 4307 } else { 4308 /* 4309 * If the newly-added system app is an older version than the 4310 * already installed version, hide it. It will be scanned later 4311 * and re-added like an update. 4312 */ 4313 if (pkg.mVersionCode < ps.versionCode) { 4314 shouldHideSystemApp = true; 4315 } else { 4316 /* 4317 * The newly found system app is a newer version that the 4318 * one previously installed. Simply remove the 4319 * already-installed application and replace it with our own 4320 * while keeping the application data. 4321 */ 4322 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4323 + ps.codePathString + ": new version " + pkg.mVersionCode 4324 + " better than installed " + ps.versionCode); 4325 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4326 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4327 getAppDexInstructionSets(ps), isMultiArch(ps)); 4328 synchronized (mInstallLock) { 4329 args.cleanUpResourcesLI(); 4330 } 4331 } 4332 } 4333 } 4334 4335 // The apk is forward locked (not public) if its code and resources 4336 // are kept in different files. (except for app in either system or 4337 // vendor path). 4338 // TODO grab this value from PackageSettings 4339 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4340 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4341 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4342 } 4343 } 4344 4345 // TODO: extend to support forward-locked splits 4346 String resourcePath = null; 4347 String baseResourcePath = null; 4348 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4349 if (ps != null && ps.resourcePathString != null) { 4350 resourcePath = ps.resourcePathString; 4351 baseResourcePath = ps.resourcePathString; 4352 } else { 4353 // Should not happen at all. Just log an error. 4354 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4355 } 4356 } else { 4357 resourcePath = pkg.codePath; 4358 baseResourcePath = pkg.baseCodePath; 4359 } 4360 4361 // Set application objects path explicitly. 4362 pkg.applicationInfo.setCodePath(pkg.codePath); 4363 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4364 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4365 pkg.applicationInfo.setResourcePath(resourcePath); 4366 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4367 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4368 4369 // Note that we invoke the following method only if we are about to unpack an application 4370 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4371 | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride); 4372 4373 /* 4374 * If the system app should be overridden by a previously installed 4375 * data, hide the system app now and let the /data/app scan pick it up 4376 * again. 4377 */ 4378 if (shouldHideSystemApp) { 4379 synchronized (mPackages) { 4380 /* 4381 * We have to grant systems permissions before we hide, because 4382 * grantPermissions will assume the package update is trying to 4383 * expand its permissions. 4384 */ 4385 grantPermissionsLPw(pkg, true); 4386 mSettings.disableSystemPackageLPw(pkg.packageName); 4387 } 4388 } 4389 4390 return scannedPkg; 4391 } 4392 4393 private static String fixProcessName(String defProcessName, 4394 String processName, int uid) { 4395 if (processName == null) { 4396 return defProcessName; 4397 } 4398 return processName; 4399 } 4400 4401 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4402 throws PackageManagerException { 4403 if (pkgSetting.signatures.mSignatures != null) { 4404 // Already existing package. Make sure signatures match 4405 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4406 == PackageManager.SIGNATURE_MATCH; 4407 if (!match) { 4408 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4409 == PackageManager.SIGNATURE_MATCH; 4410 } 4411 if (!match) { 4412 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4413 + pkg.packageName + " signatures do not match the " 4414 + "previously installed version; ignoring!"); 4415 } 4416 } 4417 4418 // Check for shared user signatures 4419 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4420 // Already existing package. Make sure signatures match 4421 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4422 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4423 if (!match) { 4424 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4425 == PackageManager.SIGNATURE_MATCH; 4426 } 4427 if (!match) { 4428 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4429 "Package " + pkg.packageName 4430 + " has no signatures that match those in shared user " 4431 + pkgSetting.sharedUser.name + "; ignoring!"); 4432 } 4433 } 4434 } 4435 4436 /** 4437 * Enforces that only the system UID or root's UID can call a method exposed 4438 * via Binder. 4439 * 4440 * @param message used as message if SecurityException is thrown 4441 * @throws SecurityException if the caller is not system or root 4442 */ 4443 private static final void enforceSystemOrRoot(String message) { 4444 final int uid = Binder.getCallingUid(); 4445 if (uid != Process.SYSTEM_UID && uid != 0) { 4446 throw new SecurityException(message); 4447 } 4448 } 4449 4450 @Override 4451 public void performBootDexOpt() { 4452 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4453 4454 final HashSet<PackageParser.Package> pkgs; 4455 synchronized (mPackages) { 4456 pkgs = mDeferredDexOpt; 4457 mDeferredDexOpt = null; 4458 } 4459 4460 if (pkgs != null) { 4461 // Filter out packages that aren't recently used. 4462 // 4463 // The exception is first boot of a non-eng device, which 4464 // should do a full dexopt. 4465 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4466 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4467 // TODO: add a property to control this? 4468 long dexOptLRUThresholdInMinutes; 4469 if (eng) { 4470 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4471 } else { 4472 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4473 } 4474 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4475 4476 int total = pkgs.size(); 4477 int skipped = 0; 4478 long now = System.currentTimeMillis(); 4479 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4480 PackageParser.Package pkg = i.next(); 4481 long then = pkg.mLastPackageUsageTimeInMills; 4482 if (then + dexOptLRUThresholdInMills < now) { 4483 if (DEBUG_DEXOPT) { 4484 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4485 ((then == 0) ? "never" : new Date(then))); 4486 } 4487 i.remove(); 4488 skipped++; 4489 } 4490 } 4491 if (DEBUG_DEXOPT) { 4492 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4493 } 4494 } 4495 4496 int i = 0; 4497 for (PackageParser.Package pkg : pkgs) { 4498 i++; 4499 if (DEBUG_DEXOPT) { 4500 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4501 + ": " + pkg.packageName); 4502 } 4503 if (!isFirstBoot()) { 4504 try { 4505 ActivityManagerNative.getDefault().showBootMessage( 4506 mContext.getResources().getString( 4507 R.string.android_upgrading_apk, 4508 i, pkgs.size()), true); 4509 } catch (RemoteException e) { 4510 } 4511 } 4512 PackageParser.Package p = pkg; 4513 synchronized (mInstallLock) { 4514 performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */, 4515 true /* include dependencies */); 4516 } 4517 } 4518 } 4519 } 4520 4521 @Override 4522 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4523 return performDexOpt(packageName, instructionSet, true); 4524 } 4525 4526 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4527 if (info.primaryCpuAbi == null) { 4528 return getPreferredInstructionSet(); 4529 } 4530 4531 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4532 } 4533 4534 public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) { 4535 PackageParser.Package p; 4536 final String targetInstructionSet; 4537 synchronized (mPackages) { 4538 p = mPackages.get(packageName); 4539 if (p == null) { 4540 return false; 4541 } 4542 if (updateUsage) { 4543 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4544 } 4545 mPackageUsage.write(false); 4546 4547 targetInstructionSet = instructionSet != null ? instructionSet : 4548 getPrimaryInstructionSet(p.applicationInfo); 4549 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4550 return false; 4551 } 4552 } 4553 4554 synchronized (mInstallLock) { 4555 final String[] instructionSets = new String[] { targetInstructionSet }; 4556 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4557 true /* include dependencies */) == DEX_OPT_PERFORMED; 4558 } 4559 } 4560 4561 public HashSet<String> getPackagesThatNeedDexOpt() { 4562 HashSet<String> pkgs = null; 4563 synchronized (mPackages) { 4564 for (PackageParser.Package p : mPackages.values()) { 4565 if (DEBUG_DEXOPT) { 4566 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4567 } 4568 if (!p.mDexOptPerformed.isEmpty()) { 4569 continue; 4570 } 4571 if (pkgs == null) { 4572 pkgs = new HashSet<String>(); 4573 } 4574 pkgs.add(p.packageName); 4575 } 4576 } 4577 return pkgs; 4578 } 4579 4580 public void shutdown() { 4581 mPackageUsage.write(true); 4582 } 4583 4584 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4585 boolean forceDex, boolean defer, HashSet<String> done) { 4586 for (int i=0; i<libs.size(); i++) { 4587 PackageParser.Package libPkg; 4588 String libName; 4589 synchronized (mPackages) { 4590 libName = libs.get(i); 4591 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4592 if (lib != null && lib.apk != null) { 4593 libPkg = mPackages.get(lib.apk); 4594 } else { 4595 libPkg = null; 4596 } 4597 } 4598 if (libPkg != null && !done.contains(libName)) { 4599 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4600 } 4601 } 4602 } 4603 4604 static final int DEX_OPT_SKIPPED = 0; 4605 static final int DEX_OPT_PERFORMED = 1; 4606 static final int DEX_OPT_DEFERRED = 2; 4607 static final int DEX_OPT_FAILED = -1; 4608 4609 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4610 boolean forceDex, boolean defer, HashSet<String> done) { 4611 final String[] instructionSets = targetInstructionSets != null ? 4612 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4613 4614 if (done != null) { 4615 done.add(pkg.packageName); 4616 if (pkg.usesLibraries != null) { 4617 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4618 } 4619 if (pkg.usesOptionalLibraries != null) { 4620 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4621 } 4622 } 4623 4624 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4625 return DEX_OPT_SKIPPED; 4626 } 4627 4628 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4629 boolean performedDexOpt = false; 4630 // There are three basic cases here: 4631 // 1.) we need to dexopt, either because we are forced or it is needed 4632 // 2.) we are defering a needed dexopt 4633 // 3.) we are skipping an unneeded dexopt 4634 for (String path : paths) { 4635 for (String instructionSet : instructionSets) { 4636 if (!forceDex && pkg.mDexOptPerformed.contains(instructionSet)) { 4637 continue; 4638 } 4639 4640 try { 4641 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4642 // patckage or the one we find does not match the image checksum (i.e. it was 4643 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4644 // odex file and it matches the checksum of the image but not its base address, 4645 // meaning we need to move it. 4646 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4647 pkg.packageName, instructionSet, defer); 4648 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4649 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4650 + pkg.applicationInfo.packageName + " isa=" + instructionSet); 4651 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4652 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4653 pkg.packageName, instructionSet); 4654 4655 if (ret < 0) { 4656 // Don't bother running dexopt again if we failed, it will probably 4657 // just result in an error again. Also, don't bother dexopting for other 4658 // paths & ISAs. 4659 return DEX_OPT_FAILED; 4660 } else { 4661 performedDexOpt = true; 4662 pkg.mDexOptPerformed.add(instructionSet); 4663 } 4664 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4665 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4666 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4667 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4668 pkg.packageName, instructionSet); 4669 4670 if (ret < 0) { 4671 // Don't bother running patchoat again if we failed, it will probably 4672 // just result in an error again. Also, don't bother dexopting for other 4673 // paths & ISAs. 4674 return DEX_OPT_FAILED; 4675 } else { 4676 performedDexOpt = true; 4677 pkg.mDexOptPerformed.add(instructionSet); 4678 } 4679 } 4680 4681 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4682 // paths and instruction sets. We'll deal with them all together when we process 4683 // our list of deferred dexopts. 4684 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4685 if (mDeferredDexOpt == null) { 4686 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4687 } 4688 mDeferredDexOpt.add(pkg); 4689 return DEX_OPT_DEFERRED; 4690 } 4691 } catch (FileNotFoundException e) { 4692 Slog.w(TAG, "Apk not found for dexopt: " + path); 4693 return DEX_OPT_FAILED; 4694 } catch (IOException e) { 4695 Slog.w(TAG, "IOException reading apk: " + path, e); 4696 return DEX_OPT_FAILED; 4697 } catch (StaleDexCacheError e) { 4698 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4699 return DEX_OPT_FAILED; 4700 } catch (Exception e) { 4701 Slog.w(TAG, "Exception when doing dexopt : ", e); 4702 return DEX_OPT_FAILED; 4703 } 4704 } 4705 } 4706 4707 // If we've gotten here, we're sure that no error occurred and that we haven't 4708 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4709 // we've skipped all of them because they are up to date. In both cases this 4710 // package doesn't need dexopt any longer. 4711 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4712 } 4713 4714 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4715 if (info.primaryCpuAbi != null) { 4716 if (info.secondaryCpuAbi != null) { 4717 return new String[] { 4718 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4719 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4720 } else { 4721 return new String[] { 4722 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4723 } 4724 } 4725 4726 return new String[] { getPreferredInstructionSet() }; 4727 } 4728 4729 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4730 if (ps.primaryCpuAbiString != null) { 4731 if (ps.secondaryCpuAbiString != null) { 4732 return new String[] { 4733 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4734 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4735 } else { 4736 return new String[] { 4737 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4738 } 4739 } 4740 4741 return new String[] { getPreferredInstructionSet() }; 4742 } 4743 4744 private static String getPreferredInstructionSet() { 4745 if (sPreferredInstructionSet == null) { 4746 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4747 } 4748 4749 return sPreferredInstructionSet; 4750 } 4751 4752 private static List<String> getAllInstructionSets() { 4753 final String[] allAbis = Build.SUPPORTED_ABIS; 4754 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4755 4756 for (String abi : allAbis) { 4757 final String instructionSet = VMRuntime.getInstructionSet(abi); 4758 if (!allInstructionSets.contains(instructionSet)) { 4759 allInstructionSets.add(instructionSet); 4760 } 4761 } 4762 4763 return allInstructionSets; 4764 } 4765 4766 @Override 4767 public void forceDexOpt(String packageName) { 4768 enforceSystemOrRoot("forceDexOpt"); 4769 4770 PackageParser.Package pkg; 4771 synchronized (mPackages) { 4772 pkg = mPackages.get(packageName); 4773 if (pkg == null) { 4774 throw new IllegalArgumentException("Missing package: " + packageName); 4775 } 4776 } 4777 4778 synchronized (mInstallLock) { 4779 final String[] instructionSets = new String[] { 4780 getPrimaryInstructionSet(pkg.applicationInfo) }; 4781 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4782 if (res != DEX_OPT_PERFORMED) { 4783 throw new IllegalStateException("Failed to dexopt: " + res); 4784 } 4785 } 4786 } 4787 4788 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4789 boolean forceDex, boolean defer, boolean inclDependencies) { 4790 HashSet<String> done; 4791 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4792 done = new HashSet<String>(); 4793 done.add(pkg.packageName); 4794 } else { 4795 done = null; 4796 } 4797 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4798 } 4799 4800 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4801 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4802 Slog.w(TAG, "Unable to update from " + oldPkg.name 4803 + " to " + newPkg.packageName 4804 + ": old package not in system partition"); 4805 return false; 4806 } else if (mPackages.get(oldPkg.name) != null) { 4807 Slog.w(TAG, "Unable to update from " + oldPkg.name 4808 + " to " + newPkg.packageName 4809 + ": old package still exists"); 4810 return false; 4811 } 4812 return true; 4813 } 4814 4815 File getDataPathForUser(int userId) { 4816 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4817 } 4818 4819 private File getDataPathForPackage(String packageName, int userId) { 4820 /* 4821 * Until we fully support multiple users, return the directory we 4822 * previously would have. The PackageManagerTests will need to be 4823 * revised when this is changed back.. 4824 */ 4825 if (userId == 0) { 4826 return new File(mAppDataDir, packageName); 4827 } else { 4828 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4829 + File.separator + packageName); 4830 } 4831 } 4832 4833 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4834 int[] users = sUserManager.getUserIds(); 4835 int res = mInstaller.install(packageName, uid, uid, seinfo); 4836 if (res < 0) { 4837 return res; 4838 } 4839 for (int user : users) { 4840 if (user != 0) { 4841 res = mInstaller.createUserData(packageName, 4842 UserHandle.getUid(user, uid), user, seinfo); 4843 if (res < 0) { 4844 return res; 4845 } 4846 } 4847 } 4848 return res; 4849 } 4850 4851 private int removeDataDirsLI(String packageName) { 4852 int[] users = sUserManager.getUserIds(); 4853 int res = 0; 4854 for (int user : users) { 4855 int resInner = mInstaller.remove(packageName, user); 4856 if (resInner < 0) { 4857 res = resInner; 4858 } 4859 } 4860 4861 return res; 4862 } 4863 4864 private int deleteCodeCacheDirsLI(String packageName) { 4865 int[] users = sUserManager.getUserIds(); 4866 int res = 0; 4867 for (int user : users) { 4868 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4869 if (resInner < 0) { 4870 res = resInner; 4871 } 4872 } 4873 return res; 4874 } 4875 4876 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4877 PackageParser.Package changingLib) { 4878 if (file.path != null) { 4879 usesLibraryFiles.add(file.path); 4880 return; 4881 } 4882 PackageParser.Package p = mPackages.get(file.apk); 4883 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4884 // If we are doing this while in the middle of updating a library apk, 4885 // then we need to make sure to use that new apk for determining the 4886 // dependencies here. (We haven't yet finished committing the new apk 4887 // to the package manager state.) 4888 if (p == null || p.packageName.equals(changingLib.packageName)) { 4889 p = changingLib; 4890 } 4891 } 4892 if (p != null) { 4893 usesLibraryFiles.addAll(p.getAllCodePaths()); 4894 } 4895 } 4896 4897 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4898 PackageParser.Package changingLib) throws PackageManagerException { 4899 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4900 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4901 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4902 for (int i=0; i<N; i++) { 4903 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4904 if (file == null) { 4905 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4906 "Package " + pkg.packageName + " requires unavailable shared library " 4907 + pkg.usesLibraries.get(i) + "; failing!"); 4908 } 4909 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4910 } 4911 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4912 for (int i=0; i<N; i++) { 4913 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4914 if (file == null) { 4915 Slog.w(TAG, "Package " + pkg.packageName 4916 + " desires unavailable shared library " 4917 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4918 } else { 4919 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4920 } 4921 } 4922 N = usesLibraryFiles.size(); 4923 if (N > 0) { 4924 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4925 } else { 4926 pkg.usesLibraryFiles = null; 4927 } 4928 } 4929 } 4930 4931 private static boolean hasString(List<String> list, List<String> which) { 4932 if (list == null) { 4933 return false; 4934 } 4935 for (int i=list.size()-1; i>=0; i--) { 4936 for (int j=which.size()-1; j>=0; j--) { 4937 if (which.get(j).equals(list.get(i))) { 4938 return true; 4939 } 4940 } 4941 } 4942 return false; 4943 } 4944 4945 private void updateAllSharedLibrariesLPw() { 4946 for (PackageParser.Package pkg : mPackages.values()) { 4947 try { 4948 updateSharedLibrariesLPw(pkg, null); 4949 } catch (PackageManagerException e) { 4950 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4951 } 4952 } 4953 } 4954 4955 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4956 PackageParser.Package changingPkg) { 4957 ArrayList<PackageParser.Package> res = null; 4958 for (PackageParser.Package pkg : mPackages.values()) { 4959 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4960 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4961 if (res == null) { 4962 res = new ArrayList<PackageParser.Package>(); 4963 } 4964 res.add(pkg); 4965 try { 4966 updateSharedLibrariesLPw(pkg, changingPkg); 4967 } catch (PackageManagerException e) { 4968 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4969 } 4970 } 4971 } 4972 return res; 4973 } 4974 4975 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 4976 int scanMode, long currentTime, UserHandle user, String abiOverride) 4977 throws PackageManagerException { 4978 final File scanFile = new File(pkg.codePath); 4979 if (pkg.applicationInfo.getCodePath() == null || 4980 pkg.applicationInfo.getResourcePath() == null) { 4981 // Bail out. The resource and code paths haven't been set. 4982 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 4983 "Code and resource paths haven't been set correctly"); 4984 } 4985 4986 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4987 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4988 } 4989 4990 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4991 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4992 } 4993 4994 if (mCustomResolverComponentName != null && 4995 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4996 setUpCustomResolverActivity(pkg); 4997 } 4998 4999 if (pkg.packageName.equals("android")) { 5000 synchronized (mPackages) { 5001 if (mAndroidApplication != null) { 5002 Slog.w(TAG, "*************************************************"); 5003 Slog.w(TAG, "Core android package being redefined. Skipping."); 5004 Slog.w(TAG, " file=" + scanFile); 5005 Slog.w(TAG, "*************************************************"); 5006 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5007 "Core android package being redefined. Skipping."); 5008 } 5009 5010 // Set up information for our fall-back user intent resolution activity. 5011 mPlatformPackage = pkg; 5012 pkg.mVersionCode = mSdkVersion; 5013 mAndroidApplication = pkg.applicationInfo; 5014 5015 if (!mResolverReplaced) { 5016 mResolveActivity.applicationInfo = mAndroidApplication; 5017 mResolveActivity.name = ResolverActivity.class.getName(); 5018 mResolveActivity.packageName = mAndroidApplication.packageName; 5019 mResolveActivity.processName = "system:ui"; 5020 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5021 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5022 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5023 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5024 mResolveActivity.exported = true; 5025 mResolveActivity.enabled = true; 5026 mResolveInfo.activityInfo = mResolveActivity; 5027 mResolveInfo.priority = 0; 5028 mResolveInfo.preferredOrder = 0; 5029 mResolveInfo.match = 0; 5030 mResolveComponentName = new ComponentName( 5031 mAndroidApplication.packageName, mResolveActivity.name); 5032 } 5033 } 5034 } 5035 5036 if (DEBUG_PACKAGE_SCANNING) { 5037 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5038 Log.d(TAG, "Scanning package " + pkg.packageName); 5039 } 5040 5041 if (mPackages.containsKey(pkg.packageName) 5042 || mSharedLibraries.containsKey(pkg.packageName)) { 5043 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5044 "Application package " + pkg.packageName 5045 + " already installed. Skipping duplicate."); 5046 } 5047 5048 // Initialize package source and resource directories 5049 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5050 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5051 5052 SharedUserSetting suid = null; 5053 PackageSetting pkgSetting = null; 5054 5055 if (!isSystemApp(pkg)) { 5056 // Only system apps can use these features. 5057 pkg.mOriginalPackages = null; 5058 pkg.mRealPackage = null; 5059 pkg.mAdoptPermissions = null; 5060 } 5061 5062 // writer 5063 synchronized (mPackages) { 5064 if (pkg.mSharedUserId != null) { 5065 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5066 if (suid == null) { 5067 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5068 "Creating application package " + pkg.packageName 5069 + " for shared user failed"); 5070 } 5071 if (DEBUG_PACKAGE_SCANNING) { 5072 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5073 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5074 + "): packages=" + suid.packages); 5075 } 5076 } 5077 5078 // Check if we are renaming from an original package name. 5079 PackageSetting origPackage = null; 5080 String realName = null; 5081 if (pkg.mOriginalPackages != null) { 5082 // This package may need to be renamed to a previously 5083 // installed name. Let's check on that... 5084 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5085 if (pkg.mOriginalPackages.contains(renamed)) { 5086 // This package had originally been installed as the 5087 // original name, and we have already taken care of 5088 // transitioning to the new one. Just update the new 5089 // one to continue using the old name. 5090 realName = pkg.mRealPackage; 5091 if (!pkg.packageName.equals(renamed)) { 5092 // Callers into this function may have already taken 5093 // care of renaming the package; only do it here if 5094 // it is not already done. 5095 pkg.setPackageName(renamed); 5096 } 5097 5098 } else { 5099 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5100 if ((origPackage = mSettings.peekPackageLPr( 5101 pkg.mOriginalPackages.get(i))) != null) { 5102 // We do have the package already installed under its 5103 // original name... should we use it? 5104 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5105 // New package is not compatible with original. 5106 origPackage = null; 5107 continue; 5108 } else if (origPackage.sharedUser != null) { 5109 // Make sure uid is compatible between packages. 5110 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5111 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5112 + " to " + pkg.packageName + ": old uid " 5113 + origPackage.sharedUser.name 5114 + " differs from " + pkg.mSharedUserId); 5115 origPackage = null; 5116 continue; 5117 } 5118 } else { 5119 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5120 + pkg.packageName + " to old name " + origPackage.name); 5121 } 5122 break; 5123 } 5124 } 5125 } 5126 } 5127 5128 if (mTransferedPackages.contains(pkg.packageName)) { 5129 Slog.w(TAG, "Package " + pkg.packageName 5130 + " was transferred to another, but its .apk remains"); 5131 } 5132 5133 // Just create the setting, don't add it yet. For already existing packages 5134 // the PkgSetting exists already and doesn't have to be created. 5135 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5136 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5137 pkg.applicationInfo.primaryCpuAbi, 5138 pkg.applicationInfo.secondaryCpuAbi, 5139 pkg.applicationInfo.flags, user, false); 5140 if (pkgSetting == null) { 5141 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5142 "Creating application package " + pkg.packageName + " failed"); 5143 } 5144 5145 if (pkgSetting.origPackage != null) { 5146 // If we are first transitioning from an original package, 5147 // fix up the new package's name now. We need to do this after 5148 // looking up the package under its new name, so getPackageLP 5149 // can take care of fiddling things correctly. 5150 pkg.setPackageName(origPackage.name); 5151 5152 // File a report about this. 5153 String msg = "New package " + pkgSetting.realName 5154 + " renamed to replace old package " + pkgSetting.name; 5155 reportSettingsProblem(Log.WARN, msg); 5156 5157 // Make a note of it. 5158 mTransferedPackages.add(origPackage.name); 5159 5160 // No longer need to retain this. 5161 pkgSetting.origPackage = null; 5162 } 5163 5164 if (realName != null) { 5165 // Make a note of it. 5166 mTransferedPackages.add(pkg.packageName); 5167 } 5168 5169 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5170 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5171 } 5172 5173 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5174 // Check all shared libraries and map to their actual file path. 5175 // We only do this here for apps not on a system dir, because those 5176 // are the only ones that can fail an install due to this. We 5177 // will take care of the system apps by updating all of their 5178 // library paths after the scan is done. 5179 updateSharedLibrariesLPw(pkg, null); 5180 } 5181 5182 if (mFoundPolicyFile) { 5183 SELinuxMMAC.assignSeinfoValue(pkg); 5184 } 5185 5186 pkg.applicationInfo.uid = pkgSetting.appId; 5187 pkg.mExtras = pkgSetting; 5188 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5189 try { 5190 verifySignaturesLP(pkgSetting, pkg); 5191 } catch (PackageManagerException e) { 5192 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5193 throw e; 5194 } 5195 // The signature has changed, but this package is in the system 5196 // image... let's recover! 5197 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5198 // However... if this package is part of a shared user, but it 5199 // doesn't match the signature of the shared user, let's fail. 5200 // What this means is that you can't change the signatures 5201 // associated with an overall shared user, which doesn't seem all 5202 // that unreasonable. 5203 if (pkgSetting.sharedUser != null) { 5204 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5205 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5206 throw new PackageManagerException( 5207 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5208 "Signature mismatch for shared user : " 5209 + pkgSetting.sharedUser); 5210 } 5211 } 5212 // File a report about this. 5213 String msg = "System package " + pkg.packageName 5214 + " signature changed; retaining data."; 5215 reportSettingsProblem(Log.WARN, msg); 5216 } 5217 } else { 5218 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5219 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5220 + pkg.packageName + " upgrade keys do not match the " 5221 + "previously installed version"); 5222 } else { 5223 // signatures may have changed as result of upgrade 5224 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5225 } 5226 } 5227 // Verify that this new package doesn't have any content providers 5228 // that conflict with existing packages. Only do this if the 5229 // package isn't already installed, since we don't want to break 5230 // things that are installed. 5231 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5232 final int N = pkg.providers.size(); 5233 int i; 5234 for (i=0; i<N; i++) { 5235 PackageParser.Provider p = pkg.providers.get(i); 5236 if (p.info.authority != null) { 5237 String names[] = p.info.authority.split(";"); 5238 for (int j = 0; j < names.length; j++) { 5239 if (mProvidersByAuthority.containsKey(names[j])) { 5240 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5241 final String otherPackageName = 5242 ((other != null && other.getComponentName() != null) ? 5243 other.getComponentName().getPackageName() : "?"); 5244 throw new PackageManagerException( 5245 INSTALL_FAILED_CONFLICTING_PROVIDER, 5246 "Can't install because provider name " + names[j] 5247 + " (in package " + pkg.applicationInfo.packageName 5248 + ") is already used by " + otherPackageName); 5249 } 5250 } 5251 } 5252 } 5253 } 5254 5255 if (pkg.mAdoptPermissions != null) { 5256 // This package wants to adopt ownership of permissions from 5257 // another package. 5258 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5259 final String origName = pkg.mAdoptPermissions.get(i); 5260 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5261 if (orig != null) { 5262 if (verifyPackageUpdateLPr(orig, pkg)) { 5263 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5264 + pkg.packageName); 5265 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5266 } 5267 } 5268 } 5269 } 5270 } 5271 5272 final String pkgName = pkg.packageName; 5273 5274 final long scanFileTime = scanFile.lastModified(); 5275 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5276 pkg.applicationInfo.processName = fixProcessName( 5277 pkg.applicationInfo.packageName, 5278 pkg.applicationInfo.processName, 5279 pkg.applicationInfo.uid); 5280 5281 File dataPath; 5282 if (mPlatformPackage == pkg) { 5283 // The system package is special. 5284 dataPath = new File (Environment.getDataDirectory(), "system"); 5285 pkg.applicationInfo.dataDir = dataPath.getPath(); 5286 5287 } else { 5288 // This is a normal package, need to make its data directory. 5289 dataPath = getDataPathForPackage(pkg.packageName, 0); 5290 5291 boolean uidError = false; 5292 5293 if (dataPath.exists()) { 5294 int currentUid = 0; 5295 try { 5296 StructStat stat = Os.stat(dataPath.getPath()); 5297 currentUid = stat.st_uid; 5298 } catch (ErrnoException e) { 5299 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5300 } 5301 5302 // If we have mismatched owners for the data path, we have a problem. 5303 if (currentUid != pkg.applicationInfo.uid) { 5304 boolean recovered = false; 5305 if (currentUid == 0) { 5306 // The directory somehow became owned by root. Wow. 5307 // This is probably because the system was stopped while 5308 // installd was in the middle of messing with its libs 5309 // directory. Ask installd to fix that. 5310 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5311 pkg.applicationInfo.uid); 5312 if (ret >= 0) { 5313 recovered = true; 5314 String msg = "Package " + pkg.packageName 5315 + " unexpectedly changed to uid 0; recovered to " + 5316 + pkg.applicationInfo.uid; 5317 reportSettingsProblem(Log.WARN, msg); 5318 } 5319 } 5320 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5321 || (scanMode&SCAN_BOOTING) != 0)) { 5322 // If this is a system app, we can at least delete its 5323 // current data so the application will still work. 5324 int ret = removeDataDirsLI(pkgName); 5325 if (ret >= 0) { 5326 // TODO: Kill the processes first 5327 // Old data gone! 5328 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5329 ? "System package " : "Third party package "; 5330 String msg = prefix + pkg.packageName 5331 + " has changed from uid: " 5332 + currentUid + " to " 5333 + pkg.applicationInfo.uid + "; old data erased"; 5334 reportSettingsProblem(Log.WARN, msg); 5335 recovered = true; 5336 5337 // And now re-install the app. 5338 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5339 pkg.applicationInfo.seinfo); 5340 if (ret == -1) { 5341 // Ack should not happen! 5342 msg = prefix + pkg.packageName 5343 + " could not have data directory re-created after delete."; 5344 reportSettingsProblem(Log.WARN, msg); 5345 throw new PackageManagerException( 5346 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5347 } 5348 } 5349 if (!recovered) { 5350 mHasSystemUidErrors = true; 5351 } 5352 } else if (!recovered) { 5353 // If we allow this install to proceed, we will be broken. 5354 // Abort, abort! 5355 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5356 "scanPackageLI"); 5357 } 5358 if (!recovered) { 5359 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5360 + pkg.applicationInfo.uid + "/fs_" 5361 + currentUid; 5362 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5363 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5364 String msg = "Package " + pkg.packageName 5365 + " has mismatched uid: " 5366 + currentUid + " on disk, " 5367 + pkg.applicationInfo.uid + " in settings"; 5368 // writer 5369 synchronized (mPackages) { 5370 mSettings.mReadMessages.append(msg); 5371 mSettings.mReadMessages.append('\n'); 5372 uidError = true; 5373 if (!pkgSetting.uidError) { 5374 reportSettingsProblem(Log.ERROR, msg); 5375 } 5376 } 5377 } 5378 } 5379 pkg.applicationInfo.dataDir = dataPath.getPath(); 5380 if (mShouldRestoreconData) { 5381 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5382 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5383 pkg.applicationInfo.uid); 5384 } 5385 } else { 5386 if (DEBUG_PACKAGE_SCANNING) { 5387 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5388 Log.v(TAG, "Want this data dir: " + dataPath); 5389 } 5390 //invoke installer to do the actual installation 5391 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5392 pkg.applicationInfo.seinfo); 5393 if (ret < 0) { 5394 // Error from installer 5395 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5396 "Unable to create data dirs [errorCode=" + ret + "]"); 5397 } 5398 5399 if (dataPath.exists()) { 5400 pkg.applicationInfo.dataDir = dataPath.getPath(); 5401 } else { 5402 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5403 pkg.applicationInfo.dataDir = null; 5404 } 5405 } 5406 5407 pkgSetting.uidError = uidError; 5408 } 5409 5410 final String path = scanFile.getPath(); 5411 final String codePath = pkg.applicationInfo.getCodePath(); 5412 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5413 // For the case where we had previously uninstalled an update, get rid 5414 // of any native binaries we might have unpackaged. Note that this assumes 5415 // that system app updates were not installed via ASEC. 5416 // 5417 // TODO(multiArch): Is this cleanup really necessary ? 5418 NativeLibraryHelper.removeNativeBinariesFromDirLI( 5419 new File(codePath, LIB_DIR_NAME), false /* delete dirs */); 5420 setBundledAppAbisAndRoots(pkg, pkgSetting); 5421 5422 // If we haven't found any native libraries for the app, check if it has 5423 // renderscript code. We'll need to force the app to 32 bit if it has 5424 // renderscript bitcode. 5425 if (pkg.applicationInfo.primaryCpuAbi == null 5426 && pkg.applicationInfo.secondaryCpuAbi == null 5427 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5428 NativeLibraryHelper.Handle handle = null; 5429 try { 5430 handle = NativeLibraryHelper.Handle.create(scanFile); 5431 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5432 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5433 } 5434 } catch (IOException ioe) { 5435 Slog.w(TAG, "Error scanning system app : " + ioe); 5436 } finally { 5437 IoUtils.closeQuietly(handle); 5438 } 5439 } 5440 5441 setNativeLibraryPaths(pkg); 5442 } else { 5443 // TODO: We can probably be smarter about this stuff. For installed apps, 5444 // we can calculate this information at install time once and for all. For 5445 // system apps, we can probably assume that this information doesn't change 5446 // after the first boot scan. As things stand, we do lots of unnecessary work. 5447 5448 // Give ourselves some initial paths; we'll come back for another 5449 // pass once we've determined ABI below. 5450 setNativeLibraryPaths(pkg); 5451 5452 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5453 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5454 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5455 5456 NativeLibraryHelper.Handle handle = null; 5457 try { 5458 handle = NativeLibraryHelper.Handle.create(scanFile); 5459 // TODO(multiArch): This can be null for apps that didn't go through the 5460 // usual installation process. We can calculate it again, like we 5461 // do during install time. 5462 // 5463 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5464 // unnecessary. 5465 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5466 5467 // Null out the abis so that they can be recalculated. 5468 pkg.applicationInfo.primaryCpuAbi = null; 5469 pkg.applicationInfo.secondaryCpuAbi = null; 5470 if (isMultiArch(pkg.applicationInfo)) { 5471 // Warn if we've set an abiOverride for multi-lib packages.. 5472 // By definition, we need to copy both 32 and 64 bit libraries for 5473 // such packages. 5474 if (abiOverride != null) { 5475 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5476 } 5477 5478 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5479 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5480 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5481 if (isAsec) { 5482 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5483 } else { 5484 abi32 = copyNativeLibrariesForInternalApp(handle, 5485 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs); 5486 } 5487 } 5488 5489 maybeThrowExceptionForMultiArchCopy( 5490 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5491 5492 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5493 if (isAsec) { 5494 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5495 } else { 5496 abi64 = copyNativeLibrariesForInternalApp(handle, 5497 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs); 5498 } 5499 } 5500 5501 maybeThrowExceptionForMultiArchCopy( 5502 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5503 5504 if (abi64 >= 0) { 5505 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5506 } 5507 5508 if (abi32 >= 0) { 5509 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5510 if (abi64 >= 0) { 5511 pkg.applicationInfo.secondaryCpuAbi = abi; 5512 } else { 5513 pkg.applicationInfo.primaryCpuAbi = abi; 5514 } 5515 } 5516 } else { 5517 String[] abiList = (abiOverride != null) ? 5518 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 5519 5520 // Enable gross and lame hacks for apps that are built with old 5521 // SDK tools. We must scan their APKs for renderscript bitcode and 5522 // not launch them if it's present. Don't bother checking on devices 5523 // that don't have 64 bit support. 5524 boolean needsRenderScriptOverride = false; 5525 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null && 5526 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5527 abiList = Build.SUPPORTED_32_BIT_ABIS; 5528 needsRenderScriptOverride = true; 5529 } 5530 5531 final int copyRet; 5532 if (isAsec) { 5533 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5534 } else { 5535 copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryRoot, abiList, 5536 useIsaSpecificSubdirs); 5537 } 5538 5539 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5540 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5541 "Error unpackaging native libs for app, errorCode=" + copyRet); 5542 } 5543 5544 if (copyRet >= 0) { 5545 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5546 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && abiOverride != null) { 5547 pkg.applicationInfo.primaryCpuAbi = abiOverride; 5548 } else if (needsRenderScriptOverride) { 5549 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5550 } 5551 } 5552 } catch (IOException ioe) { 5553 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5554 } finally { 5555 IoUtils.closeQuietly(handle); 5556 } 5557 5558 // Now that we've calculated the ABIs and determined if it's an internal app, 5559 // we will go ahead and populate the nativeLibraryPath. 5560 setNativeLibraryPaths(pkg); 5561 5562 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5563 final int[] userIds = sUserManager.getUserIds(); 5564 synchronized (mInstallLock) { 5565 // Create a native library symlink only if we have native libraries 5566 // and if the native libraries are 32 bit libraries. We do not provide 5567 // this symlink for 64 bit libraries. 5568 if (pkg.applicationInfo.primaryCpuAbi != null && 5569 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5570 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5571 for (int userId : userIds) { 5572 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5573 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5574 "Failed linking native library dir (user=" + userId + ")"); 5575 } 5576 } 5577 } 5578 } 5579 } 5580 5581 // This is a special case for the "system" package, where the ABI is 5582 // dictated by the zygote configuration (and init.rc). We should keep track 5583 // of this ABI so that we can deal with "normal" applications that run under 5584 // the same UID correctly. 5585 if (mPlatformPackage == pkg) { 5586 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5587 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5588 } 5589 5590 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5591 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5592 5593 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5594 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5595 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5596 5597 // Push the derived path down into PackageSettings so we know what to 5598 // clean up at uninstall time. 5599 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5600 5601 if (DEBUG_ABI_SELECTION) { 5602 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5603 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5604 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5605 } 5606 5607 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5608 // We don't do this here during boot because we can do it all 5609 // at once after scanning all existing packages. 5610 // 5611 // We also do this *before* we perform dexopt on this package, so that 5612 // we can avoid redundant dexopts, and also to make sure we've got the 5613 // code and package path correct. 5614 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5615 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0); 5616 } 5617 5618 if ((scanMode&SCAN_NO_DEX) == 0) { 5619 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5620 == DEX_OPT_FAILED) { 5621 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5622 removeDataDirsLI(pkg.packageName); 5623 } 5624 5625 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5626 } 5627 } 5628 5629 if (mFactoryTest && pkg.requestedPermissions.contains( 5630 android.Manifest.permission.FACTORY_TEST)) { 5631 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5632 } 5633 5634 ArrayList<PackageParser.Package> clientLibPkgs = null; 5635 5636 // writer 5637 synchronized (mPackages) { 5638 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5639 // Only system apps can add new shared libraries. 5640 if (pkg.libraryNames != null) { 5641 for (int i=0; i<pkg.libraryNames.size(); i++) { 5642 String name = pkg.libraryNames.get(i); 5643 boolean allowed = false; 5644 if (isUpdatedSystemApp(pkg)) { 5645 // New library entries can only be added through the 5646 // system image. This is important to get rid of a lot 5647 // of nasty edge cases: for example if we allowed a non- 5648 // system update of the app to add a library, then uninstalling 5649 // the update would make the library go away, and assumptions 5650 // we made such as through app install filtering would now 5651 // have allowed apps on the device which aren't compatible 5652 // with it. Better to just have the restriction here, be 5653 // conservative, and create many fewer cases that can negatively 5654 // impact the user experience. 5655 final PackageSetting sysPs = mSettings 5656 .getDisabledSystemPkgLPr(pkg.packageName); 5657 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5658 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5659 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5660 allowed = true; 5661 allowed = true; 5662 break; 5663 } 5664 } 5665 } 5666 } else { 5667 allowed = true; 5668 } 5669 if (allowed) { 5670 if (!mSharedLibraries.containsKey(name)) { 5671 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5672 } else if (!name.equals(pkg.packageName)) { 5673 Slog.w(TAG, "Package " + pkg.packageName + " library " 5674 + name + " already exists; skipping"); 5675 } 5676 } else { 5677 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5678 + name + " that is not declared on system image; skipping"); 5679 } 5680 } 5681 if ((scanMode&SCAN_BOOTING) == 0) { 5682 // If we are not booting, we need to update any applications 5683 // that are clients of our shared library. If we are booting, 5684 // this will all be done once the scan is complete. 5685 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5686 } 5687 } 5688 } 5689 } 5690 5691 // We also need to dexopt any apps that are dependent on this library. Note that 5692 // if these fail, we should abort the install since installing the library will 5693 // result in some apps being broken. 5694 if (clientLibPkgs != null) { 5695 if ((scanMode&SCAN_NO_DEX) == 0) { 5696 for (int i=0; i<clientLibPkgs.size(); i++) { 5697 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5698 if (performDexOptLI(clientPkg, null /* instruction sets */, 5699 forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5700 == DEX_OPT_FAILED) { 5701 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5702 removeDataDirsLI(pkg.packageName); 5703 } 5704 5705 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5706 "scanPackageLI failed to dexopt clientLibPkgs"); 5707 } 5708 } 5709 } 5710 } 5711 5712 // Request the ActivityManager to kill the process(only for existing packages) 5713 // so that we do not end up in a confused state while the user is still using the older 5714 // version of the application while the new one gets installed. 5715 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5716 // If the package lives in an asec, tell everyone that the container is going 5717 // away so they can clean up any references to its resources (which would prevent 5718 // vold from being able to unmount the asec) 5719 if (isForwardLocked(pkg) || isExternal(pkg)) { 5720 if (DEBUG_INSTALL) { 5721 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5722 } 5723 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5724 final ArrayList<String> pkgList = new ArrayList<String>(1); 5725 pkgList.add(pkg.applicationInfo.packageName); 5726 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5727 } 5728 5729 // Post the request that it be killed now that the going-away broadcast is en route 5730 killApplication(pkg.applicationInfo.packageName, 5731 pkg.applicationInfo.uid, "update pkg"); 5732 } 5733 5734 // Also need to kill any apps that are dependent on the library. 5735 if (clientLibPkgs != null) { 5736 for (int i=0; i<clientLibPkgs.size(); i++) { 5737 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5738 killApplication(clientPkg.applicationInfo.packageName, 5739 clientPkg.applicationInfo.uid, "update lib"); 5740 } 5741 } 5742 5743 // writer 5744 synchronized (mPackages) { 5745 // We don't expect installation to fail beyond this point, 5746 if ((scanMode&SCAN_MONITOR) != 0) { 5747 mAppDirs.put(pkg.codePath, pkg); 5748 } 5749 // Add the new setting to mSettings 5750 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5751 // Add the new setting to mPackages 5752 mPackages.put(pkg.applicationInfo.packageName, pkg); 5753 // Make sure we don't accidentally delete its data. 5754 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5755 while (iter.hasNext()) { 5756 PackageCleanItem item = iter.next(); 5757 if (pkgName.equals(item.packageName)) { 5758 iter.remove(); 5759 } 5760 } 5761 5762 // Take care of first install / last update times. 5763 if (currentTime != 0) { 5764 if (pkgSetting.firstInstallTime == 0) { 5765 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5766 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5767 pkgSetting.lastUpdateTime = currentTime; 5768 } 5769 } else if (pkgSetting.firstInstallTime == 0) { 5770 // We need *something*. Take time time stamp of the file. 5771 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5772 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5773 if (scanFileTime != pkgSetting.timeStamp) { 5774 // A package on the system image has changed; consider this 5775 // to be an update. 5776 pkgSetting.lastUpdateTime = scanFileTime; 5777 } 5778 } 5779 5780 // Add the package's KeySets to the global KeySetManagerService 5781 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5782 try { 5783 // Old KeySetData no longer valid. 5784 ksms.removeAppKeySetDataLPw(pkg.packageName); 5785 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5786 if (pkg.mKeySetMapping != null) { 5787 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5788 pkg.mKeySetMapping.entrySet()) { 5789 if (entry.getValue() != null) { 5790 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5791 entry.getValue(), entry.getKey()); 5792 } 5793 } 5794 if (pkg.mUpgradeKeySets != null) { 5795 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5796 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5797 } 5798 } 5799 } 5800 } catch (NullPointerException e) { 5801 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5802 } catch (IllegalArgumentException e) { 5803 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5804 } 5805 5806 int N = pkg.providers.size(); 5807 StringBuilder r = null; 5808 int i; 5809 for (i=0; i<N; i++) { 5810 PackageParser.Provider p = pkg.providers.get(i); 5811 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5812 p.info.processName, pkg.applicationInfo.uid); 5813 mProviders.addProvider(p); 5814 p.syncable = p.info.isSyncable; 5815 if (p.info.authority != null) { 5816 String names[] = p.info.authority.split(";"); 5817 p.info.authority = null; 5818 for (int j = 0; j < names.length; j++) { 5819 if (j == 1 && p.syncable) { 5820 // We only want the first authority for a provider to possibly be 5821 // syncable, so if we already added this provider using a different 5822 // authority clear the syncable flag. We copy the provider before 5823 // changing it because the mProviders object contains a reference 5824 // to a provider that we don't want to change. 5825 // Only do this for the second authority since the resulting provider 5826 // object can be the same for all future authorities for this provider. 5827 p = new PackageParser.Provider(p); 5828 p.syncable = false; 5829 } 5830 if (!mProvidersByAuthority.containsKey(names[j])) { 5831 mProvidersByAuthority.put(names[j], p); 5832 if (p.info.authority == null) { 5833 p.info.authority = names[j]; 5834 } else { 5835 p.info.authority = p.info.authority + ";" + names[j]; 5836 } 5837 if (DEBUG_PACKAGE_SCANNING) { 5838 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5839 Log.d(TAG, "Registered content provider: " + names[j] 5840 + ", className = " + p.info.name + ", isSyncable = " 5841 + p.info.isSyncable); 5842 } 5843 } else { 5844 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5845 Slog.w(TAG, "Skipping provider name " + names[j] + 5846 " (in package " + pkg.applicationInfo.packageName + 5847 "): name already used by " 5848 + ((other != null && other.getComponentName() != null) 5849 ? other.getComponentName().getPackageName() : "?")); 5850 } 5851 } 5852 } 5853 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5854 if (r == null) { 5855 r = new StringBuilder(256); 5856 } else { 5857 r.append(' '); 5858 } 5859 r.append(p.info.name); 5860 } 5861 } 5862 if (r != null) { 5863 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5864 } 5865 5866 N = pkg.services.size(); 5867 r = null; 5868 for (i=0; i<N; i++) { 5869 PackageParser.Service s = pkg.services.get(i); 5870 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5871 s.info.processName, pkg.applicationInfo.uid); 5872 mServices.addService(s); 5873 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5874 if (r == null) { 5875 r = new StringBuilder(256); 5876 } else { 5877 r.append(' '); 5878 } 5879 r.append(s.info.name); 5880 } 5881 } 5882 if (r != null) { 5883 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5884 } 5885 5886 N = pkg.receivers.size(); 5887 r = null; 5888 for (i=0; i<N; i++) { 5889 PackageParser.Activity a = pkg.receivers.get(i); 5890 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5891 a.info.processName, pkg.applicationInfo.uid); 5892 mReceivers.addActivity(a, "receiver"); 5893 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5894 if (r == null) { 5895 r = new StringBuilder(256); 5896 } else { 5897 r.append(' '); 5898 } 5899 r.append(a.info.name); 5900 } 5901 } 5902 if (r != null) { 5903 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5904 } 5905 5906 N = pkg.activities.size(); 5907 r = null; 5908 for (i=0; i<N; i++) { 5909 PackageParser.Activity a = pkg.activities.get(i); 5910 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5911 a.info.processName, pkg.applicationInfo.uid); 5912 mActivities.addActivity(a, "activity"); 5913 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5914 if (r == null) { 5915 r = new StringBuilder(256); 5916 } else { 5917 r.append(' '); 5918 } 5919 r.append(a.info.name); 5920 } 5921 } 5922 if (r != null) { 5923 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5924 } 5925 5926 N = pkg.permissionGroups.size(); 5927 r = null; 5928 for (i=0; i<N; i++) { 5929 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5930 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5931 if (cur == null) { 5932 mPermissionGroups.put(pg.info.name, pg); 5933 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5934 if (r == null) { 5935 r = new StringBuilder(256); 5936 } else { 5937 r.append(' '); 5938 } 5939 r.append(pg.info.name); 5940 } 5941 } else { 5942 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5943 + pg.info.packageName + " ignored: original from " 5944 + cur.info.packageName); 5945 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5946 if (r == null) { 5947 r = new StringBuilder(256); 5948 } else { 5949 r.append(' '); 5950 } 5951 r.append("DUP:"); 5952 r.append(pg.info.name); 5953 } 5954 } 5955 } 5956 if (r != null) { 5957 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5958 } 5959 5960 N = pkg.permissions.size(); 5961 r = null; 5962 for (i=0; i<N; i++) { 5963 PackageParser.Permission p = pkg.permissions.get(i); 5964 HashMap<String, BasePermission> permissionMap = 5965 p.tree ? mSettings.mPermissionTrees 5966 : mSettings.mPermissions; 5967 p.group = mPermissionGroups.get(p.info.group); 5968 if (p.info.group == null || p.group != null) { 5969 BasePermission bp = permissionMap.get(p.info.name); 5970 if (bp == null) { 5971 bp = new BasePermission(p.info.name, p.info.packageName, 5972 BasePermission.TYPE_NORMAL); 5973 permissionMap.put(p.info.name, bp); 5974 } 5975 if (bp.perm == null) { 5976 if (bp.sourcePackage != null 5977 && !bp.sourcePackage.equals(p.info.packageName)) { 5978 // If this is a permission that was formerly defined by a non-system 5979 // app, but is now defined by a system app (following an upgrade), 5980 // discard the previous declaration and consider the system's to be 5981 // canonical. 5982 if (isSystemApp(p.owner)) { 5983 String msg = "New decl " + p.owner + " of permission " 5984 + p.info.name + " is system"; 5985 reportSettingsProblem(Log.WARN, msg); 5986 bp.sourcePackage = null; 5987 } 5988 } 5989 if (bp.sourcePackage == null 5990 || bp.sourcePackage.equals(p.info.packageName)) { 5991 BasePermission tree = findPermissionTreeLP(p.info.name); 5992 if (tree == null 5993 || tree.sourcePackage.equals(p.info.packageName)) { 5994 bp.packageSetting = pkgSetting; 5995 bp.perm = p; 5996 bp.uid = pkg.applicationInfo.uid; 5997 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5998 if (r == null) { 5999 r = new StringBuilder(256); 6000 } else { 6001 r.append(' '); 6002 } 6003 r.append(p.info.name); 6004 } 6005 } else { 6006 Slog.w(TAG, "Permission " + p.info.name + " from package " 6007 + p.info.packageName + " ignored: base tree " 6008 + tree.name + " is from package " 6009 + tree.sourcePackage); 6010 } 6011 } else { 6012 Slog.w(TAG, "Permission " + p.info.name + " from package " 6013 + p.info.packageName + " ignored: original from " 6014 + bp.sourcePackage); 6015 } 6016 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6017 if (r == null) { 6018 r = new StringBuilder(256); 6019 } else { 6020 r.append(' '); 6021 } 6022 r.append("DUP:"); 6023 r.append(p.info.name); 6024 } 6025 if (bp.perm == p) { 6026 bp.protectionLevel = p.info.protectionLevel; 6027 } 6028 } else { 6029 Slog.w(TAG, "Permission " + p.info.name + " from package " 6030 + p.info.packageName + " ignored: no group " 6031 + p.group); 6032 } 6033 } 6034 if (r != null) { 6035 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6036 } 6037 6038 N = pkg.instrumentation.size(); 6039 r = null; 6040 for (i=0; i<N; i++) { 6041 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6042 a.info.packageName = pkg.applicationInfo.packageName; 6043 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6044 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6045 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6046 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6047 a.info.dataDir = pkg.applicationInfo.dataDir; 6048 6049 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6050 // need other information about the application, like the ABI and what not ? 6051 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6052 mInstrumentation.put(a.getComponentName(), a); 6053 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6054 if (r == null) { 6055 r = new StringBuilder(256); 6056 } else { 6057 r.append(' '); 6058 } 6059 r.append(a.info.name); 6060 } 6061 } 6062 if (r != null) { 6063 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6064 } 6065 6066 if (pkg.protectedBroadcasts != null) { 6067 N = pkg.protectedBroadcasts.size(); 6068 for (i=0; i<N; i++) { 6069 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6070 } 6071 } 6072 6073 pkgSetting.setTimeStamp(scanFileTime); 6074 6075 // Create idmap files for pairs of (packages, overlay packages). 6076 // Note: "android", ie framework-res.apk, is handled by native layers. 6077 if (pkg.mOverlayTarget != null) { 6078 // This is an overlay package. 6079 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6080 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6081 mOverlays.put(pkg.mOverlayTarget, 6082 new HashMap<String, PackageParser.Package>()); 6083 } 6084 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6085 map.put(pkg.packageName, pkg); 6086 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6087 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6088 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6089 "scanPackageLI failed to createIdmap"); 6090 } 6091 } 6092 } else if (mOverlays.containsKey(pkg.packageName) && 6093 !pkg.packageName.equals("android")) { 6094 // This is a regular package, with one or more known overlay packages. 6095 createIdmapsForPackageLI(pkg); 6096 } 6097 } 6098 6099 return pkg; 6100 } 6101 6102 /** 6103 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6104 * i.e, so that all packages can be run inside a single process if required. 6105 * 6106 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6107 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6108 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6109 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6110 * updating a package that belongs to a shared user. 6111 * 6112 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6113 * adds unnecessary complexity. 6114 */ 6115 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6116 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6117 String requiredInstructionSet = null; 6118 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6119 requiredInstructionSet = VMRuntime.getInstructionSet( 6120 scannedPackage.applicationInfo.primaryCpuAbi); 6121 } 6122 6123 PackageSetting requirer = null; 6124 for (PackageSetting ps : packagesForUser) { 6125 // If packagesForUser contains scannedPackage, we skip it. This will happen 6126 // when scannedPackage is an update of an existing package. Without this check, 6127 // we will never be able to change the ABI of any package belonging to a shared 6128 // user, even if it's compatible with other packages. 6129 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6130 if (ps.primaryCpuAbiString == null) { 6131 continue; 6132 } 6133 6134 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6135 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6136 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6137 // this but there's not much we can do. 6138 String errorMessage = "Instruction set mismatch, " 6139 + ((requirer == null) ? "[caller]" : requirer) 6140 + " requires " + requiredInstructionSet + " whereas " + ps 6141 + " requires " + instructionSet; 6142 Slog.w(TAG, errorMessage); 6143 } 6144 6145 if (requiredInstructionSet == null) { 6146 requiredInstructionSet = instructionSet; 6147 requirer = ps; 6148 } 6149 } 6150 } 6151 6152 if (requiredInstructionSet != null) { 6153 String adjustedAbi; 6154 if (requirer != null) { 6155 // requirer != null implies that either scannedPackage was null or that scannedPackage 6156 // did not require an ABI, in which case we have to adjust scannedPackage to match 6157 // the ABI of the set (which is the same as requirer's ABI) 6158 adjustedAbi = requirer.primaryCpuAbiString; 6159 if (scannedPackage != null) { 6160 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6161 } 6162 } else { 6163 // requirer == null implies that we're updating all ABIs in the set to 6164 // match scannedPackage. 6165 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6166 } 6167 6168 for (PackageSetting ps : packagesForUser) { 6169 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6170 if (ps.primaryCpuAbiString != null) { 6171 continue; 6172 } 6173 6174 ps.primaryCpuAbiString = adjustedAbi; 6175 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6176 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6177 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6178 6179 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6180 deferDexOpt, true) == DEX_OPT_FAILED) { 6181 ps.primaryCpuAbiString = null; 6182 ps.pkg.applicationInfo.primaryCpuAbi = null; 6183 return; 6184 } else { 6185 mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet()); 6186 } 6187 } 6188 } 6189 } 6190 } 6191 } 6192 6193 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6194 synchronized (mPackages) { 6195 mResolverReplaced = true; 6196 // Set up information for custom user intent resolution activity. 6197 mResolveActivity.applicationInfo = pkg.applicationInfo; 6198 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6199 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6200 mResolveActivity.processName = null; 6201 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6202 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6203 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6204 mResolveActivity.theme = 0; 6205 mResolveActivity.exported = true; 6206 mResolveActivity.enabled = true; 6207 mResolveInfo.activityInfo = mResolveActivity; 6208 mResolveInfo.priority = 0; 6209 mResolveInfo.preferredOrder = 0; 6210 mResolveInfo.match = 0; 6211 mResolveComponentName = mCustomResolverComponentName; 6212 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6213 mResolveComponentName); 6214 } 6215 } 6216 6217 private static String calculateApkRoot(final String codePathString) { 6218 final File codePath = new File(codePathString); 6219 final File codeRoot; 6220 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6221 codeRoot = Environment.getRootDirectory(); 6222 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6223 codeRoot = Environment.getOemDirectory(); 6224 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6225 codeRoot = Environment.getVendorDirectory(); 6226 } else { 6227 // Unrecognized code path; take its top real segment as the apk root: 6228 // e.g. /something/app/blah.apk => /something 6229 try { 6230 File f = codePath.getCanonicalFile(); 6231 File parent = f.getParentFile(); // non-null because codePath is a file 6232 File tmp; 6233 while ((tmp = parent.getParentFile()) != null) { 6234 f = parent; 6235 parent = tmp; 6236 } 6237 codeRoot = f; 6238 Slog.w(TAG, "Unrecognized code path " 6239 + codePath + " - using " + codeRoot); 6240 } catch (IOException e) { 6241 // Can't canonicalize the code path -- shenanigans? 6242 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6243 return Environment.getRootDirectory().getPath(); 6244 } 6245 } 6246 return codeRoot.getPath(); 6247 } 6248 6249 /** 6250 * Derive and set the location of native libraries for the given package, 6251 * which varies depending on where and how the package was installed. 6252 */ 6253 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6254 final ApplicationInfo info = pkg.applicationInfo; 6255 final String codePath = pkg.codePath; 6256 final File codeFile = new File(codePath); 6257 // If "/system/lib64/apkname" exists, assume that is the per-package 6258 // native library directory to use; otherwise use "/system/lib/apkname". 6259 final String apkRoot = calculateApkRoot(info.sourceDir); 6260 6261 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6262 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6263 6264 6265 info.nativeLibraryRootDir = null; 6266 info.nativeLibraryRootRequiresIsa = false; 6267 info.nativeLibraryDir = null; 6268 info.secondaryNativeLibraryDir = null; 6269 6270 if (isApkFile(codeFile)) { 6271 // Monolithic install 6272 if (bundledApp) { 6273 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6274 getPrimaryInstructionSet(info)); 6275 6276 // This is a bundled system app so choose the path based on the ABI. 6277 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6278 // is just the default path. 6279 final String apkName = deriveCodePathName(codePath); 6280 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6281 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6282 apkName).getAbsolutePath(); 6283 6284 if (info.secondaryCpuAbi != null) { 6285 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6286 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6287 secondaryLibDir, apkName).getAbsolutePath(); 6288 } 6289 } else if (asecApp) { 6290 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6291 .getAbsolutePath(); 6292 } else { 6293 final String apkName = deriveCodePathName(codePath); 6294 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6295 .getAbsolutePath(); 6296 } 6297 6298 info.nativeLibraryRootRequiresIsa = false; 6299 info.nativeLibraryDir = info.nativeLibraryRootDir; 6300 } else { 6301 // Cluster install 6302 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6303 info.nativeLibraryRootRequiresIsa = true; 6304 6305 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6306 getPrimaryInstructionSet(info)).getAbsolutePath(); 6307 6308 if (info.secondaryCpuAbi != null) { 6309 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6310 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6311 } 6312 } 6313 } 6314 6315 /** 6316 * Calculate the abis and roots for a bundled app. These can uniquely 6317 * be determined from the contents of the system partition, i.e whether 6318 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6319 * of this information, and instead assume that the system was built 6320 * sensibly. 6321 */ 6322 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6323 PackageSetting pkgSetting) { 6324 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6325 6326 // If "/system/lib64/apkname" exists, assume that is the per-package 6327 // native library directory to use; otherwise use "/system/lib/apkname". 6328 final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6329 setBundledAppAbi(pkg, apkRoot, apkName); 6330 // pkgSetting might be null during rescan following uninstall of updates 6331 // to a bundled app, so accommodate that possibility. The settings in 6332 // that case will be established later from the parsed package. 6333 // 6334 // If the settings aren't null, sync them up with what we've just derived. 6335 // note that apkRoot isn't stored in the package settings. 6336 if (pkgSetting != null) { 6337 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6338 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6339 } 6340 } 6341 6342 /** 6343 * Deduces the ABI of a bundled app and sets the relevant fields on the 6344 * parsed pkg object. 6345 * 6346 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6347 * under which system libraries are installed. 6348 * @param apkName the name of the installed package. 6349 */ 6350 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6351 final File codeFile = new File(pkg.codePath); 6352 6353 final boolean has64BitLibs; 6354 final boolean has32BitLibs; 6355 if (isApkFile(codeFile)) { 6356 // Monolithic install 6357 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6358 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6359 } else { 6360 // Cluster install 6361 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6362 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6363 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6364 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6365 has64BitLibs = (new File(rootDir, isa)).exists(); 6366 } else { 6367 has64BitLibs = false; 6368 } 6369 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6370 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6371 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6372 has32BitLibs = (new File(rootDir, isa)).exists(); 6373 } else { 6374 has32BitLibs = false; 6375 } 6376 } 6377 6378 if (has64BitLibs && !has32BitLibs) { 6379 // The package has 64 bit libs, but not 32 bit libs. Its primary 6380 // ABI should be 64 bit. We can safely assume here that the bundled 6381 // native libraries correspond to the most preferred ABI in the list. 6382 6383 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6384 pkg.applicationInfo.secondaryCpuAbi = null; 6385 } else if (has32BitLibs && !has64BitLibs) { 6386 // The package has 32 bit libs but not 64 bit libs. Its primary 6387 // ABI should be 32 bit. 6388 6389 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6390 pkg.applicationInfo.secondaryCpuAbi = null; 6391 } else if (has32BitLibs && has64BitLibs) { 6392 // The application has both 64 and 32 bit bundled libraries. We check 6393 // here that the app declares multiArch support, and warn if it doesn't. 6394 // 6395 // We will be lenient here and record both ABIs. The primary will be the 6396 // ABI that's higher on the list, i.e, a device that's configured to prefer 6397 // 64 bit apps will see a 64 bit primary ABI, 6398 6399 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6400 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6401 } 6402 6403 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6404 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6405 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6406 } else { 6407 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6408 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6409 } 6410 } else { 6411 pkg.applicationInfo.primaryCpuAbi = null; 6412 pkg.applicationInfo.secondaryCpuAbi = null; 6413 } 6414 } 6415 6416 private static void createNativeLibrarySubdir(File path) throws IOException { 6417 if (!path.isDirectory()) { 6418 path.delete(); 6419 6420 if (!path.mkdir()) { 6421 throw new IOException("Cannot create " + path.getPath()); 6422 } 6423 6424 try { 6425 Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6426 } catch (ErrnoException e) { 6427 throw new IOException("Cannot chmod native library directory " 6428 + path.getPath(), e); 6429 } 6430 } else if (!SELinux.restorecon(path)) { 6431 throw new IOException("Cannot set SELinux context for " + path.getPath()); 6432 } 6433 } 6434 6435 private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle, 6436 final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException { 6437 createNativeLibrarySubdir(nativeLibraryRoot); 6438 6439 /* 6440 * If this is an internal application or our nativeLibraryPath points to 6441 * the app-lib directory, unpack the libraries if necessary. 6442 */ 6443 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6444 if (abi >= 0) { 6445 /* 6446 * If we have a matching instruction set, construct a subdir under the native 6447 * library root that corresponds to this instruction set. 6448 */ 6449 final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]); 6450 final File subDir; 6451 if (useIsaSubdir) { 6452 final File isaSubdir = new File(nativeLibraryRoot, instructionSet); 6453 createNativeLibrarySubdir(isaSubdir); 6454 subDir = isaSubdir; 6455 } else { 6456 subDir = nativeLibraryRoot; 6457 } 6458 6459 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, subDir, abiList[abi]); 6460 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6461 return copyRet; 6462 } 6463 } 6464 6465 return abi; 6466 } 6467 6468 private void killApplication(String pkgName, int appId, String reason) { 6469 // Request the ActivityManager to kill the process(only for existing packages) 6470 // so that we do not end up in a confused state while the user is still using the older 6471 // version of the application while the new one gets installed. 6472 IActivityManager am = ActivityManagerNative.getDefault(); 6473 if (am != null) { 6474 try { 6475 am.killApplicationWithAppId(pkgName, appId, reason); 6476 } catch (RemoteException e) { 6477 } 6478 } 6479 } 6480 6481 void removePackageLI(PackageSetting ps, boolean chatty) { 6482 if (DEBUG_INSTALL) { 6483 if (chatty) 6484 Log.d(TAG, "Removing package " + ps.name); 6485 } 6486 6487 // writer 6488 synchronized (mPackages) { 6489 mPackages.remove(ps.name); 6490 if (ps.codePathString != null) { 6491 mAppDirs.remove(ps.codePathString); 6492 } 6493 6494 final PackageParser.Package pkg = ps.pkg; 6495 if (pkg != null) { 6496 cleanPackageDataStructuresLILPw(pkg, chatty); 6497 } 6498 } 6499 } 6500 6501 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6502 if (DEBUG_INSTALL) { 6503 if (chatty) 6504 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6505 } 6506 6507 // writer 6508 synchronized (mPackages) { 6509 mPackages.remove(pkg.applicationInfo.packageName); 6510 if (pkg.codePath != null) { 6511 mAppDirs.remove(pkg.codePath); 6512 } 6513 cleanPackageDataStructuresLILPw(pkg, chatty); 6514 } 6515 } 6516 6517 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6518 int N = pkg.providers.size(); 6519 StringBuilder r = null; 6520 int i; 6521 for (i=0; i<N; i++) { 6522 PackageParser.Provider p = pkg.providers.get(i); 6523 mProviders.removeProvider(p); 6524 if (p.info.authority == null) { 6525 6526 /* There was another ContentProvider with this authority when 6527 * this app was installed so this authority is null, 6528 * Ignore it as we don't have to unregister the provider. 6529 */ 6530 continue; 6531 } 6532 String names[] = p.info.authority.split(";"); 6533 for (int j = 0; j < names.length; j++) { 6534 if (mProvidersByAuthority.get(names[j]) == p) { 6535 mProvidersByAuthority.remove(names[j]); 6536 if (DEBUG_REMOVE) { 6537 if (chatty) 6538 Log.d(TAG, "Unregistered content provider: " + names[j] 6539 + ", className = " + p.info.name + ", isSyncable = " 6540 + p.info.isSyncable); 6541 } 6542 } 6543 } 6544 if (DEBUG_REMOVE && chatty) { 6545 if (r == null) { 6546 r = new StringBuilder(256); 6547 } else { 6548 r.append(' '); 6549 } 6550 r.append(p.info.name); 6551 } 6552 } 6553 if (r != null) { 6554 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6555 } 6556 6557 N = pkg.services.size(); 6558 r = null; 6559 for (i=0; i<N; i++) { 6560 PackageParser.Service s = pkg.services.get(i); 6561 mServices.removeService(s); 6562 if (chatty) { 6563 if (r == null) { 6564 r = new StringBuilder(256); 6565 } else { 6566 r.append(' '); 6567 } 6568 r.append(s.info.name); 6569 } 6570 } 6571 if (r != null) { 6572 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6573 } 6574 6575 N = pkg.receivers.size(); 6576 r = null; 6577 for (i=0; i<N; i++) { 6578 PackageParser.Activity a = pkg.receivers.get(i); 6579 mReceivers.removeActivity(a, "receiver"); 6580 if (DEBUG_REMOVE && chatty) { 6581 if (r == null) { 6582 r = new StringBuilder(256); 6583 } else { 6584 r.append(' '); 6585 } 6586 r.append(a.info.name); 6587 } 6588 } 6589 if (r != null) { 6590 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6591 } 6592 6593 N = pkg.activities.size(); 6594 r = null; 6595 for (i=0; i<N; i++) { 6596 PackageParser.Activity a = pkg.activities.get(i); 6597 mActivities.removeActivity(a, "activity"); 6598 if (DEBUG_REMOVE && chatty) { 6599 if (r == null) { 6600 r = new StringBuilder(256); 6601 } else { 6602 r.append(' '); 6603 } 6604 r.append(a.info.name); 6605 } 6606 } 6607 if (r != null) { 6608 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6609 } 6610 6611 N = pkg.permissions.size(); 6612 r = null; 6613 for (i=0; i<N; i++) { 6614 PackageParser.Permission p = pkg.permissions.get(i); 6615 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6616 if (bp == null) { 6617 bp = mSettings.mPermissionTrees.get(p.info.name); 6618 } 6619 if (bp != null && bp.perm == p) { 6620 bp.perm = null; 6621 if (DEBUG_REMOVE && chatty) { 6622 if (r == null) { 6623 r = new StringBuilder(256); 6624 } else { 6625 r.append(' '); 6626 } 6627 r.append(p.info.name); 6628 } 6629 } 6630 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6631 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6632 if (appOpPerms != null) { 6633 appOpPerms.remove(pkg.packageName); 6634 } 6635 } 6636 } 6637 if (r != null) { 6638 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6639 } 6640 6641 N = pkg.requestedPermissions.size(); 6642 r = null; 6643 for (i=0; i<N; i++) { 6644 String perm = pkg.requestedPermissions.get(i); 6645 BasePermission bp = mSettings.mPermissions.get(perm); 6646 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6647 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6648 if (appOpPerms != null) { 6649 appOpPerms.remove(pkg.packageName); 6650 if (appOpPerms.isEmpty()) { 6651 mAppOpPermissionPackages.remove(perm); 6652 } 6653 } 6654 } 6655 } 6656 if (r != null) { 6657 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6658 } 6659 6660 N = pkg.instrumentation.size(); 6661 r = null; 6662 for (i=0; i<N; i++) { 6663 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6664 mInstrumentation.remove(a.getComponentName()); 6665 if (DEBUG_REMOVE && chatty) { 6666 if (r == null) { 6667 r = new StringBuilder(256); 6668 } else { 6669 r.append(' '); 6670 } 6671 r.append(a.info.name); 6672 } 6673 } 6674 if (r != null) { 6675 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6676 } 6677 6678 r = null; 6679 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6680 // Only system apps can hold shared libraries. 6681 if (pkg.libraryNames != null) { 6682 for (i=0; i<pkg.libraryNames.size(); i++) { 6683 String name = pkg.libraryNames.get(i); 6684 SharedLibraryEntry cur = mSharedLibraries.get(name); 6685 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6686 mSharedLibraries.remove(name); 6687 if (DEBUG_REMOVE && chatty) { 6688 if (r == null) { 6689 r = new StringBuilder(256); 6690 } else { 6691 r.append(' '); 6692 } 6693 r.append(name); 6694 } 6695 } 6696 } 6697 } 6698 } 6699 if (r != null) { 6700 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6701 } 6702 } 6703 6704 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6705 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6706 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6707 return true; 6708 } 6709 } 6710 return false; 6711 } 6712 6713 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6714 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6715 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6716 6717 private void updatePermissionsLPw(String changingPkg, 6718 PackageParser.Package pkgInfo, int flags) { 6719 // Make sure there are no dangling permission trees. 6720 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6721 while (it.hasNext()) { 6722 final BasePermission bp = it.next(); 6723 if (bp.packageSetting == null) { 6724 // We may not yet have parsed the package, so just see if 6725 // we still know about its settings. 6726 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6727 } 6728 if (bp.packageSetting == null) { 6729 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6730 + " from package " + bp.sourcePackage); 6731 it.remove(); 6732 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6733 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6734 Slog.i(TAG, "Removing old permission tree: " + bp.name 6735 + " from package " + bp.sourcePackage); 6736 flags |= UPDATE_PERMISSIONS_ALL; 6737 it.remove(); 6738 } 6739 } 6740 } 6741 6742 // Make sure all dynamic permissions have been assigned to a package, 6743 // and make sure there are no dangling permissions. 6744 it = mSettings.mPermissions.values().iterator(); 6745 while (it.hasNext()) { 6746 final BasePermission bp = it.next(); 6747 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6748 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6749 + bp.name + " pkg=" + bp.sourcePackage 6750 + " info=" + bp.pendingInfo); 6751 if (bp.packageSetting == null && bp.pendingInfo != null) { 6752 final BasePermission tree = findPermissionTreeLP(bp.name); 6753 if (tree != null && tree.perm != null) { 6754 bp.packageSetting = tree.packageSetting; 6755 bp.perm = new PackageParser.Permission(tree.perm.owner, 6756 new PermissionInfo(bp.pendingInfo)); 6757 bp.perm.info.packageName = tree.perm.info.packageName; 6758 bp.perm.info.name = bp.name; 6759 bp.uid = tree.uid; 6760 } 6761 } 6762 } 6763 if (bp.packageSetting == null) { 6764 // We may not yet have parsed the package, so just see if 6765 // we still know about its settings. 6766 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6767 } 6768 if (bp.packageSetting == null) { 6769 Slog.w(TAG, "Removing dangling permission: " + bp.name 6770 + " from package " + bp.sourcePackage); 6771 it.remove(); 6772 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6773 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6774 Slog.i(TAG, "Removing old permission: " + bp.name 6775 + " from package " + bp.sourcePackage); 6776 flags |= UPDATE_PERMISSIONS_ALL; 6777 it.remove(); 6778 } 6779 } 6780 } 6781 6782 // Now update the permissions for all packages, in particular 6783 // replace the granted permissions of the system packages. 6784 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6785 for (PackageParser.Package pkg : mPackages.values()) { 6786 if (pkg != pkgInfo) { 6787 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6788 } 6789 } 6790 } 6791 6792 if (pkgInfo != null) { 6793 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6794 } 6795 } 6796 6797 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6798 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6799 if (ps == null) { 6800 return; 6801 } 6802 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6803 HashSet<String> origPermissions = gp.grantedPermissions; 6804 boolean changedPermission = false; 6805 6806 if (replace) { 6807 ps.permissionsFixed = false; 6808 if (gp == ps) { 6809 origPermissions = new HashSet<String>(gp.grantedPermissions); 6810 gp.grantedPermissions.clear(); 6811 gp.gids = mGlobalGids; 6812 } 6813 } 6814 6815 if (gp.gids == null) { 6816 gp.gids = mGlobalGids; 6817 } 6818 6819 final int N = pkg.requestedPermissions.size(); 6820 for (int i=0; i<N; i++) { 6821 final String name = pkg.requestedPermissions.get(i); 6822 final boolean required = pkg.requestedPermissionsRequired.get(i); 6823 final BasePermission bp = mSettings.mPermissions.get(name); 6824 if (DEBUG_INSTALL) { 6825 if (gp != ps) { 6826 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6827 } 6828 } 6829 6830 if (bp == null || bp.packageSetting == null) { 6831 Slog.w(TAG, "Unknown permission " + name 6832 + " in package " + pkg.packageName); 6833 continue; 6834 } 6835 6836 final String perm = bp.name; 6837 boolean allowed; 6838 boolean allowedSig = false; 6839 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6840 // Keep track of app op permissions. 6841 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6842 if (pkgs == null) { 6843 pkgs = new ArraySet<>(); 6844 mAppOpPermissionPackages.put(bp.name, pkgs); 6845 } 6846 pkgs.add(pkg.packageName); 6847 } 6848 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6849 if (level == PermissionInfo.PROTECTION_NORMAL 6850 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6851 // We grant a normal or dangerous permission if any of the following 6852 // are true: 6853 // 1) The permission is required 6854 // 2) The permission is optional, but was granted in the past 6855 // 3) The permission is optional, but was requested by an 6856 // app in /system (not /data) 6857 // 6858 // Otherwise, reject the permission. 6859 allowed = (required || origPermissions.contains(perm) 6860 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6861 } else if (bp.packageSetting == null) { 6862 // This permission is invalid; skip it. 6863 allowed = false; 6864 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6865 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6866 if (allowed) { 6867 allowedSig = true; 6868 } 6869 } else { 6870 allowed = false; 6871 } 6872 if (DEBUG_INSTALL) { 6873 if (gp != ps) { 6874 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6875 } 6876 } 6877 if (allowed) { 6878 if (!isSystemApp(ps) && ps.permissionsFixed) { 6879 // If this is an existing, non-system package, then 6880 // we can't add any new permissions to it. 6881 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6882 // Except... if this is a permission that was added 6883 // to the platform (note: need to only do this when 6884 // updating the platform). 6885 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6886 } 6887 } 6888 if (allowed) { 6889 if (!gp.grantedPermissions.contains(perm)) { 6890 changedPermission = true; 6891 gp.grantedPermissions.add(perm); 6892 gp.gids = appendInts(gp.gids, bp.gids); 6893 } else if (!ps.haveGids) { 6894 gp.gids = appendInts(gp.gids, bp.gids); 6895 } 6896 } else { 6897 Slog.w(TAG, "Not granting permission " + perm 6898 + " to package " + pkg.packageName 6899 + " because it was previously installed without"); 6900 } 6901 } else { 6902 if (gp.grantedPermissions.remove(perm)) { 6903 changedPermission = true; 6904 gp.gids = removeInts(gp.gids, bp.gids); 6905 Slog.i(TAG, "Un-granting permission " + perm 6906 + " from package " + pkg.packageName 6907 + " (protectionLevel=" + bp.protectionLevel 6908 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6909 + ")"); 6910 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6911 // Don't print warning for app op permissions, since it is fine for them 6912 // not to be granted, there is a UI for the user to decide. 6913 Slog.w(TAG, "Not granting permission " + perm 6914 + " to package " + pkg.packageName 6915 + " (protectionLevel=" + bp.protectionLevel 6916 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6917 + ")"); 6918 } 6919 } 6920 } 6921 6922 if ((changedPermission || replace) && !ps.permissionsFixed && 6923 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6924 // This is the first that we have heard about this package, so the 6925 // permissions we have now selected are fixed until explicitly 6926 // changed. 6927 ps.permissionsFixed = true; 6928 } 6929 ps.haveGids = true; 6930 } 6931 6932 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6933 boolean allowed = false; 6934 final int NP = PackageParser.NEW_PERMISSIONS.length; 6935 for (int ip=0; ip<NP; ip++) { 6936 final PackageParser.NewPermissionInfo npi 6937 = PackageParser.NEW_PERMISSIONS[ip]; 6938 if (npi.name.equals(perm) 6939 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6940 allowed = true; 6941 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6942 + pkg.packageName); 6943 break; 6944 } 6945 } 6946 return allowed; 6947 } 6948 6949 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6950 BasePermission bp, HashSet<String> origPermissions) { 6951 boolean allowed; 6952 allowed = (compareSignatures( 6953 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6954 == PackageManager.SIGNATURE_MATCH) 6955 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6956 == PackageManager.SIGNATURE_MATCH); 6957 if (!allowed && (bp.protectionLevel 6958 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6959 if (isSystemApp(pkg)) { 6960 // For updated system applications, a system permission 6961 // is granted only if it had been defined by the original application. 6962 if (isUpdatedSystemApp(pkg)) { 6963 final PackageSetting sysPs = mSettings 6964 .getDisabledSystemPkgLPr(pkg.packageName); 6965 final GrantedPermissions origGp = sysPs.sharedUser != null 6966 ? sysPs.sharedUser : sysPs; 6967 6968 if (origGp.grantedPermissions.contains(perm)) { 6969 // If the original was granted this permission, we take 6970 // that grant decision as read and propagate it to the 6971 // update. 6972 allowed = true; 6973 } else { 6974 // The system apk may have been updated with an older 6975 // version of the one on the data partition, but which 6976 // granted a new system permission that it didn't have 6977 // before. In this case we do want to allow the app to 6978 // now get the new permission if the ancestral apk is 6979 // privileged to get it. 6980 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6981 for (int j=0; 6982 j<sysPs.pkg.requestedPermissions.size(); j++) { 6983 if (perm.equals( 6984 sysPs.pkg.requestedPermissions.get(j))) { 6985 allowed = true; 6986 break; 6987 } 6988 } 6989 } 6990 } 6991 } else { 6992 allowed = isPrivilegedApp(pkg); 6993 } 6994 } 6995 } 6996 if (!allowed && (bp.protectionLevel 6997 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6998 // For development permissions, a development permission 6999 // is granted only if it was already granted. 7000 allowed = origPermissions.contains(perm); 7001 } 7002 return allowed; 7003 } 7004 7005 final class ActivityIntentResolver 7006 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7007 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7008 boolean defaultOnly, int userId) { 7009 if (!sUserManager.exists(userId)) return null; 7010 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7011 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7012 } 7013 7014 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7015 int userId) { 7016 if (!sUserManager.exists(userId)) return null; 7017 mFlags = flags; 7018 return super.queryIntent(intent, resolvedType, 7019 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7020 } 7021 7022 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7023 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7024 if (!sUserManager.exists(userId)) return null; 7025 if (packageActivities == null) { 7026 return null; 7027 } 7028 mFlags = flags; 7029 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7030 final int N = packageActivities.size(); 7031 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7032 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7033 7034 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7035 for (int i = 0; i < N; ++i) { 7036 intentFilters = packageActivities.get(i).intents; 7037 if (intentFilters != null && intentFilters.size() > 0) { 7038 PackageParser.ActivityIntentInfo[] array = 7039 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7040 intentFilters.toArray(array); 7041 listCut.add(array); 7042 } 7043 } 7044 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7045 } 7046 7047 public final void addActivity(PackageParser.Activity a, String type) { 7048 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7049 mActivities.put(a.getComponentName(), a); 7050 if (DEBUG_SHOW_INFO) 7051 Log.v( 7052 TAG, " " + type + " " + 7053 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7054 if (DEBUG_SHOW_INFO) 7055 Log.v(TAG, " Class=" + a.info.name); 7056 final int NI = a.intents.size(); 7057 for (int j=0; j<NI; j++) { 7058 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7059 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7060 intent.setPriority(0); 7061 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7062 + a.className + " with priority > 0, forcing to 0"); 7063 } 7064 if (DEBUG_SHOW_INFO) { 7065 Log.v(TAG, " IntentFilter:"); 7066 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7067 } 7068 if (!intent.debugCheck()) { 7069 Log.w(TAG, "==> For Activity " + a.info.name); 7070 } 7071 addFilter(intent); 7072 } 7073 } 7074 7075 public final void removeActivity(PackageParser.Activity a, String type) { 7076 mActivities.remove(a.getComponentName()); 7077 if (DEBUG_SHOW_INFO) { 7078 Log.v(TAG, " " + type + " " 7079 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7080 : a.info.name) + ":"); 7081 Log.v(TAG, " Class=" + a.info.name); 7082 } 7083 final int NI = a.intents.size(); 7084 for (int j=0; j<NI; j++) { 7085 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7086 if (DEBUG_SHOW_INFO) { 7087 Log.v(TAG, " IntentFilter:"); 7088 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7089 } 7090 removeFilter(intent); 7091 } 7092 } 7093 7094 @Override 7095 protected boolean allowFilterResult( 7096 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7097 ActivityInfo filterAi = filter.activity.info; 7098 for (int i=dest.size()-1; i>=0; i--) { 7099 ActivityInfo destAi = dest.get(i).activityInfo; 7100 if (destAi.name == filterAi.name 7101 && destAi.packageName == filterAi.packageName) { 7102 return false; 7103 } 7104 } 7105 return true; 7106 } 7107 7108 @Override 7109 protected ActivityIntentInfo[] newArray(int size) { 7110 return new ActivityIntentInfo[size]; 7111 } 7112 7113 @Override 7114 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7115 if (!sUserManager.exists(userId)) return true; 7116 PackageParser.Package p = filter.activity.owner; 7117 if (p != null) { 7118 PackageSetting ps = (PackageSetting)p.mExtras; 7119 if (ps != null) { 7120 // System apps are never considered stopped for purposes of 7121 // filtering, because there may be no way for the user to 7122 // actually re-launch them. 7123 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7124 && ps.getStopped(userId); 7125 } 7126 } 7127 return false; 7128 } 7129 7130 @Override 7131 protected boolean isPackageForFilter(String packageName, 7132 PackageParser.ActivityIntentInfo info) { 7133 return packageName.equals(info.activity.owner.packageName); 7134 } 7135 7136 @Override 7137 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7138 int match, int userId) { 7139 if (!sUserManager.exists(userId)) return null; 7140 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7141 return null; 7142 } 7143 final PackageParser.Activity activity = info.activity; 7144 if (mSafeMode && (activity.info.applicationInfo.flags 7145 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7146 return null; 7147 } 7148 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7149 if (ps == null) { 7150 return null; 7151 } 7152 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7153 ps.readUserState(userId), userId); 7154 if (ai == null) { 7155 return null; 7156 } 7157 final ResolveInfo res = new ResolveInfo(); 7158 res.activityInfo = ai; 7159 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7160 res.filter = info; 7161 } 7162 res.priority = info.getPriority(); 7163 res.preferredOrder = activity.owner.mPreferredOrder; 7164 //System.out.println("Result: " + res.activityInfo.className + 7165 // " = " + res.priority); 7166 res.match = match; 7167 res.isDefault = info.hasDefault; 7168 res.labelRes = info.labelRes; 7169 res.nonLocalizedLabel = info.nonLocalizedLabel; 7170 if (userNeedsBadging(userId)) { 7171 res.noResourceId = true; 7172 } else { 7173 res.icon = info.icon; 7174 } 7175 res.system = isSystemApp(res.activityInfo.applicationInfo); 7176 return res; 7177 } 7178 7179 @Override 7180 protected void sortResults(List<ResolveInfo> results) { 7181 Collections.sort(results, mResolvePrioritySorter); 7182 } 7183 7184 @Override 7185 protected void dumpFilter(PrintWriter out, String prefix, 7186 PackageParser.ActivityIntentInfo filter) { 7187 out.print(prefix); out.print( 7188 Integer.toHexString(System.identityHashCode(filter.activity))); 7189 out.print(' '); 7190 filter.activity.printComponentShortName(out); 7191 out.print(" filter "); 7192 out.println(Integer.toHexString(System.identityHashCode(filter))); 7193 } 7194 7195// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7196// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7197// final List<ResolveInfo> retList = Lists.newArrayList(); 7198// while (i.hasNext()) { 7199// final ResolveInfo resolveInfo = i.next(); 7200// if (isEnabledLP(resolveInfo.activityInfo)) { 7201// retList.add(resolveInfo); 7202// } 7203// } 7204// return retList; 7205// } 7206 7207 // Keys are String (activity class name), values are Activity. 7208 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7209 = new HashMap<ComponentName, PackageParser.Activity>(); 7210 private int mFlags; 7211 } 7212 7213 private final class ServiceIntentResolver 7214 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7215 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7216 boolean defaultOnly, int userId) { 7217 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7218 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7219 } 7220 7221 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7222 int userId) { 7223 if (!sUserManager.exists(userId)) return null; 7224 mFlags = flags; 7225 return super.queryIntent(intent, resolvedType, 7226 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7227 } 7228 7229 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7230 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7231 if (!sUserManager.exists(userId)) return null; 7232 if (packageServices == null) { 7233 return null; 7234 } 7235 mFlags = flags; 7236 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7237 final int N = packageServices.size(); 7238 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7239 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7240 7241 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7242 for (int i = 0; i < N; ++i) { 7243 intentFilters = packageServices.get(i).intents; 7244 if (intentFilters != null && intentFilters.size() > 0) { 7245 PackageParser.ServiceIntentInfo[] array = 7246 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7247 intentFilters.toArray(array); 7248 listCut.add(array); 7249 } 7250 } 7251 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7252 } 7253 7254 public final void addService(PackageParser.Service s) { 7255 mServices.put(s.getComponentName(), s); 7256 if (DEBUG_SHOW_INFO) { 7257 Log.v(TAG, " " 7258 + (s.info.nonLocalizedLabel != null 7259 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7260 Log.v(TAG, " Class=" + s.info.name); 7261 } 7262 final int NI = s.intents.size(); 7263 int j; 7264 for (j=0; j<NI; j++) { 7265 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7266 if (DEBUG_SHOW_INFO) { 7267 Log.v(TAG, " IntentFilter:"); 7268 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7269 } 7270 if (!intent.debugCheck()) { 7271 Log.w(TAG, "==> For Service " + s.info.name); 7272 } 7273 addFilter(intent); 7274 } 7275 } 7276 7277 public final void removeService(PackageParser.Service s) { 7278 mServices.remove(s.getComponentName()); 7279 if (DEBUG_SHOW_INFO) { 7280 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7281 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7282 Log.v(TAG, " Class=" + s.info.name); 7283 } 7284 final int NI = s.intents.size(); 7285 int j; 7286 for (j=0; j<NI; j++) { 7287 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7288 if (DEBUG_SHOW_INFO) { 7289 Log.v(TAG, " IntentFilter:"); 7290 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7291 } 7292 removeFilter(intent); 7293 } 7294 } 7295 7296 @Override 7297 protected boolean allowFilterResult( 7298 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7299 ServiceInfo filterSi = filter.service.info; 7300 for (int i=dest.size()-1; i>=0; i--) { 7301 ServiceInfo destAi = dest.get(i).serviceInfo; 7302 if (destAi.name == filterSi.name 7303 && destAi.packageName == filterSi.packageName) { 7304 return false; 7305 } 7306 } 7307 return true; 7308 } 7309 7310 @Override 7311 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7312 return new PackageParser.ServiceIntentInfo[size]; 7313 } 7314 7315 @Override 7316 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7317 if (!sUserManager.exists(userId)) return true; 7318 PackageParser.Package p = filter.service.owner; 7319 if (p != null) { 7320 PackageSetting ps = (PackageSetting)p.mExtras; 7321 if (ps != null) { 7322 // System apps are never considered stopped for purposes of 7323 // filtering, because there may be no way for the user to 7324 // actually re-launch them. 7325 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7326 && ps.getStopped(userId); 7327 } 7328 } 7329 return false; 7330 } 7331 7332 @Override 7333 protected boolean isPackageForFilter(String packageName, 7334 PackageParser.ServiceIntentInfo info) { 7335 return packageName.equals(info.service.owner.packageName); 7336 } 7337 7338 @Override 7339 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7340 int match, int userId) { 7341 if (!sUserManager.exists(userId)) return null; 7342 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7343 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7344 return null; 7345 } 7346 final PackageParser.Service service = info.service; 7347 if (mSafeMode && (service.info.applicationInfo.flags 7348 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7349 return null; 7350 } 7351 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7352 if (ps == null) { 7353 return null; 7354 } 7355 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7356 ps.readUserState(userId), userId); 7357 if (si == null) { 7358 return null; 7359 } 7360 final ResolveInfo res = new ResolveInfo(); 7361 res.serviceInfo = si; 7362 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7363 res.filter = filter; 7364 } 7365 res.priority = info.getPriority(); 7366 res.preferredOrder = service.owner.mPreferredOrder; 7367 //System.out.println("Result: " + res.activityInfo.className + 7368 // " = " + res.priority); 7369 res.match = match; 7370 res.isDefault = info.hasDefault; 7371 res.labelRes = info.labelRes; 7372 res.nonLocalizedLabel = info.nonLocalizedLabel; 7373 res.icon = info.icon; 7374 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7375 return res; 7376 } 7377 7378 @Override 7379 protected void sortResults(List<ResolveInfo> results) { 7380 Collections.sort(results, mResolvePrioritySorter); 7381 } 7382 7383 @Override 7384 protected void dumpFilter(PrintWriter out, String prefix, 7385 PackageParser.ServiceIntentInfo filter) { 7386 out.print(prefix); out.print( 7387 Integer.toHexString(System.identityHashCode(filter.service))); 7388 out.print(' '); 7389 filter.service.printComponentShortName(out); 7390 out.print(" filter "); 7391 out.println(Integer.toHexString(System.identityHashCode(filter))); 7392 } 7393 7394// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7395// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7396// final List<ResolveInfo> retList = Lists.newArrayList(); 7397// while (i.hasNext()) { 7398// final ResolveInfo resolveInfo = (ResolveInfo) i; 7399// if (isEnabledLP(resolveInfo.serviceInfo)) { 7400// retList.add(resolveInfo); 7401// } 7402// } 7403// return retList; 7404// } 7405 7406 // Keys are String (activity class name), values are Activity. 7407 private final HashMap<ComponentName, PackageParser.Service> mServices 7408 = new HashMap<ComponentName, PackageParser.Service>(); 7409 private int mFlags; 7410 }; 7411 7412 private final class ProviderIntentResolver 7413 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7414 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7415 boolean defaultOnly, int userId) { 7416 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7417 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7418 } 7419 7420 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7421 int userId) { 7422 if (!sUserManager.exists(userId)) 7423 return null; 7424 mFlags = flags; 7425 return super.queryIntent(intent, resolvedType, 7426 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7427 } 7428 7429 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7430 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7431 if (!sUserManager.exists(userId)) 7432 return null; 7433 if (packageProviders == null) { 7434 return null; 7435 } 7436 mFlags = flags; 7437 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7438 final int N = packageProviders.size(); 7439 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7440 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7441 7442 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7443 for (int i = 0; i < N; ++i) { 7444 intentFilters = packageProviders.get(i).intents; 7445 if (intentFilters != null && intentFilters.size() > 0) { 7446 PackageParser.ProviderIntentInfo[] array = 7447 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7448 intentFilters.toArray(array); 7449 listCut.add(array); 7450 } 7451 } 7452 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7453 } 7454 7455 public final void addProvider(PackageParser.Provider p) { 7456 if (mProviders.containsKey(p.getComponentName())) { 7457 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7458 return; 7459 } 7460 7461 mProviders.put(p.getComponentName(), p); 7462 if (DEBUG_SHOW_INFO) { 7463 Log.v(TAG, " " 7464 + (p.info.nonLocalizedLabel != null 7465 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7466 Log.v(TAG, " Class=" + p.info.name); 7467 } 7468 final int NI = p.intents.size(); 7469 int j; 7470 for (j = 0; j < NI; j++) { 7471 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7472 if (DEBUG_SHOW_INFO) { 7473 Log.v(TAG, " IntentFilter:"); 7474 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7475 } 7476 if (!intent.debugCheck()) { 7477 Log.w(TAG, "==> For Provider " + p.info.name); 7478 } 7479 addFilter(intent); 7480 } 7481 } 7482 7483 public final void removeProvider(PackageParser.Provider p) { 7484 mProviders.remove(p.getComponentName()); 7485 if (DEBUG_SHOW_INFO) { 7486 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7487 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7488 Log.v(TAG, " Class=" + p.info.name); 7489 } 7490 final int NI = p.intents.size(); 7491 int j; 7492 for (j = 0; j < NI; j++) { 7493 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7494 if (DEBUG_SHOW_INFO) { 7495 Log.v(TAG, " IntentFilter:"); 7496 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7497 } 7498 removeFilter(intent); 7499 } 7500 } 7501 7502 @Override 7503 protected boolean allowFilterResult( 7504 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7505 ProviderInfo filterPi = filter.provider.info; 7506 for (int i = dest.size() - 1; i >= 0; i--) { 7507 ProviderInfo destPi = dest.get(i).providerInfo; 7508 if (destPi.name == filterPi.name 7509 && destPi.packageName == filterPi.packageName) { 7510 return false; 7511 } 7512 } 7513 return true; 7514 } 7515 7516 @Override 7517 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7518 return new PackageParser.ProviderIntentInfo[size]; 7519 } 7520 7521 @Override 7522 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7523 if (!sUserManager.exists(userId)) 7524 return true; 7525 PackageParser.Package p = filter.provider.owner; 7526 if (p != null) { 7527 PackageSetting ps = (PackageSetting) p.mExtras; 7528 if (ps != null) { 7529 // System apps are never considered stopped for purposes of 7530 // filtering, because there may be no way for the user to 7531 // actually re-launch them. 7532 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7533 && ps.getStopped(userId); 7534 } 7535 } 7536 return false; 7537 } 7538 7539 @Override 7540 protected boolean isPackageForFilter(String packageName, 7541 PackageParser.ProviderIntentInfo info) { 7542 return packageName.equals(info.provider.owner.packageName); 7543 } 7544 7545 @Override 7546 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7547 int match, int userId) { 7548 if (!sUserManager.exists(userId)) 7549 return null; 7550 final PackageParser.ProviderIntentInfo info = filter; 7551 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7552 return null; 7553 } 7554 final PackageParser.Provider provider = info.provider; 7555 if (mSafeMode && (provider.info.applicationInfo.flags 7556 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7557 return null; 7558 } 7559 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7560 if (ps == null) { 7561 return null; 7562 } 7563 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7564 ps.readUserState(userId), userId); 7565 if (pi == null) { 7566 return null; 7567 } 7568 final ResolveInfo res = new ResolveInfo(); 7569 res.providerInfo = pi; 7570 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7571 res.filter = filter; 7572 } 7573 res.priority = info.getPriority(); 7574 res.preferredOrder = provider.owner.mPreferredOrder; 7575 res.match = match; 7576 res.isDefault = info.hasDefault; 7577 res.labelRes = info.labelRes; 7578 res.nonLocalizedLabel = info.nonLocalizedLabel; 7579 res.icon = info.icon; 7580 res.system = isSystemApp(res.providerInfo.applicationInfo); 7581 return res; 7582 } 7583 7584 @Override 7585 protected void sortResults(List<ResolveInfo> results) { 7586 Collections.sort(results, mResolvePrioritySorter); 7587 } 7588 7589 @Override 7590 protected void dumpFilter(PrintWriter out, String prefix, 7591 PackageParser.ProviderIntentInfo filter) { 7592 out.print(prefix); 7593 out.print( 7594 Integer.toHexString(System.identityHashCode(filter.provider))); 7595 out.print(' '); 7596 filter.provider.printComponentShortName(out); 7597 out.print(" filter "); 7598 out.println(Integer.toHexString(System.identityHashCode(filter))); 7599 } 7600 7601 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7602 = new HashMap<ComponentName, PackageParser.Provider>(); 7603 private int mFlags; 7604 }; 7605 7606 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7607 new Comparator<ResolveInfo>() { 7608 public int compare(ResolveInfo r1, ResolveInfo r2) { 7609 int v1 = r1.priority; 7610 int v2 = r2.priority; 7611 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7612 if (v1 != v2) { 7613 return (v1 > v2) ? -1 : 1; 7614 } 7615 v1 = r1.preferredOrder; 7616 v2 = r2.preferredOrder; 7617 if (v1 != v2) { 7618 return (v1 > v2) ? -1 : 1; 7619 } 7620 if (r1.isDefault != r2.isDefault) { 7621 return r1.isDefault ? -1 : 1; 7622 } 7623 v1 = r1.match; 7624 v2 = r2.match; 7625 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7626 if (v1 != v2) { 7627 return (v1 > v2) ? -1 : 1; 7628 } 7629 if (r1.system != r2.system) { 7630 return r1.system ? -1 : 1; 7631 } 7632 return 0; 7633 } 7634 }; 7635 7636 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7637 new Comparator<ProviderInfo>() { 7638 public int compare(ProviderInfo p1, ProviderInfo p2) { 7639 final int v1 = p1.initOrder; 7640 final int v2 = p2.initOrder; 7641 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7642 } 7643 }; 7644 7645 static final void sendPackageBroadcast(String action, String pkg, 7646 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7647 int[] userIds) { 7648 IActivityManager am = ActivityManagerNative.getDefault(); 7649 if (am != null) { 7650 try { 7651 if (userIds == null) { 7652 userIds = am.getRunningUserIds(); 7653 } 7654 for (int id : userIds) { 7655 final Intent intent = new Intent(action, 7656 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7657 if (extras != null) { 7658 intent.putExtras(extras); 7659 } 7660 if (targetPkg != null) { 7661 intent.setPackage(targetPkg); 7662 } 7663 // Modify the UID when posting to other users 7664 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7665 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7666 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7667 intent.putExtra(Intent.EXTRA_UID, uid); 7668 } 7669 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7670 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7671 if (DEBUG_BROADCASTS) { 7672 RuntimeException here = new RuntimeException("here"); 7673 here.fillInStackTrace(); 7674 Slog.d(TAG, "Sending to user " + id + ": " 7675 + intent.toShortString(false, true, false, false) 7676 + " " + intent.getExtras(), here); 7677 } 7678 am.broadcastIntent(null, intent, null, finishedReceiver, 7679 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7680 finishedReceiver != null, false, id); 7681 } 7682 } catch (RemoteException ex) { 7683 } 7684 } 7685 } 7686 7687 /** 7688 * Check if the external storage media is available. This is true if there 7689 * is a mounted external storage medium or if the external storage is 7690 * emulated. 7691 */ 7692 private boolean isExternalMediaAvailable() { 7693 return mMediaMounted || Environment.isExternalStorageEmulated(); 7694 } 7695 7696 @Override 7697 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7698 // writer 7699 synchronized (mPackages) { 7700 if (!isExternalMediaAvailable()) { 7701 // If the external storage is no longer mounted at this point, 7702 // the caller may not have been able to delete all of this 7703 // packages files and can not delete any more. Bail. 7704 return null; 7705 } 7706 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7707 if (lastPackage != null) { 7708 pkgs.remove(lastPackage); 7709 } 7710 if (pkgs.size() > 0) { 7711 return pkgs.get(0); 7712 } 7713 } 7714 return null; 7715 } 7716 7717 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7718 if (false) { 7719 RuntimeException here = new RuntimeException("here"); 7720 here.fillInStackTrace(); 7721 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7722 + " andCode=" + andCode, here); 7723 } 7724 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7725 userId, andCode ? 1 : 0, packageName)); 7726 } 7727 7728 void startCleaningPackages() { 7729 // reader 7730 synchronized (mPackages) { 7731 if (!isExternalMediaAvailable()) { 7732 return; 7733 } 7734 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7735 return; 7736 } 7737 } 7738 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7739 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7740 IActivityManager am = ActivityManagerNative.getDefault(); 7741 if (am != null) { 7742 try { 7743 am.startService(null, intent, null, UserHandle.USER_OWNER); 7744 } catch (RemoteException e) { 7745 } 7746 } 7747 } 7748 7749 @Override 7750 public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags, 7751 String installerPackageName, VerificationParams verificationParams, 7752 String packageAbiOverride) { 7753 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7754 null); 7755 7756 final File originFile = new File(originPath); 7757 final int uid = Binder.getCallingUid(); 7758 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7759 try { 7760 if (observer != null) { 7761 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7762 } 7763 } catch (RemoteException re) { 7764 } 7765 return; 7766 } 7767 7768 UserHandle user; 7769 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7770 user = UserHandle.ALL; 7771 } else { 7772 user = new UserHandle(UserHandle.getUserId(uid)); 7773 } 7774 7775 final int filteredFlags; 7776 if (uid == Process.SHELL_UID || uid == 0) { 7777 if (DEBUG_INSTALL) { 7778 Slog.v(TAG, "Install from ADB"); 7779 } 7780 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7781 } else { 7782 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7783 } 7784 7785 verificationParams.setInstallerUid(uid); 7786 7787 final Message msg = mHandler.obtainMessage(INIT_COPY); 7788 msg.obj = new InstallParams(originFile, false, observer, filteredFlags, 7789 installerPackageName, verificationParams, user, packageAbiOverride); 7790 mHandler.sendMessage(msg); 7791 } 7792 7793 void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer, 7794 InstallSessionParams params, String installerPackageName, int installerUid, 7795 UserHandle user) { 7796 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7797 params.referrerUri, installerUid, null); 7798 7799 final Message msg = mHandler.obtainMessage(INIT_COPY); 7800 msg.obj = new InstallParams(stageDir, true, observer, params.installFlags, 7801 installerPackageName, verifParams, user, params.abiOverride); 7802 mHandler.sendMessage(msg); 7803 } 7804 7805 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7806 Bundle extras = new Bundle(1); 7807 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7808 7809 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7810 packageName, extras, null, null, new int[] {userId}); 7811 try { 7812 IActivityManager am = ActivityManagerNative.getDefault(); 7813 final boolean isSystem = 7814 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7815 if (isSystem && am.isUserRunning(userId, false)) { 7816 // The just-installed/enabled app is bundled on the system, so presumed 7817 // to be able to run automatically without needing an explicit launch. 7818 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7819 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7820 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7821 .setPackage(packageName); 7822 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7823 android.app.AppOpsManager.OP_NONE, false, false, userId); 7824 } 7825 } catch (RemoteException e) { 7826 // shouldn't happen 7827 Slog.w(TAG, "Unable to bootstrap installed package", e); 7828 } 7829 } 7830 7831 @Override 7832 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7833 int userId) { 7834 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7835 PackageSetting pkgSetting; 7836 final int uid = Binder.getCallingUid(); 7837 if (UserHandle.getUserId(uid) != userId) { 7838 mContext.enforceCallingOrSelfPermission( 7839 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7840 "setApplicationHiddenSetting for user " + userId); 7841 } 7842 7843 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7844 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7845 return false; 7846 } 7847 7848 long callingId = Binder.clearCallingIdentity(); 7849 try { 7850 boolean sendAdded = false; 7851 boolean sendRemoved = false; 7852 // writer 7853 synchronized (mPackages) { 7854 pkgSetting = mSettings.mPackages.get(packageName); 7855 if (pkgSetting == null) { 7856 return false; 7857 } 7858 if (pkgSetting.getHidden(userId) != hidden) { 7859 pkgSetting.setHidden(hidden, userId); 7860 mSettings.writePackageRestrictionsLPr(userId); 7861 if (hidden) { 7862 sendRemoved = true; 7863 } else { 7864 sendAdded = true; 7865 } 7866 } 7867 } 7868 if (sendAdded) { 7869 sendPackageAddedForUser(packageName, pkgSetting, userId); 7870 return true; 7871 } 7872 if (sendRemoved) { 7873 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7874 "hiding pkg"); 7875 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7876 } 7877 } finally { 7878 Binder.restoreCallingIdentity(callingId); 7879 } 7880 return false; 7881 } 7882 7883 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7884 int userId) { 7885 final PackageRemovedInfo info = new PackageRemovedInfo(); 7886 info.removedPackage = packageName; 7887 info.removedUsers = new int[] {userId}; 7888 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7889 info.sendBroadcast(false, false, false); 7890 } 7891 7892 /** 7893 * Returns true if application is not found or there was an error. Otherwise it returns 7894 * the hidden state of the package for the given user. 7895 */ 7896 @Override 7897 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 7898 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7899 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7900 "getApplicationHidden for user " + userId); 7901 PackageSetting pkgSetting; 7902 long callingId = Binder.clearCallingIdentity(); 7903 try { 7904 // writer 7905 synchronized (mPackages) { 7906 pkgSetting = mSettings.mPackages.get(packageName); 7907 if (pkgSetting == null) { 7908 return true; 7909 } 7910 return pkgSetting.getHidden(userId); 7911 } 7912 } finally { 7913 Binder.restoreCallingIdentity(callingId); 7914 } 7915 } 7916 7917 /** 7918 * @hide 7919 */ 7920 @Override 7921 public int installExistingPackageAsUser(String packageName, int userId) { 7922 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7923 null); 7924 PackageSetting pkgSetting; 7925 final int uid = Binder.getCallingUid(); 7926 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7927 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7928 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7929 } 7930 7931 long callingId = Binder.clearCallingIdentity(); 7932 try { 7933 boolean sendAdded = false; 7934 Bundle extras = new Bundle(1); 7935 7936 // writer 7937 synchronized (mPackages) { 7938 pkgSetting = mSettings.mPackages.get(packageName); 7939 if (pkgSetting == null) { 7940 return PackageManager.INSTALL_FAILED_INVALID_URI; 7941 } 7942 if (!pkgSetting.getInstalled(userId)) { 7943 pkgSetting.setInstalled(true, userId); 7944 pkgSetting.setHidden(false, userId); 7945 mSettings.writePackageRestrictionsLPr(userId); 7946 sendAdded = true; 7947 } 7948 } 7949 7950 if (sendAdded) { 7951 sendPackageAddedForUser(packageName, pkgSetting, userId); 7952 } 7953 } finally { 7954 Binder.restoreCallingIdentity(callingId); 7955 } 7956 7957 return PackageManager.INSTALL_SUCCEEDED; 7958 } 7959 7960 boolean isUserRestricted(int userId, String restrictionKey) { 7961 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7962 if (restrictions.getBoolean(restrictionKey, false)) { 7963 Log.w(TAG, "User is restricted: " + restrictionKey); 7964 return true; 7965 } 7966 return false; 7967 } 7968 7969 @Override 7970 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7971 mContext.enforceCallingOrSelfPermission( 7972 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7973 "Only package verification agents can verify applications"); 7974 7975 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7976 final PackageVerificationResponse response = new PackageVerificationResponse( 7977 verificationCode, Binder.getCallingUid()); 7978 msg.arg1 = id; 7979 msg.obj = response; 7980 mHandler.sendMessage(msg); 7981 } 7982 7983 @Override 7984 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7985 long millisecondsToDelay) { 7986 mContext.enforceCallingOrSelfPermission( 7987 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7988 "Only package verification agents can extend verification timeouts"); 7989 7990 final PackageVerificationState state = mPendingVerification.get(id); 7991 final PackageVerificationResponse response = new PackageVerificationResponse( 7992 verificationCodeAtTimeout, Binder.getCallingUid()); 7993 7994 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7995 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7996 } 7997 if (millisecondsToDelay < 0) { 7998 millisecondsToDelay = 0; 7999 } 8000 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8001 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8002 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8003 } 8004 8005 if ((state != null) && !state.timeoutExtended()) { 8006 state.extendTimeout(); 8007 8008 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8009 msg.arg1 = id; 8010 msg.obj = response; 8011 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8012 } 8013 } 8014 8015 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8016 int verificationCode, UserHandle user) { 8017 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8018 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8019 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8020 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8021 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8022 8023 mContext.sendBroadcastAsUser(intent, user, 8024 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8025 } 8026 8027 private ComponentName matchComponentForVerifier(String packageName, 8028 List<ResolveInfo> receivers) { 8029 ActivityInfo targetReceiver = null; 8030 8031 final int NR = receivers.size(); 8032 for (int i = 0; i < NR; i++) { 8033 final ResolveInfo info = receivers.get(i); 8034 if (info.activityInfo == null) { 8035 continue; 8036 } 8037 8038 if (packageName.equals(info.activityInfo.packageName)) { 8039 targetReceiver = info.activityInfo; 8040 break; 8041 } 8042 } 8043 8044 if (targetReceiver == null) { 8045 return null; 8046 } 8047 8048 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8049 } 8050 8051 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8052 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8053 if (pkgInfo.verifiers.length == 0) { 8054 return null; 8055 } 8056 8057 final int N = pkgInfo.verifiers.length; 8058 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8059 for (int i = 0; i < N; i++) { 8060 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8061 8062 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8063 receivers); 8064 if (comp == null) { 8065 continue; 8066 } 8067 8068 final int verifierUid = getUidForVerifier(verifierInfo); 8069 if (verifierUid == -1) { 8070 continue; 8071 } 8072 8073 if (DEBUG_VERIFY) { 8074 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8075 + " with the correct signature"); 8076 } 8077 sufficientVerifiers.add(comp); 8078 verificationState.addSufficientVerifier(verifierUid); 8079 } 8080 8081 return sufficientVerifiers; 8082 } 8083 8084 private int getUidForVerifier(VerifierInfo verifierInfo) { 8085 synchronized (mPackages) { 8086 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8087 if (pkg == null) { 8088 return -1; 8089 } else if (pkg.mSignatures.length != 1) { 8090 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8091 + " has more than one signature; ignoring"); 8092 return -1; 8093 } 8094 8095 /* 8096 * If the public key of the package's signature does not match 8097 * our expected public key, then this is a different package and 8098 * we should skip. 8099 */ 8100 8101 final byte[] expectedPublicKey; 8102 try { 8103 final Signature verifierSig = pkg.mSignatures[0]; 8104 final PublicKey publicKey = verifierSig.getPublicKey(); 8105 expectedPublicKey = publicKey.getEncoded(); 8106 } catch (CertificateException e) { 8107 return -1; 8108 } 8109 8110 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8111 8112 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8113 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8114 + " does not have the expected public key; ignoring"); 8115 return -1; 8116 } 8117 8118 return pkg.applicationInfo.uid; 8119 } 8120 } 8121 8122 @Override 8123 public void finishPackageInstall(int token) { 8124 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8125 8126 if (DEBUG_INSTALL) { 8127 Slog.v(TAG, "BM finishing package install for " + token); 8128 } 8129 8130 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8131 mHandler.sendMessage(msg); 8132 } 8133 8134 /** 8135 * Get the verification agent timeout. 8136 * 8137 * @return verification timeout in milliseconds 8138 */ 8139 private long getVerificationTimeout() { 8140 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8141 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8142 DEFAULT_VERIFICATION_TIMEOUT); 8143 } 8144 8145 /** 8146 * Get the default verification agent response code. 8147 * 8148 * @return default verification response code 8149 */ 8150 private int getDefaultVerificationResponse() { 8151 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8152 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8153 DEFAULT_VERIFICATION_RESPONSE); 8154 } 8155 8156 /** 8157 * Check whether or not package verification has been enabled. 8158 * 8159 * @return true if verification should be performed 8160 */ 8161 private boolean isVerificationEnabled(int userId, int flags) { 8162 if (!DEFAULT_VERIFY_ENABLE) { 8163 return false; 8164 } 8165 8166 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8167 8168 // Check if installing from ADB 8169 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8170 // Do not run verification in a test harness environment 8171 if (ActivityManager.isRunningInTestHarness()) { 8172 return false; 8173 } 8174 if (ensureVerifyAppsEnabled) { 8175 return true; 8176 } 8177 // Check if the developer does not want package verification for ADB installs 8178 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8179 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8180 return false; 8181 } 8182 } 8183 8184 if (ensureVerifyAppsEnabled) { 8185 return true; 8186 } 8187 8188 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8189 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8190 } 8191 8192 /** 8193 * Get the "allow unknown sources" setting. 8194 * 8195 * @return the current "allow unknown sources" setting 8196 */ 8197 private int getUnknownSourcesSettings() { 8198 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8199 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8200 -1); 8201 } 8202 8203 @Override 8204 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8205 final int uid = Binder.getCallingUid(); 8206 // writer 8207 synchronized (mPackages) { 8208 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8209 if (targetPackageSetting == null) { 8210 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8211 } 8212 8213 PackageSetting installerPackageSetting; 8214 if (installerPackageName != null) { 8215 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8216 if (installerPackageSetting == null) { 8217 throw new IllegalArgumentException("Unknown installer package: " 8218 + installerPackageName); 8219 } 8220 } else { 8221 installerPackageSetting = null; 8222 } 8223 8224 Signature[] callerSignature; 8225 Object obj = mSettings.getUserIdLPr(uid); 8226 if (obj != null) { 8227 if (obj instanceof SharedUserSetting) { 8228 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8229 } else if (obj instanceof PackageSetting) { 8230 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8231 } else { 8232 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8233 } 8234 } else { 8235 throw new SecurityException("Unknown calling uid " + uid); 8236 } 8237 8238 // Verify: can't set installerPackageName to a package that is 8239 // not signed with the same cert as the caller. 8240 if (installerPackageSetting != null) { 8241 if (compareSignatures(callerSignature, 8242 installerPackageSetting.signatures.mSignatures) 8243 != PackageManager.SIGNATURE_MATCH) { 8244 throw new SecurityException( 8245 "Caller does not have same cert as new installer package " 8246 + installerPackageName); 8247 } 8248 } 8249 8250 // Verify: if target already has an installer package, it must 8251 // be signed with the same cert as the caller. 8252 if (targetPackageSetting.installerPackageName != null) { 8253 PackageSetting setting = mSettings.mPackages.get( 8254 targetPackageSetting.installerPackageName); 8255 // If the currently set package isn't valid, then it's always 8256 // okay to change it. 8257 if (setting != null) { 8258 if (compareSignatures(callerSignature, 8259 setting.signatures.mSignatures) 8260 != PackageManager.SIGNATURE_MATCH) { 8261 throw new SecurityException( 8262 "Caller does not have same cert as old installer package " 8263 + targetPackageSetting.installerPackageName); 8264 } 8265 } 8266 } 8267 8268 // Okay! 8269 targetPackageSetting.installerPackageName = installerPackageName; 8270 scheduleWriteSettingsLocked(); 8271 } 8272 } 8273 8274 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8275 // Queue up an async operation since the package installation may take a little while. 8276 mHandler.post(new Runnable() { 8277 public void run() { 8278 mHandler.removeCallbacks(this); 8279 // Result object to be returned 8280 PackageInstalledInfo res = new PackageInstalledInfo(); 8281 res.returnCode = currentStatus; 8282 res.uid = -1; 8283 res.pkg = null; 8284 res.removedInfo = new PackageRemovedInfo(); 8285 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8286 args.doPreInstall(res.returnCode); 8287 synchronized (mInstallLock) { 8288 installPackageLI(args, true, res); 8289 } 8290 args.doPostInstall(res.returnCode, res.uid); 8291 } 8292 8293 // A restore should be performed at this point if (a) the install 8294 // succeeded, (b) the operation is not an update, and (c) the new 8295 // package has not opted out of backup participation. 8296 final boolean update = res.removedInfo.removedPackage != null; 8297 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8298 boolean doRestore = !update 8299 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8300 8301 // Set up the post-install work request bookkeeping. This will be used 8302 // and cleaned up by the post-install event handling regardless of whether 8303 // there's a restore pass performed. Token values are >= 1. 8304 int token; 8305 if (mNextInstallToken < 0) mNextInstallToken = 1; 8306 token = mNextInstallToken++; 8307 8308 PostInstallData data = new PostInstallData(args, res); 8309 mRunningInstalls.put(token, data); 8310 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8311 8312 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8313 // Pass responsibility to the Backup Manager. It will perform a 8314 // restore if appropriate, then pass responsibility back to the 8315 // Package Manager to run the post-install observer callbacks 8316 // and broadcasts. 8317 IBackupManager bm = IBackupManager.Stub.asInterface( 8318 ServiceManager.getService(Context.BACKUP_SERVICE)); 8319 if (bm != null) { 8320 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8321 + " to BM for possible restore"); 8322 try { 8323 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8324 } catch (RemoteException e) { 8325 // can't happen; the backup manager is local 8326 } catch (Exception e) { 8327 Slog.e(TAG, "Exception trying to enqueue restore", e); 8328 doRestore = false; 8329 } 8330 } else { 8331 Slog.e(TAG, "Backup Manager not found!"); 8332 doRestore = false; 8333 } 8334 } 8335 8336 if (!doRestore) { 8337 // No restore possible, or the Backup Manager was mysteriously not 8338 // available -- just fire the post-install work request directly. 8339 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8340 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8341 mHandler.sendMessage(msg); 8342 } 8343 } 8344 }); 8345 } 8346 8347 private abstract class HandlerParams { 8348 private static final int MAX_RETRIES = 4; 8349 8350 /** 8351 * Number of times startCopy() has been attempted and had a non-fatal 8352 * error. 8353 */ 8354 private int mRetries = 0; 8355 8356 /** User handle for the user requesting the information or installation. */ 8357 private final UserHandle mUser; 8358 8359 HandlerParams(UserHandle user) { 8360 mUser = user; 8361 } 8362 8363 UserHandle getUser() { 8364 return mUser; 8365 } 8366 8367 final boolean startCopy() { 8368 boolean res; 8369 try { 8370 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8371 8372 if (++mRetries > MAX_RETRIES) { 8373 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8374 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8375 handleServiceError(); 8376 return false; 8377 } else { 8378 handleStartCopy(); 8379 res = true; 8380 } 8381 } catch (RemoteException e) { 8382 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8383 mHandler.sendEmptyMessage(MCS_RECONNECT); 8384 res = false; 8385 } 8386 handleReturnCode(); 8387 return res; 8388 } 8389 8390 final void serviceError() { 8391 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8392 handleServiceError(); 8393 handleReturnCode(); 8394 } 8395 8396 abstract void handleStartCopy() throws RemoteException; 8397 abstract void handleServiceError(); 8398 abstract void handleReturnCode(); 8399 } 8400 8401 class MeasureParams extends HandlerParams { 8402 private final PackageStats mStats; 8403 private boolean mSuccess; 8404 8405 private final IPackageStatsObserver mObserver; 8406 8407 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8408 super(new UserHandle(stats.userHandle)); 8409 mObserver = observer; 8410 mStats = stats; 8411 } 8412 8413 @Override 8414 public String toString() { 8415 return "MeasureParams{" 8416 + Integer.toHexString(System.identityHashCode(this)) 8417 + " " + mStats.packageName + "}"; 8418 } 8419 8420 @Override 8421 void handleStartCopy() throws RemoteException { 8422 synchronized (mInstallLock) { 8423 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8424 } 8425 8426 if (mSuccess) { 8427 final boolean mounted; 8428 if (Environment.isExternalStorageEmulated()) { 8429 mounted = true; 8430 } else { 8431 final String status = Environment.getExternalStorageState(); 8432 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8433 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8434 } 8435 8436 if (mounted) { 8437 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8438 8439 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8440 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8441 8442 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8443 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8444 8445 // Always subtract cache size, since it's a subdirectory 8446 mStats.externalDataSize -= mStats.externalCacheSize; 8447 8448 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8449 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8450 8451 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8452 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8453 } 8454 } 8455 } 8456 8457 @Override 8458 void handleReturnCode() { 8459 if (mObserver != null) { 8460 try { 8461 mObserver.onGetStatsCompleted(mStats, mSuccess); 8462 } catch (RemoteException e) { 8463 Slog.i(TAG, "Observer no longer exists."); 8464 } 8465 } 8466 } 8467 8468 @Override 8469 void handleServiceError() { 8470 Slog.e(TAG, "Could not measure application " + mStats.packageName 8471 + " external storage"); 8472 } 8473 } 8474 8475 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8476 throws RemoteException { 8477 long result = 0; 8478 for (File path : paths) { 8479 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8480 } 8481 return result; 8482 } 8483 8484 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8485 for (File path : paths) { 8486 try { 8487 mcs.clearDirectory(path.getAbsolutePath()); 8488 } catch (RemoteException e) { 8489 } 8490 } 8491 } 8492 8493 class InstallParams extends HandlerParams { 8494 /** 8495 * Location where install is coming from, before it has been 8496 * copied/renamed into place. This could be a single monolithic APK 8497 * file, or a cluster directory. This location may be untrusted. 8498 */ 8499 final File originFile; 8500 8501 /** 8502 * Flag indicating that {@link #originFile} has already been staged, 8503 * meaning downstream users don't need to defensively copy the contents. 8504 */ 8505 boolean originStaged; 8506 8507 final IPackageInstallObserver2 observer; 8508 int flags; 8509 final String installerPackageName; 8510 final VerificationParams verificationParams; 8511 private InstallArgs mArgs; 8512 private int mRet; 8513 final String packageAbiOverride; 8514 boolean multiArch; 8515 8516 InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 8517 int flags, String installerPackageName, VerificationParams verificationParams, 8518 UserHandle user, String packageAbiOverride) { 8519 super(user); 8520 this.originFile = Preconditions.checkNotNull(originFile); 8521 this.originStaged = originStaged; 8522 this.observer = observer; 8523 this.flags = flags; 8524 this.installerPackageName = installerPackageName; 8525 this.verificationParams = verificationParams; 8526 this.packageAbiOverride = packageAbiOverride; 8527 } 8528 8529 @Override 8530 public String toString() { 8531 return "InstallParams{" 8532 + Integer.toHexString(System.identityHashCode(this)) 8533 + " " + originFile + "}"; 8534 } 8535 8536 public ManifestDigest getManifestDigest() { 8537 if (verificationParams == null) { 8538 return null; 8539 } 8540 return verificationParams.getManifestDigest(); 8541 } 8542 8543 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8544 String packageName = pkgLite.packageName; 8545 int installLocation = pkgLite.installLocation; 8546 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8547 // reader 8548 synchronized (mPackages) { 8549 PackageParser.Package pkg = mPackages.get(packageName); 8550 if (pkg != null) { 8551 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8552 // Check for downgrading. 8553 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8554 if (pkgLite.versionCode < pkg.mVersionCode) { 8555 Slog.w(TAG, "Can't install update of " + packageName 8556 + " update version " + pkgLite.versionCode 8557 + " is older than installed version " 8558 + pkg.mVersionCode); 8559 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8560 } 8561 } 8562 // Check for updated system application. 8563 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8564 if (onSd) { 8565 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8566 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8567 } 8568 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8569 } else { 8570 if (onSd) { 8571 // Install flag overrides everything. 8572 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8573 } 8574 // If current upgrade specifies particular preference 8575 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8576 // Application explicitly specified internal. 8577 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8578 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8579 // App explictly prefers external. Let policy decide 8580 } else { 8581 // Prefer previous location 8582 if (isExternal(pkg)) { 8583 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8584 } 8585 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8586 } 8587 } 8588 } else { 8589 // Invalid install. Return error code 8590 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8591 } 8592 } 8593 } 8594 // All the special cases have been taken care of. 8595 // Return result based on recommended install location. 8596 if (onSd) { 8597 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8598 } 8599 return pkgLite.recommendedInstallLocation; 8600 } 8601 8602 private long getMemoryLowThreshold() { 8603 final DeviceStorageMonitorInternal 8604 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8605 if (dsm == null) { 8606 return 0L; 8607 } 8608 return dsm.getMemoryLowThreshold(); 8609 } 8610 8611 /* 8612 * Invoke remote method to get package information and install 8613 * location values. Override install location based on default 8614 * policy if needed and then create install arguments based 8615 * on the install location. 8616 */ 8617 public void handleStartCopy() throws RemoteException { 8618 int ret = PackageManager.INSTALL_SUCCEEDED; 8619 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8620 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8621 PackageInfoLite pkgLite = null; 8622 8623 if (onInt && onSd) { 8624 // Check if both bits are set. 8625 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8626 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8627 } else { 8628 final long lowThreshold = getMemoryLowThreshold(); 8629 if (lowThreshold == 0L) { 8630 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8631 } 8632 8633 // Remote call to find out default install location 8634 final String originPath = originFile.getAbsolutePath(); 8635 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold, 8636 packageAbiOverride); 8637 // Keep track of whether this package is a multiArch package until 8638 // we perform a full scan of it. We need to do this because we might 8639 // end up extracting the package shared libraries before we perform 8640 // a full scan. 8641 multiArch = pkgLite.multiArch; 8642 8643 /* 8644 * If we have too little free space, try to free cache 8645 * before giving up. 8646 */ 8647 if (pkgLite.recommendedInstallLocation 8648 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8649 final long size = mContainerService.calculateInstalledSize( 8650 originPath, isForwardLocked(), packageAbiOverride); 8651 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8652 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, 8653 lowThreshold, packageAbiOverride); 8654 } 8655 /* 8656 * The cache free must have deleted the file we 8657 * downloaded to install. 8658 * 8659 * TODO: fix the "freeCache" call to not delete 8660 * the file we care about. 8661 */ 8662 if (pkgLite.recommendedInstallLocation 8663 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8664 pkgLite.recommendedInstallLocation 8665 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8666 } 8667 } 8668 } 8669 8670 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8671 int loc = pkgLite.recommendedInstallLocation; 8672 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8673 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8674 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8675 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8676 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8677 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8678 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8679 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8680 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8681 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8682 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8683 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8684 } else { 8685 // Override with defaults if needed. 8686 loc = installLocationPolicy(pkgLite, flags); 8687 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8688 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8689 } else if (!onSd && !onInt) { 8690 // Override install location with flags 8691 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8692 // Set the flag to install on external media. 8693 flags |= PackageManager.INSTALL_EXTERNAL; 8694 flags &= ~PackageManager.INSTALL_INTERNAL; 8695 } else { 8696 // Make sure the flag for installing on external 8697 // media is unset 8698 flags |= PackageManager.INSTALL_INTERNAL; 8699 flags &= ~PackageManager.INSTALL_EXTERNAL; 8700 } 8701 } 8702 } 8703 } 8704 8705 final InstallArgs args = createInstallArgs(this); 8706 mArgs = args; 8707 8708 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8709 /* 8710 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8711 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8712 */ 8713 int userIdentifier = getUser().getIdentifier(); 8714 if (userIdentifier == UserHandle.USER_ALL 8715 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8716 userIdentifier = UserHandle.USER_OWNER; 8717 } 8718 8719 /* 8720 * Determine if we have any installed package verifiers. If we 8721 * do, then we'll defer to them to verify the packages. 8722 */ 8723 final int requiredUid = mRequiredVerifierPackage == null ? -1 8724 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8725 if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) { 8726 // TODO: send verifier the install session instead of uri 8727 final Intent verification = new Intent( 8728 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8729 verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE); 8730 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8731 8732 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8733 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8734 0 /* TODO: Which userId? */); 8735 8736 if (DEBUG_VERIFY) { 8737 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8738 + verification.toString() + " with " + pkgLite.verifiers.length 8739 + " optional verifiers"); 8740 } 8741 8742 final int verificationId = mPendingVerificationToken++; 8743 8744 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8745 8746 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8747 installerPackageName); 8748 8749 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8750 8751 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8752 pkgLite.packageName); 8753 8754 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8755 pkgLite.versionCode); 8756 8757 if (verificationParams != null) { 8758 if (verificationParams.getVerificationURI() != null) { 8759 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8760 verificationParams.getVerificationURI()); 8761 } 8762 if (verificationParams.getOriginatingURI() != null) { 8763 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8764 verificationParams.getOriginatingURI()); 8765 } 8766 if (verificationParams.getReferrer() != null) { 8767 verification.putExtra(Intent.EXTRA_REFERRER, 8768 verificationParams.getReferrer()); 8769 } 8770 if (verificationParams.getOriginatingUid() >= 0) { 8771 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8772 verificationParams.getOriginatingUid()); 8773 } 8774 if (verificationParams.getInstallerUid() >= 0) { 8775 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8776 verificationParams.getInstallerUid()); 8777 } 8778 } 8779 8780 final PackageVerificationState verificationState = new PackageVerificationState( 8781 requiredUid, args); 8782 8783 mPendingVerification.append(verificationId, verificationState); 8784 8785 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8786 receivers, verificationState); 8787 8788 /* 8789 * If any sufficient verifiers were listed in the package 8790 * manifest, attempt to ask them. 8791 */ 8792 if (sufficientVerifiers != null) { 8793 final int N = sufficientVerifiers.size(); 8794 if (N == 0) { 8795 Slog.i(TAG, "Additional verifiers required, but none installed."); 8796 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8797 } else { 8798 for (int i = 0; i < N; i++) { 8799 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8800 8801 final Intent sufficientIntent = new Intent(verification); 8802 sufficientIntent.setComponent(verifierComponent); 8803 8804 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8805 } 8806 } 8807 } 8808 8809 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8810 mRequiredVerifierPackage, receivers); 8811 if (ret == PackageManager.INSTALL_SUCCEEDED 8812 && mRequiredVerifierPackage != null) { 8813 /* 8814 * Send the intent to the required verification agent, 8815 * but only start the verification timeout after the 8816 * target BroadcastReceivers have run. 8817 */ 8818 verification.setComponent(requiredVerifierComponent); 8819 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8820 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8821 new BroadcastReceiver() { 8822 @Override 8823 public void onReceive(Context context, Intent intent) { 8824 final Message msg = mHandler 8825 .obtainMessage(CHECK_PENDING_VERIFICATION); 8826 msg.arg1 = verificationId; 8827 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8828 } 8829 }, null, 0, null, null); 8830 8831 /* 8832 * We don't want the copy to proceed until verification 8833 * succeeds, so null out this field. 8834 */ 8835 mArgs = null; 8836 } 8837 } else { 8838 /* 8839 * No package verification is enabled, so immediately start 8840 * the remote call to initiate copy using temporary file. 8841 */ 8842 ret = args.copyApk(mContainerService, true); 8843 } 8844 } 8845 8846 mRet = ret; 8847 } 8848 8849 @Override 8850 void handleReturnCode() { 8851 // If mArgs is null, then MCS couldn't be reached. When it 8852 // reconnects, it will try again to install. At that point, this 8853 // will succeed. 8854 if (mArgs != null) { 8855 processPendingInstall(mArgs, mRet); 8856 } 8857 } 8858 8859 @Override 8860 void handleServiceError() { 8861 mArgs = createInstallArgs(this); 8862 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8863 } 8864 8865 public boolean isForwardLocked() { 8866 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8867 } 8868 } 8869 8870 /* 8871 * Utility class used in movePackage api. 8872 * srcArgs and targetArgs are not set for invalid flags and make 8873 * sure to do null checks when invoking methods on them. 8874 * We probably want to return ErrorPrams for both failed installs 8875 * and moves. 8876 */ 8877 class MoveParams extends HandlerParams { 8878 final IPackageMoveObserver observer; 8879 final int flags; 8880 final String packageName; 8881 final InstallArgs srcArgs; 8882 final InstallArgs targetArgs; 8883 int uid; 8884 int mRet; 8885 8886 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8887 String packageName, String[] instructionSets, int uid, UserHandle user, 8888 boolean isMultiArch) { 8889 super(user); 8890 this.srcArgs = srcArgs; 8891 this.observer = observer; 8892 this.flags = flags; 8893 this.packageName = packageName; 8894 this.uid = uid; 8895 if (srcArgs != null) { 8896 final String codePath = srcArgs.getCodePath(); 8897 targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, 8898 instructionSets, isMultiArch); 8899 } else { 8900 targetArgs = null; 8901 } 8902 } 8903 8904 @Override 8905 public String toString() { 8906 return "MoveParams{" 8907 + Integer.toHexString(System.identityHashCode(this)) 8908 + " " + packageName + "}"; 8909 } 8910 8911 public void handleStartCopy() throws RemoteException { 8912 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8913 // Check for storage space on target medium 8914 if (!targetArgs.checkFreeStorage(mContainerService)) { 8915 Log.w(TAG, "Insufficient storage to install"); 8916 return; 8917 } 8918 8919 mRet = srcArgs.doPreCopy(); 8920 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8921 return; 8922 } 8923 8924 mRet = targetArgs.copyApk(mContainerService, false); 8925 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8926 srcArgs.doPostCopy(uid); 8927 return; 8928 } 8929 8930 mRet = srcArgs.doPostCopy(uid); 8931 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8932 return; 8933 } 8934 8935 mRet = targetArgs.doPreInstall(mRet); 8936 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8937 return; 8938 } 8939 8940 if (DEBUG_SD_INSTALL) { 8941 StringBuilder builder = new StringBuilder(); 8942 if (srcArgs != null) { 8943 builder.append("src: "); 8944 builder.append(srcArgs.getCodePath()); 8945 } 8946 if (targetArgs != null) { 8947 builder.append(" target : "); 8948 builder.append(targetArgs.getCodePath()); 8949 } 8950 Log.i(TAG, builder.toString()); 8951 } 8952 } 8953 8954 @Override 8955 void handleReturnCode() { 8956 targetArgs.doPostInstall(mRet, uid); 8957 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8958 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8959 currentStatus = PackageManager.MOVE_SUCCEEDED; 8960 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8961 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8962 } 8963 processPendingMove(this, currentStatus); 8964 } 8965 8966 @Override 8967 void handleServiceError() { 8968 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8969 } 8970 } 8971 8972 /** 8973 * Used during creation of InstallArgs 8974 * 8975 * @param flags package installation flags 8976 * @return true if should be installed on external storage 8977 */ 8978 private static boolean installOnSd(int flags) { 8979 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8980 return false; 8981 } 8982 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8983 return true; 8984 } 8985 return false; 8986 } 8987 8988 /** 8989 * Used during creation of InstallArgs 8990 * 8991 * @param flags package installation flags 8992 * @return true if should be installed as forward locked 8993 */ 8994 private static boolean installForwardLocked(int flags) { 8995 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8996 } 8997 8998 private InstallArgs createInstallArgs(InstallParams params) { 8999 // TODO: extend to support incoming zero-copy locations 9000 9001 if (installOnSd(params.flags) || params.isForwardLocked()) { 9002 return new AsecInstallArgs(params); 9003 } else { 9004 return new FileInstallArgs(params); 9005 } 9006 } 9007 9008 /** 9009 * Create args that describe an existing installed package. Typically used 9010 * when cleaning up old installs, or used as a move source. 9011 */ 9012 private InstallArgs createInstallArgsForExisting(int flags, String codePath, 9013 String resourcePath, String nativeLibraryRoot, String[] instructionSets, 9014 boolean isMultiArch) { 9015 final boolean isInAsec; 9016 if (installOnSd(flags)) { 9017 /* Apps on SD card are always in ASEC containers. */ 9018 isInAsec = true; 9019 } else if (installForwardLocked(flags) 9020 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9021 /* 9022 * Forward-locked apps are only in ASEC containers if they're the 9023 * new style 9024 */ 9025 isInAsec = true; 9026 } else { 9027 isInAsec = false; 9028 } 9029 9030 if (isInAsec) { 9031 return new AsecInstallArgs(codePath, instructionSets, 9032 installOnSd(flags), installForwardLocked(flags), isMultiArch); 9033 } else { 9034 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9035 instructionSets, isMultiArch); 9036 } 9037 } 9038 9039 private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName, 9040 String[] instructionSets, boolean isMultiArch) { 9041 final File codeFile = new File(codePath); 9042 if (installOnSd(flags) || installForwardLocked(flags)) { 9043 String cid = getNextCodePath(codePath, pkgName, "/" 9044 + AsecInstallArgs.RES_FILE_NAME); 9045 return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags), 9046 installForwardLocked(flags), isMultiArch); 9047 } else { 9048 return new FileInstallArgs(codeFile, instructionSets, isMultiArch); 9049 } 9050 } 9051 9052 static abstract class InstallArgs { 9053 /** @see InstallParams#originFile */ 9054 final File originFile; 9055 /** @see InstallParams#originStaged */ 9056 final boolean originStaged; 9057 9058 // TODO: define inherit location 9059 9060 final IPackageInstallObserver2 observer; 9061 // Always refers to PackageManager flags only 9062 final int flags; 9063 final String installerPackageName; 9064 final ManifestDigest manifestDigest; 9065 final UserHandle user; 9066 final String abiOverride; 9067 final boolean multiArch; 9068 9069 // The list of instruction sets supported by this app. This is currently 9070 // only used during the rmdex() phase to clean up resources. We can get rid of this 9071 // if we move dex files under the common app path. 9072 /* nullable */ String[] instructionSets; 9073 9074 InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 9075 int flags, String installerPackageName, ManifestDigest manifestDigest, 9076 UserHandle user, String[] instructionSets, 9077 String abiOverride, boolean multiArch) { 9078 this.originFile = originFile; 9079 this.originStaged = originStaged; 9080 this.flags = flags; 9081 this.observer = observer; 9082 this.installerPackageName = installerPackageName; 9083 this.manifestDigest = manifestDigest; 9084 this.user = user; 9085 this.instructionSets = instructionSets; 9086 this.abiOverride = abiOverride; 9087 this.multiArch = multiArch; 9088 } 9089 9090 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9091 abstract int doPreInstall(int status); 9092 9093 /** 9094 * Rename package into final resting place. All paths on the given 9095 * scanned package should be updated to reflect the rename. 9096 */ 9097 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9098 abstract int doPostInstall(int status, int uid); 9099 9100 /** @see PackageSettingBase#codePathString */ 9101 abstract String getCodePath(); 9102 /** @see PackageSettingBase#resourcePathString */ 9103 abstract String getResourcePath(); 9104 abstract String getLegacyNativeLibraryPath(); 9105 9106 // Need installer lock especially for dex file removal. 9107 abstract void cleanUpResourcesLI(); 9108 abstract boolean doPostDeleteLI(boolean delete); 9109 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9110 9111 /** 9112 * Called before the source arguments are copied. This is used mostly 9113 * for MoveParams when it needs to read the source file to put it in the 9114 * destination. 9115 */ 9116 int doPreCopy() { 9117 return PackageManager.INSTALL_SUCCEEDED; 9118 } 9119 9120 /** 9121 * Called after the source arguments are copied. This is used mostly for 9122 * MoveParams when it needs to read the source file to put it in the 9123 * destination. 9124 * 9125 * @return 9126 */ 9127 int doPostCopy(int uid) { 9128 return PackageManager.INSTALL_SUCCEEDED; 9129 } 9130 9131 protected boolean isFwdLocked() { 9132 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9133 } 9134 9135 UserHandle getUser() { 9136 return user; 9137 } 9138 } 9139 9140 /** 9141 * Logic to handle installation of non-ASEC applications, including copying 9142 * and renaming logic. 9143 */ 9144 class FileInstallArgs extends InstallArgs { 9145 private File codeFile; 9146 private File resourceFile; 9147 private File legacyNativeLibraryPath; 9148 9149 // Example topology: 9150 // /data/app/com.example/base.apk 9151 // /data/app/com.example/split_foo.apk 9152 // /data/app/com.example/lib/arm/libfoo.so 9153 // /data/app/com.example/lib/arm64/libfoo.so 9154 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9155 9156 /** New install */ 9157 FileInstallArgs(InstallParams params) { 9158 super(params.originFile, params.originStaged, params.observer, params.flags, 9159 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9160 null /* instruction sets */, params.packageAbiOverride, 9161 params.multiArch); 9162 if (isFwdLocked()) { 9163 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9164 } 9165 } 9166 9167 /** Existing install */ 9168 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9169 String[] instructionSets, boolean isMultiArch) { 9170 super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch); 9171 this.codeFile = (codePath != null) ? new File(codePath) : null; 9172 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9173 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9174 new File(legacyNativeLibraryPath) : null; 9175 } 9176 9177 /** New install from existing */ 9178 FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) { 9179 super(originFile, false, null, 0, null, null, null, instructionSets, null, 9180 isMultiArch); 9181 } 9182 9183 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9184 final long lowThreshold; 9185 9186 final DeviceStorageMonitorInternal 9187 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9188 if (dsm == null) { 9189 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9190 lowThreshold = 0L; 9191 } else { 9192 if (dsm.isMemoryLow()) { 9193 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9194 return false; 9195 } 9196 9197 lowThreshold = dsm.getMemoryLowThreshold(); 9198 } 9199 9200 return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9201 lowThreshold); 9202 } 9203 9204 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9205 int ret = PackageManager.INSTALL_SUCCEEDED; 9206 9207 if (originStaged) { 9208 Slog.d(TAG, originFile + " already staged; skipping copy"); 9209 codeFile = originFile; 9210 resourceFile = originFile; 9211 } else { 9212 try { 9213 final File tempDir = mInstallerService.allocateSessionDir(); 9214 codeFile = tempDir; 9215 resourceFile = tempDir; 9216 } catch (IOException e) { 9217 Slog.w(TAG, "Failed to create copy file: " + e); 9218 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9219 } 9220 9221 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9222 @Override 9223 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9224 if (!FileUtils.isValidExtFilename(name)) { 9225 throw new IllegalArgumentException("Invalid filename: " + name); 9226 } 9227 try { 9228 final File file = new File(codeFile, name); 9229 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9230 O_RDWR | O_CREAT, 0644); 9231 Os.chmod(file.getAbsolutePath(), 0644); 9232 return new ParcelFileDescriptor(fd); 9233 } catch (ErrnoException e) { 9234 throw new RemoteException("Failed to open: " + e.getMessage()); 9235 } 9236 } 9237 }; 9238 9239 ret = imcs.copyPackage(originFile.getAbsolutePath(), target); 9240 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9241 Slog.e(TAG, "Failed to copy package"); 9242 return ret; 9243 } 9244 } 9245 9246 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9247 NativeLibraryHelper.Handle handle = null; 9248 try { 9249 handle = NativeLibraryHelper.Handle.create(codeFile); 9250 if (multiArch) { 9251 // Warn if we've set an abiOverride for multi-lib packages.. 9252 // By definition, we need to copy both 32 and 64 bit libraries for 9253 // such packages. 9254 if (abiOverride != null) { 9255 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9256 } 9257 9258 int copyRet = PackageManager.NO_NATIVE_LIBRARIES; 9259 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9260 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9261 Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */); 9262 maybeThrowExceptionForMultiArchCopy("Failure copying 32 bit native libraries", copyRet); 9263 } 9264 9265 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9266 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9267 Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */); 9268 maybeThrowExceptionForMultiArchCopy("Failure copying 64 bit native libraries", copyRet); 9269 } 9270 } else { 9271 String[] abiList = (abiOverride != null) ? 9272 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 9273 9274 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null && 9275 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9276 abiList = Build.SUPPORTED_32_BIT_ABIS; 9277 } 9278 9279 int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList, 9280 true /* use isa specific subdirs */); 9281 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9282 Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]"); 9283 return copyRet; 9284 } 9285 } 9286 } catch (IOException e) { 9287 Slog.e(TAG, "Copying native libraries failed", e); 9288 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9289 } catch (PackageManagerException pme) { 9290 Slog.e(TAG, "Copying native libraries failed", pme); 9291 ret = pme.error; 9292 } finally { 9293 IoUtils.closeQuietly(handle); 9294 } 9295 9296 return ret; 9297 } 9298 9299 int doPreInstall(int status) { 9300 if (status != PackageManager.INSTALL_SUCCEEDED) { 9301 cleanUp(); 9302 } 9303 return status; 9304 } 9305 9306 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9307 if (status != PackageManager.INSTALL_SUCCEEDED) { 9308 cleanUp(); 9309 return false; 9310 } else { 9311 final File beforeCodeFile = codeFile; 9312 final File afterCodeFile = getNextCodePath(pkg.packageName); 9313 9314 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9315 try { 9316 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9317 } catch (ErrnoException e) { 9318 Slog.d(TAG, "Failed to rename", e); 9319 return false; 9320 } 9321 9322 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9323 Slog.d(TAG, "Failed to restorecon"); 9324 return false; 9325 } 9326 9327 // Reflect the rename internally 9328 codeFile = afterCodeFile; 9329 resourceFile = afterCodeFile; 9330 9331 // Reflect the rename in scanned details 9332 pkg.codePath = afterCodeFile.getAbsolutePath(); 9333 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9334 pkg.baseCodePath); 9335 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9336 pkg.splitCodePaths); 9337 9338 // Reflect the rename in app info 9339 pkg.applicationInfo.setCodePath(pkg.codePath); 9340 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9341 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9342 pkg.applicationInfo.setResourcePath(pkg.codePath); 9343 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9344 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9345 9346 return true; 9347 } 9348 } 9349 9350 int doPostInstall(int status, int uid) { 9351 if (status != PackageManager.INSTALL_SUCCEEDED) { 9352 cleanUp(); 9353 } 9354 return status; 9355 } 9356 9357 @Override 9358 String getCodePath() { 9359 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9360 } 9361 9362 @Override 9363 String getResourcePath() { 9364 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9365 } 9366 9367 @Override 9368 String getLegacyNativeLibraryPath() { 9369 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9370 } 9371 9372 private boolean cleanUp() { 9373 if (codeFile == null || !codeFile.exists()) { 9374 return false; 9375 } 9376 9377 if (codeFile.isDirectory()) { 9378 FileUtils.deleteContents(codeFile); 9379 } 9380 codeFile.delete(); 9381 9382 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9383 resourceFile.delete(); 9384 } 9385 9386 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9387 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9388 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9389 } 9390 legacyNativeLibraryPath.delete(); 9391 } 9392 9393 return true; 9394 } 9395 9396 void cleanUpResourcesLI() { 9397 // Try enumerating all code paths before deleting 9398 List<String> allCodePaths = Collections.EMPTY_LIST; 9399 if (codeFile != null && codeFile.exists()) { 9400 try { 9401 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9402 allCodePaths = pkg.getAllCodePaths(); 9403 } catch (PackageParserException e) { 9404 // Ignored; we tried our best 9405 } 9406 } 9407 9408 cleanUp(); 9409 9410 if (!allCodePaths.isEmpty()) { 9411 if (instructionSets == null) { 9412 throw new IllegalStateException("instructionSet == null"); 9413 } 9414 9415 for (String codePath : allCodePaths) { 9416 for (String instructionSet : instructionSets) { 9417 int retCode = mInstaller.rmdex(codePath, instructionSet); 9418 if (retCode < 0) { 9419 Slog.w(TAG, "Couldn't remove dex file for package: " 9420 + " at location " + codePath + ", retcode=" + retCode); 9421 // we don't consider this to be a failure of the core package deletion 9422 } 9423 } 9424 } 9425 } 9426 } 9427 9428 boolean doPostDeleteLI(boolean delete) { 9429 // XXX err, shouldn't we respect the delete flag? 9430 cleanUpResourcesLI(); 9431 return true; 9432 } 9433 } 9434 9435 private boolean isAsecExternal(String cid) { 9436 final String asecPath = PackageHelper.getSdFilesystem(cid); 9437 return !asecPath.startsWith(mAsecInternalPath); 9438 } 9439 9440 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9441 PackageManagerException { 9442 if (copyRet < 0) { 9443 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9444 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9445 throw new PackageManagerException(copyRet, message); 9446 } 9447 } 9448 } 9449 9450 /** 9451 * Extract the MountService "container ID" from the full code path of an 9452 * .apk. 9453 */ 9454 static String cidFromCodePath(String fullCodePath) { 9455 int eidx = fullCodePath.lastIndexOf("/"); 9456 String subStr1 = fullCodePath.substring(0, eidx); 9457 int sidx = subStr1.lastIndexOf("/"); 9458 return subStr1.substring(sidx+1, eidx); 9459 } 9460 9461 /** 9462 * Logic to handle installation of ASEC applications, including copying and 9463 * renaming logic. 9464 */ 9465 class AsecInstallArgs extends InstallArgs { 9466 // TODO: teach about handling cluster directories 9467 9468 static final String RES_FILE_NAME = "pkg.apk"; 9469 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9470 9471 String cid; 9472 String packagePath; 9473 String resourcePath; 9474 String legacyNativeLibraryDir; 9475 9476 /** New install */ 9477 AsecInstallArgs(InstallParams params) { 9478 super(params.originFile, params.originStaged, params.observer, params.flags, 9479 params.installerPackageName, params.getManifestDigest(), 9480 params.getUser(), null /* instruction sets */, 9481 params.packageAbiOverride, params.multiArch); 9482 } 9483 9484 /** Existing install */ 9485 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9486 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9487 super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9488 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9489 instructionSets, null, isMultiArch); 9490 // Extract cid from fullCodePath 9491 int eidx = fullCodePath.lastIndexOf("/"); 9492 String subStr1 = fullCodePath.substring(0, eidx); 9493 int sidx = subStr1.lastIndexOf("/"); 9494 cid = subStr1.substring(sidx+1, eidx); 9495 setCachePath(subStr1); 9496 } 9497 9498 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked, 9499 boolean isMultiArch) { 9500 super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9501 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9502 instructionSets, null, isMultiArch); 9503 this.cid = cid; 9504 setCachePath(PackageHelper.getSdDir(cid)); 9505 } 9506 9507 /** New install from existing */ 9508 AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets, 9509 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9510 super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9511 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9512 instructionSets, null, isMultiArch); 9513 this.cid = cid; 9514 } 9515 9516 void createCopyFile() { 9517 cid = getTempContainerId(); 9518 } 9519 9520 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9521 return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9522 abiOverride); 9523 } 9524 9525 private final boolean isExternal() { 9526 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9527 } 9528 9529 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9530 if (temp) { 9531 createCopyFile(); 9532 } else { 9533 /* 9534 * Pre-emptively destroy the container since it's destroyed if 9535 * copying fails due to it existing anyway. 9536 */ 9537 PackageHelper.destroySdDir(cid); 9538 } 9539 9540 final String newCachePath = imcs.copyPackageToContainer( 9541 originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9542 isFwdLocked(), abiOverride); 9543 9544 if (newCachePath != null) { 9545 setCachePath(newCachePath); 9546 return PackageManager.INSTALL_SUCCEEDED; 9547 } else { 9548 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9549 } 9550 } 9551 9552 @Override 9553 String getCodePath() { 9554 return packagePath; 9555 } 9556 9557 @Override 9558 String getResourcePath() { 9559 return resourcePath; 9560 } 9561 9562 @Override 9563 String getLegacyNativeLibraryPath() { 9564 return legacyNativeLibraryDir; 9565 } 9566 9567 int doPreInstall(int status) { 9568 if (status != PackageManager.INSTALL_SUCCEEDED) { 9569 // Destroy container 9570 PackageHelper.destroySdDir(cid); 9571 } else { 9572 boolean mounted = PackageHelper.isContainerMounted(cid); 9573 if (!mounted) { 9574 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9575 Process.SYSTEM_UID); 9576 if (newCachePath != null) { 9577 setCachePath(newCachePath); 9578 } else { 9579 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9580 } 9581 } 9582 } 9583 return status; 9584 } 9585 9586 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9587 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9588 String newCachePath = null; 9589 if (PackageHelper.isContainerMounted(cid)) { 9590 // Unmount the container 9591 if (!PackageHelper.unMountSdDir(cid)) { 9592 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9593 return false; 9594 } 9595 } 9596 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9597 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9598 " which might be stale. Will try to clean up."); 9599 // Clean up the stale container and proceed to recreate. 9600 if (!PackageHelper.destroySdDir(newCacheId)) { 9601 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9602 return false; 9603 } 9604 // Successfully cleaned up stale container. Try to rename again. 9605 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9606 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9607 + " inspite of cleaning it up."); 9608 return false; 9609 } 9610 } 9611 if (!PackageHelper.isContainerMounted(newCacheId)) { 9612 Slog.w(TAG, "Mounting container " + newCacheId); 9613 newCachePath = PackageHelper.mountSdDir(newCacheId, 9614 getEncryptKey(), Process.SYSTEM_UID); 9615 } else { 9616 newCachePath = PackageHelper.getSdDir(newCacheId); 9617 } 9618 if (newCachePath == null) { 9619 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9620 return false; 9621 } 9622 Log.i(TAG, "Succesfully renamed " + cid + 9623 " to " + newCacheId + 9624 " at new path: " + newCachePath); 9625 cid = newCacheId; 9626 setCachePath(newCachePath); 9627 9628 // TODO: extend to support split APKs 9629 pkg.codePath = getCodePath(); 9630 pkg.baseCodePath = getCodePath(); 9631 pkg.splitCodePaths = null; 9632 9633 pkg.applicationInfo.setCodePath(getCodePath()); 9634 pkg.applicationInfo.setBaseCodePath(getCodePath()); 9635 pkg.applicationInfo.setSplitCodePaths(null); 9636 pkg.applicationInfo.setResourcePath(getResourcePath()); 9637 pkg.applicationInfo.setBaseResourcePath(getResourcePath()); 9638 pkg.applicationInfo.setSplitResourcePaths(null); 9639 9640 return true; 9641 } 9642 9643 private void setCachePath(String newCachePath) { 9644 File cachePath = new File(newCachePath); 9645 legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath(); 9646 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9647 9648 if (isFwdLocked()) { 9649 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9650 } else { 9651 resourcePath = packagePath; 9652 } 9653 } 9654 9655 int doPostInstall(int status, int uid) { 9656 if (status != PackageManager.INSTALL_SUCCEEDED) { 9657 cleanUp(); 9658 } else { 9659 final int groupOwner; 9660 final String protectedFile; 9661 if (isFwdLocked()) { 9662 groupOwner = UserHandle.getSharedAppGid(uid); 9663 protectedFile = RES_FILE_NAME; 9664 } else { 9665 groupOwner = -1; 9666 protectedFile = null; 9667 } 9668 9669 if (uid < Process.FIRST_APPLICATION_UID 9670 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9671 Slog.e(TAG, "Failed to finalize " + cid); 9672 PackageHelper.destroySdDir(cid); 9673 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9674 } 9675 9676 boolean mounted = PackageHelper.isContainerMounted(cid); 9677 if (!mounted) { 9678 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9679 } 9680 } 9681 return status; 9682 } 9683 9684 private void cleanUp() { 9685 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9686 9687 // Destroy secure container 9688 PackageHelper.destroySdDir(cid); 9689 } 9690 9691 void cleanUpResourcesLI() { 9692 String sourceFile = getCodePath(); 9693 // Remove dex file 9694 if (instructionSets == null) { 9695 throw new IllegalStateException("instructionSet == null"); 9696 } 9697 for (String instructionSet : instructionSets) { 9698 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9699 if (retCode < 0) { 9700 Slog.w(TAG, "Couldn't remove dex file for package: " 9701 + " at location " 9702 + sourceFile.toString() + ", retcode=" + retCode); 9703 // we don't consider this to be a failure of the core package deletion 9704 } 9705 } 9706 cleanUp(); 9707 } 9708 9709 boolean matchContainer(String app) { 9710 if (cid.startsWith(app)) { 9711 return true; 9712 } 9713 return false; 9714 } 9715 9716 String getPackageName() { 9717 return getAsecPackageName(cid); 9718 } 9719 9720 boolean doPostDeleteLI(boolean delete) { 9721 boolean ret = false; 9722 boolean mounted = PackageHelper.isContainerMounted(cid); 9723 if (mounted) { 9724 // Unmount first 9725 ret = PackageHelper.unMountSdDir(cid); 9726 } 9727 if (ret && delete) { 9728 cleanUpResourcesLI(); 9729 } 9730 return ret; 9731 } 9732 9733 @Override 9734 int doPreCopy() { 9735 if (isFwdLocked()) { 9736 if (!PackageHelper.fixSdPermissions(cid, 9737 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9738 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9739 } 9740 } 9741 9742 return PackageManager.INSTALL_SUCCEEDED; 9743 } 9744 9745 @Override 9746 int doPostCopy(int uid) { 9747 if (isFwdLocked()) { 9748 if (uid < Process.FIRST_APPLICATION_UID 9749 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9750 RES_FILE_NAME)) { 9751 Slog.e(TAG, "Failed to finalize " + cid); 9752 PackageHelper.destroySdDir(cid); 9753 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9754 } 9755 } 9756 9757 return PackageManager.INSTALL_SUCCEEDED; 9758 } 9759 } 9760 9761 static String getAsecPackageName(String packageCid) { 9762 int idx = packageCid.lastIndexOf("-"); 9763 if (idx == -1) { 9764 return packageCid; 9765 } 9766 return packageCid.substring(0, idx); 9767 } 9768 9769 // Utility method used to create code paths based on package name and available index. 9770 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9771 String idxStr = ""; 9772 int idx = 1; 9773 // Fall back to default value of idx=1 if prefix is not 9774 // part of oldCodePath 9775 if (oldCodePath != null) { 9776 String subStr = oldCodePath; 9777 // Drop the suffix right away 9778 if (suffix != null && subStr.endsWith(suffix)) { 9779 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9780 } 9781 // If oldCodePath already contains prefix find out the 9782 // ending index to either increment or decrement. 9783 int sidx = subStr.lastIndexOf(prefix); 9784 if (sidx != -1) { 9785 subStr = subStr.substring(sidx + prefix.length()); 9786 if (subStr != null) { 9787 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9788 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9789 } 9790 try { 9791 idx = Integer.parseInt(subStr); 9792 if (idx <= 1) { 9793 idx++; 9794 } else { 9795 idx--; 9796 } 9797 } catch(NumberFormatException e) { 9798 } 9799 } 9800 } 9801 } 9802 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9803 return prefix + idxStr; 9804 } 9805 9806 private File getNextCodePath(String packageName) { 9807 int suffix = 1; 9808 File result; 9809 do { 9810 result = new File(mAppInstallDir, packageName + "-" + suffix); 9811 suffix++; 9812 } while (result.exists()); 9813 return result; 9814 } 9815 9816 // Utility method used to ignore ADD/REMOVE events 9817 // by directory observer. 9818 private static boolean ignoreCodePath(String fullPathStr) { 9819 String apkName = deriveCodePathName(fullPathStr); 9820 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9821 if (idx != -1 && ((idx+1) < apkName.length())) { 9822 // Make sure the package ends with a numeral 9823 String version = apkName.substring(idx+1); 9824 try { 9825 Integer.parseInt(version); 9826 return true; 9827 } catch (NumberFormatException e) {} 9828 } 9829 return false; 9830 } 9831 9832 // Utility method that returns the relative package path with respect 9833 // to the installation directory. Like say for /data/data/com.test-1.apk 9834 // string com.test-1 is returned. 9835 static String deriveCodePathName(String codePath) { 9836 if (codePath == null) { 9837 return null; 9838 } 9839 final File codeFile = new File(codePath); 9840 final String name = codeFile.getName(); 9841 if (codeFile.isDirectory()) { 9842 return name; 9843 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9844 final int lastDot = name.lastIndexOf('.'); 9845 return name.substring(0, lastDot); 9846 } else { 9847 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9848 return null; 9849 } 9850 } 9851 9852 class PackageInstalledInfo { 9853 String name; 9854 int uid; 9855 // The set of users that originally had this package installed. 9856 int[] origUsers; 9857 // The set of users that now have this package installed. 9858 int[] newUsers; 9859 PackageParser.Package pkg; 9860 int returnCode; 9861 String returnMsg; 9862 PackageRemovedInfo removedInfo; 9863 9864 public void setError(int code, String msg) { 9865 returnCode = code; 9866 returnMsg = msg; 9867 Slog.w(TAG, msg); 9868 } 9869 9870 public void setError(String msg, PackageParserException e) { 9871 returnCode = e.error; 9872 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9873 Slog.w(TAG, msg, e); 9874 } 9875 9876 public void setError(String msg, PackageManagerException e) { 9877 returnCode = e.error; 9878 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9879 Slog.w(TAG, msg, e); 9880 } 9881 9882 // In some error cases we want to convey more info back to the observer 9883 String origPackage; 9884 String origPermission; 9885 } 9886 9887 /* 9888 * Install a non-existing package. 9889 */ 9890 private void installNewPackageLI(PackageParser.Package pkg, 9891 int parseFlags, int scanMode, UserHandle user, 9892 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9893 // Remember this for later, in case we need to rollback this install 9894 String pkgName = pkg.packageName; 9895 9896 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9897 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9898 synchronized(mPackages) { 9899 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9900 // A package with the same name is already installed, though 9901 // it has been renamed to an older name. The package we 9902 // are trying to install should be installed as an update to 9903 // the existing one, but that has not been requested, so bail. 9904 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9905 + " without first uninstalling package running as " 9906 + mSettings.mRenamedPackages.get(pkgName)); 9907 return; 9908 } 9909 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9910 // Don't allow installation over an existing package with the same name. 9911 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9912 + " without first uninstalling."); 9913 return; 9914 } 9915 } 9916 9917 try { 9918 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9919 System.currentTimeMillis(), user, abiOverride); 9920 9921 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9922 // delete the partially installed application. the data directory will have to be 9923 // restored if it was already existing 9924 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9925 // remove package from internal structures. Note that we want deletePackageX to 9926 // delete the package data and cache directories that it created in 9927 // scanPackageLocked, unless those directories existed before we even tried to 9928 // install. 9929 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9930 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9931 res.removedInfo, true); 9932 } 9933 9934 } catch (PackageManagerException e) { 9935 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9936 } 9937 } 9938 9939 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9940 // Upgrade keysets are being used. Determine if new package has a superset of the 9941 // required keys. 9942 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9943 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9944 for (int i = 0; i < upgradeKeySets.length; i++) { 9945 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9946 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9947 return true; 9948 } 9949 } 9950 return false; 9951 } 9952 9953 private void replacePackageLI(PackageParser.Package pkg, 9954 int parseFlags, int scanMode, UserHandle user, 9955 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9956 PackageParser.Package oldPackage; 9957 String pkgName = pkg.packageName; 9958 int[] allUsers; 9959 boolean[] perUserInstalled; 9960 9961 // First find the old package info and check signatures 9962 synchronized(mPackages) { 9963 oldPackage = mPackages.get(pkgName); 9964 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9965 PackageSetting ps = mSettings.mPackages.get(pkgName); 9966 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9967 // default to original signature matching 9968 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9969 != PackageManager.SIGNATURE_MATCH) { 9970 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9971 "New package has a different signature: " + pkgName); 9972 return; 9973 } 9974 } else { 9975 if(!checkUpgradeKeySetLP(ps, pkg)) { 9976 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9977 "New package not signed by keys specified by upgrade-keysets: " 9978 + pkgName); 9979 return; 9980 } 9981 } 9982 9983 // In case of rollback, remember per-user/profile install state 9984 allUsers = sUserManager.getUserIds(); 9985 perUserInstalled = new boolean[allUsers.length]; 9986 for (int i = 0; i < allUsers.length; i++) { 9987 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9988 } 9989 } 9990 9991 boolean sysPkg = (isSystemApp(oldPackage)); 9992 if (sysPkg) { 9993 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9994 user, allUsers, perUserInstalled, installerPackageName, res, 9995 abiOverride); 9996 } else { 9997 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9998 user, allUsers, perUserInstalled, installerPackageName, res, 9999 abiOverride); 10000 } 10001 } 10002 10003 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10004 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10005 int[] allUsers, boolean[] perUserInstalled, 10006 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10007 String pkgName = deletedPackage.packageName; 10008 boolean deletedPkg = true; 10009 boolean updatedSettings = false; 10010 10011 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10012 + deletedPackage); 10013 long origUpdateTime; 10014 if (pkg.mExtras != null) { 10015 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10016 } else { 10017 origUpdateTime = 0; 10018 } 10019 10020 // First delete the existing package while retaining the data directory 10021 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10022 res.removedInfo, true)) { 10023 // If the existing package wasn't successfully deleted 10024 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10025 deletedPkg = false; 10026 } else { 10027 // Successfully deleted the old package. Now proceed with re-installation 10028 deleteCodeCacheDirsLI(pkgName); 10029 try { 10030 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10031 scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user, abiOverride); 10032 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10033 updatedSettings = true; 10034 } catch (PackageManagerException e) { 10035 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10036 } 10037 } 10038 10039 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10040 // remove package from internal structures. Note that we want deletePackageX to 10041 // delete the package data and cache directories that it created in 10042 // scanPackageLocked, unless those directories existed before we even tried to 10043 // install. 10044 if(updatedSettings) { 10045 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10046 deletePackageLI( 10047 pkgName, null, true, allUsers, perUserInstalled, 10048 PackageManager.DELETE_KEEP_DATA, 10049 res.removedInfo, true); 10050 } 10051 // Since we failed to install the new package we need to restore the old 10052 // package that we deleted. 10053 if (deletedPkg) { 10054 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10055 File restoreFile = new File(deletedPackage.codePath); 10056 // Parse old package 10057 boolean oldOnSd = isExternal(deletedPackage); 10058 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10059 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10060 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10061 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 10062 | SCAN_UPDATE_TIME; 10063 try { 10064 scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null, 10065 null); 10066 } catch (PackageManagerException e) { 10067 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10068 + e.getMessage()); 10069 return; 10070 } 10071 // Restore of old package succeeded. Update permissions. 10072 // writer 10073 synchronized (mPackages) { 10074 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10075 UPDATE_PERMISSIONS_ALL); 10076 // can downgrade to reader 10077 mSettings.writeLPr(); 10078 } 10079 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10080 } 10081 } 10082 } 10083 10084 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10085 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10086 int[] allUsers, boolean[] perUserInstalled, 10087 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10088 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10089 + ", old=" + deletedPackage); 10090 boolean updatedSettings = false; 10091 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 10092 PackageParser.PARSE_IS_SYSTEM; 10093 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10094 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10095 } 10096 String packageName = deletedPackage.packageName; 10097 if (packageName == null) { 10098 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10099 "Attempt to delete null packageName."); 10100 return; 10101 } 10102 PackageParser.Package oldPkg; 10103 PackageSetting oldPkgSetting; 10104 // reader 10105 synchronized (mPackages) { 10106 oldPkg = mPackages.get(packageName); 10107 oldPkgSetting = mSettings.mPackages.get(packageName); 10108 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10109 (oldPkgSetting == null)) { 10110 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10111 "Couldn't find package:" + packageName + " information"); 10112 return; 10113 } 10114 } 10115 10116 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10117 10118 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10119 res.removedInfo.removedPackage = packageName; 10120 // Remove existing system package 10121 removePackageLI(oldPkgSetting, true); 10122 // writer 10123 synchronized (mPackages) { 10124 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10125 // We didn't need to disable the .apk as a current system package, 10126 // which means we are replacing another update that is already 10127 // installed. We need to make sure to delete the older one's .apk. 10128 res.removedInfo.args = createInstallArgsForExisting(0, 10129 deletedPackage.applicationInfo.getCodePath(), 10130 deletedPackage.applicationInfo.getResourcePath(), 10131 deletedPackage.applicationInfo.nativeLibraryRootDir, 10132 getAppDexInstructionSets(deletedPackage.applicationInfo), 10133 isMultiArch(deletedPackage.applicationInfo)); 10134 } else { 10135 res.removedInfo.args = null; 10136 } 10137 } 10138 10139 // Successfully disabled the old package. Now proceed with re-installation 10140 deleteCodeCacheDirsLI(packageName); 10141 10142 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10143 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10144 10145 PackageParser.Package newPackage = null; 10146 try { 10147 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride); 10148 if (newPackage.mExtras != null) { 10149 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10150 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10151 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10152 10153 // is the update attempting to change shared user? that isn't going to work... 10154 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10155 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10156 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10157 + " to " + newPkgSetting.sharedUser); 10158 updatedSettings = true; 10159 } 10160 } 10161 10162 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10163 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10164 updatedSettings = true; 10165 } 10166 10167 } catch (PackageManagerException e) { 10168 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10169 } 10170 10171 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10172 // Re installation failed. Restore old information 10173 // Remove new pkg information 10174 if (newPackage != null) { 10175 removeInstalledPackageLI(newPackage, true); 10176 } 10177 // Add back the old system package 10178 try { 10179 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, 10180 null); 10181 } catch (PackageManagerException e) { 10182 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10183 } 10184 // Restore the old system information in Settings 10185 synchronized(mPackages) { 10186 if (updatedSettings) { 10187 mSettings.enableSystemPackageLPw(packageName); 10188 mSettings.setInstallerPackageName(packageName, 10189 oldPkgSetting.installerPackageName); 10190 } 10191 mSettings.writeLPr(); 10192 } 10193 } 10194 } 10195 10196 // Utility method used to move dex files during install. 10197 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10198 // TODO: extend to move split APK dex files 10199 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10200 final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo); 10201 for (String instructionSet : instructionSets) { 10202 int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath, 10203 instructionSet); 10204 if (retCode != 0) { 10205 /* 10206 * Programs may be lazily run through dexopt, so the 10207 * source may not exist. However, something seems to 10208 * have gone wrong, so note that dexopt needs to be 10209 * run again and remove the source file. In addition, 10210 * remove the target to make sure there isn't a stale 10211 * file from a previous version of the package. 10212 */ 10213 newPackage.mDexOptPerformed.clear(); 10214 mInstaller.rmdex(oldCodePath, instructionSet); 10215 mInstaller.rmdex(newPackage.baseCodePath, instructionSet); 10216 } 10217 } 10218 } 10219 return PackageManager.INSTALL_SUCCEEDED; 10220 } 10221 10222 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10223 int[] allUsers, boolean[] perUserInstalled, 10224 PackageInstalledInfo res) { 10225 String pkgName = newPackage.packageName; 10226 synchronized (mPackages) { 10227 //write settings. the installStatus will be incomplete at this stage. 10228 //note that the new package setting would have already been 10229 //added to mPackages. It hasn't been persisted yet. 10230 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10231 mSettings.writeLPr(); 10232 } 10233 10234 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10235 10236 synchronized (mPackages) { 10237 updatePermissionsLPw(newPackage.packageName, newPackage, 10238 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10239 ? UPDATE_PERMISSIONS_ALL : 0)); 10240 // For system-bundled packages, we assume that installing an upgraded version 10241 // of the package implies that the user actually wants to run that new code, 10242 // so we enable the package. 10243 if (isSystemApp(newPackage)) { 10244 // NB: implicit assumption that system package upgrades apply to all users 10245 if (DEBUG_INSTALL) { 10246 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10247 } 10248 PackageSetting ps = mSettings.mPackages.get(pkgName); 10249 if (ps != null) { 10250 if (res.origUsers != null) { 10251 for (int userHandle : res.origUsers) { 10252 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10253 userHandle, installerPackageName); 10254 } 10255 } 10256 // Also convey the prior install/uninstall state 10257 if (allUsers != null && perUserInstalled != null) { 10258 for (int i = 0; i < allUsers.length; i++) { 10259 if (DEBUG_INSTALL) { 10260 Slog.d(TAG, " user " + allUsers[i] 10261 + " => " + perUserInstalled[i]); 10262 } 10263 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10264 } 10265 // these install state changes will be persisted in the 10266 // upcoming call to mSettings.writeLPr(). 10267 } 10268 } 10269 } 10270 res.name = pkgName; 10271 res.uid = newPackage.applicationInfo.uid; 10272 res.pkg = newPackage; 10273 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10274 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10275 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10276 //to update install status 10277 mSettings.writeLPr(); 10278 } 10279 } 10280 10281 private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) { 10282 int pFlags = args.flags; 10283 String installerPackageName = args.installerPackageName; 10284 File tmpPackageFile = new File(args.getCodePath()); 10285 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10286 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10287 boolean replace = false; 10288 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10289 | (newInstall ? SCAN_NEW_INSTALL : 0); 10290 // Result object to be returned 10291 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10292 10293 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10294 // Retrieve PackageSettings and parse package 10295 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10296 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10297 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10298 PackageParser pp = new PackageParser(); 10299 pp.setSeparateProcesses(mSeparateProcesses); 10300 pp.setDisplayMetrics(mMetrics); 10301 10302 final PackageParser.Package pkg; 10303 try { 10304 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10305 } catch (PackageParserException e) { 10306 res.setError("Failed parse during installPackageLI", e); 10307 return; 10308 } 10309 10310 String pkgName = res.name = pkg.packageName; 10311 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10312 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10313 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10314 return; 10315 } 10316 } 10317 10318 try { 10319 pp.collectCertificates(pkg, parseFlags); 10320 pp.collectManifestDigest(pkg); 10321 } catch (PackageParserException e) { 10322 res.setError("Failed collect during installPackageLI", e); 10323 return; 10324 } 10325 10326 /* If the installer passed in a manifest digest, compare it now. */ 10327 if (args.manifestDigest != null) { 10328 if (DEBUG_INSTALL) { 10329 final String parsedManifest = pkg.manifestDigest == null ? "null" 10330 : pkg.manifestDigest.toString(); 10331 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10332 + parsedManifest); 10333 } 10334 10335 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10336 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10337 return; 10338 } 10339 } else if (DEBUG_INSTALL) { 10340 final String parsedManifest = pkg.manifestDigest == null 10341 ? "null" : pkg.manifestDigest.toString(); 10342 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10343 } 10344 10345 // Get rid of all references to package scan path via parser. 10346 pp = null; 10347 String oldCodePath = null; 10348 boolean systemApp = false; 10349 synchronized (mPackages) { 10350 // Check whether the newly-scanned package wants to define an already-defined perm 10351 int N = pkg.permissions.size(); 10352 for (int i = N-1; i >= 0; i--) { 10353 PackageParser.Permission perm = pkg.permissions.get(i); 10354 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10355 if (bp != null) { 10356 // If the defining package is signed with our cert, it's okay. This 10357 // also includes the "updating the same package" case, of course. 10358 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10359 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10360 // If the owning package is the system itself, we log but allow 10361 // install to proceed; we fail the install on all other permission 10362 // redefinitions. 10363 if (!bp.sourcePackage.equals("android")) { 10364 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10365 + pkg.packageName + " attempting to redeclare permission " 10366 + perm.info.name + " already owned by " + bp.sourcePackage); 10367 res.origPermission = perm.info.name; 10368 res.origPackage = bp.sourcePackage; 10369 return; 10370 } else { 10371 Slog.w(TAG, "Package " + pkg.packageName 10372 + " attempting to redeclare system permission " 10373 + perm.info.name + "; ignoring new declaration"); 10374 pkg.permissions.remove(i); 10375 } 10376 } 10377 } 10378 } 10379 10380 // Check if installing already existing package 10381 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10382 String oldName = mSettings.mRenamedPackages.get(pkgName); 10383 if (pkg.mOriginalPackages != null 10384 && pkg.mOriginalPackages.contains(oldName) 10385 && mPackages.containsKey(oldName)) { 10386 // This package is derived from an original package, 10387 // and this device has been updating from that original 10388 // name. We must continue using the original name, so 10389 // rename the new package here. 10390 pkg.setPackageName(oldName); 10391 pkgName = pkg.packageName; 10392 replace = true; 10393 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10394 + oldName + " pkgName=" + pkgName); 10395 } else if (mPackages.containsKey(pkgName)) { 10396 // This package, under its official name, already exists 10397 // on the device; we should replace it. 10398 replace = true; 10399 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10400 } 10401 } 10402 PackageSetting ps = mSettings.mPackages.get(pkgName); 10403 if (ps != null) { 10404 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10405 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10406 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10407 systemApp = (ps.pkg.applicationInfo.flags & 10408 ApplicationInfo.FLAG_SYSTEM) != 0; 10409 } 10410 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10411 } 10412 } 10413 10414 if (systemApp && onSd) { 10415 // Disable updates to system apps on sdcard 10416 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10417 "Cannot install updates to system apps on sdcard"); 10418 return; 10419 } 10420 10421 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10422 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10423 return; 10424 } 10425 10426 if (replace) { 10427 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10428 installerPackageName, res, args.abiOverride); 10429 } else { 10430 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10431 installerPackageName, res, args.abiOverride); 10432 } 10433 synchronized (mPackages) { 10434 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10435 if (ps != null) { 10436 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10437 } 10438 } 10439 } 10440 10441 private static boolean isForwardLocked(PackageParser.Package pkg) { 10442 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10443 } 10444 10445 private static boolean isForwardLocked(ApplicationInfo info) { 10446 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10447 } 10448 10449 private boolean isForwardLocked(PackageSetting ps) { 10450 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10451 } 10452 10453 private static boolean isMultiArch(PackageSetting ps) { 10454 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10455 } 10456 10457 private static boolean isMultiArch(ApplicationInfo info) { 10458 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10459 } 10460 10461 private static boolean isExternal(PackageParser.Package pkg) { 10462 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10463 } 10464 10465 private static boolean isExternal(PackageSetting ps) { 10466 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10467 } 10468 10469 private static boolean isExternal(ApplicationInfo info) { 10470 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10471 } 10472 10473 private static boolean isSystemApp(PackageParser.Package pkg) { 10474 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10475 } 10476 10477 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10478 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10479 } 10480 10481 private static boolean isSystemApp(ApplicationInfo info) { 10482 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10483 } 10484 10485 private static boolean isSystemApp(PackageSetting ps) { 10486 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10487 } 10488 10489 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10490 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10491 } 10492 10493 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10494 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10495 } 10496 10497 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10498 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10499 } 10500 10501 private int packageFlagsToInstallFlags(PackageSetting ps) { 10502 int installFlags = 0; 10503 if (isExternal(ps)) { 10504 installFlags |= PackageManager.INSTALL_EXTERNAL; 10505 } 10506 if (isForwardLocked(ps)) { 10507 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10508 } 10509 return installFlags; 10510 } 10511 10512 private void deleteTempPackageFiles() { 10513 final FilenameFilter filter = new FilenameFilter() { 10514 public boolean accept(File dir, String name) { 10515 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10516 } 10517 }; 10518 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10519 file.delete(); 10520 } 10521 } 10522 10523 @Override 10524 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10525 int flags) { 10526 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10527 flags); 10528 } 10529 10530 @Override 10531 public void deletePackage(final String packageName, 10532 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10533 mContext.enforceCallingOrSelfPermission( 10534 android.Manifest.permission.DELETE_PACKAGES, null); 10535 final int uid = Binder.getCallingUid(); 10536 if (UserHandle.getUserId(uid) != userId) { 10537 mContext.enforceCallingPermission( 10538 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10539 "deletePackage for user " + userId); 10540 } 10541 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10542 try { 10543 observer.onPackageDeleted(packageName, 10544 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10545 } catch (RemoteException re) { 10546 } 10547 return; 10548 } 10549 10550 boolean uninstallBlocked = false; 10551 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10552 int[] users = sUserManager.getUserIds(); 10553 for (int i = 0; i < users.length; ++i) { 10554 if (getBlockUninstallForUser(packageName, users[i])) { 10555 uninstallBlocked = true; 10556 break; 10557 } 10558 } 10559 } else { 10560 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10561 } 10562 if (uninstallBlocked) { 10563 try { 10564 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10565 null); 10566 } catch (RemoteException re) { 10567 } 10568 return; 10569 } 10570 10571 if (DEBUG_REMOVE) { 10572 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10573 } 10574 // Queue up an async operation since the package deletion may take a little while. 10575 mHandler.post(new Runnable() { 10576 public void run() { 10577 mHandler.removeCallbacks(this); 10578 final int returnCode = deletePackageX(packageName, userId, flags); 10579 if (observer != null) { 10580 try { 10581 observer.onPackageDeleted(packageName, returnCode, null); 10582 } catch (RemoteException e) { 10583 Log.i(TAG, "Observer no longer exists."); 10584 } //end catch 10585 } //end if 10586 } //end run 10587 }); 10588 } 10589 10590 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10591 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10592 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10593 try { 10594 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10595 || dpm.isDeviceOwner(packageName))) { 10596 return true; 10597 } 10598 } catch (RemoteException e) { 10599 } 10600 return false; 10601 } 10602 10603 /** 10604 * This method is an internal method that could be get invoked either 10605 * to delete an installed package or to clean up a failed installation. 10606 * After deleting an installed package, a broadcast is sent to notify any 10607 * listeners that the package has been installed. For cleaning up a failed 10608 * installation, the broadcast is not necessary since the package's 10609 * installation wouldn't have sent the initial broadcast either 10610 * The key steps in deleting a package are 10611 * deleting the package information in internal structures like mPackages, 10612 * deleting the packages base directories through installd 10613 * updating mSettings to reflect current status 10614 * persisting settings for later use 10615 * sending a broadcast if necessary 10616 */ 10617 private int deletePackageX(String packageName, int userId, int flags) { 10618 final PackageRemovedInfo info = new PackageRemovedInfo(); 10619 final boolean res; 10620 10621 if (isPackageDeviceAdmin(packageName, userId)) { 10622 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10623 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10624 } 10625 10626 boolean removedForAllUsers = false; 10627 boolean systemUpdate = false; 10628 10629 // for the uninstall-updates case and restricted profiles, remember the per- 10630 // userhandle installed state 10631 int[] allUsers; 10632 boolean[] perUserInstalled; 10633 synchronized (mPackages) { 10634 PackageSetting ps = mSettings.mPackages.get(packageName); 10635 allUsers = sUserManager.getUserIds(); 10636 perUserInstalled = new boolean[allUsers.length]; 10637 for (int i = 0; i < allUsers.length; i++) { 10638 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10639 } 10640 } 10641 10642 synchronized (mInstallLock) { 10643 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10644 res = deletePackageLI(packageName, 10645 (flags & PackageManager.DELETE_ALL_USERS) != 0 10646 ? UserHandle.ALL : new UserHandle(userId), 10647 true, allUsers, perUserInstalled, 10648 flags | REMOVE_CHATTY, info, true); 10649 systemUpdate = info.isRemovedPackageSystemUpdate; 10650 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10651 removedForAllUsers = true; 10652 } 10653 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10654 + " removedForAllUsers=" + removedForAllUsers); 10655 } 10656 10657 if (res) { 10658 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10659 10660 // If the removed package was a system update, the old system package 10661 // was re-enabled; we need to broadcast this information 10662 if (systemUpdate) { 10663 Bundle extras = new Bundle(1); 10664 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10665 ? info.removedAppId : info.uid); 10666 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10667 10668 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10669 extras, null, null, null); 10670 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10671 extras, null, null, null); 10672 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10673 null, packageName, null, null); 10674 } 10675 } 10676 // Force a gc here. 10677 Runtime.getRuntime().gc(); 10678 // Delete the resources here after sending the broadcast to let 10679 // other processes clean up before deleting resources. 10680 if (info.args != null) { 10681 synchronized (mInstallLock) { 10682 info.args.doPostDeleteLI(true); 10683 } 10684 } 10685 10686 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10687 } 10688 10689 static class PackageRemovedInfo { 10690 String removedPackage; 10691 int uid = -1; 10692 int removedAppId = -1; 10693 int[] removedUsers = null; 10694 boolean isRemovedPackageSystemUpdate = false; 10695 // Clean up resources deleted packages. 10696 InstallArgs args = null; 10697 10698 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10699 Bundle extras = new Bundle(1); 10700 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10701 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10702 if (replacing) { 10703 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10704 } 10705 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10706 if (removedPackage != null) { 10707 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10708 extras, null, null, removedUsers); 10709 if (fullRemove && !replacing) { 10710 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10711 extras, null, null, removedUsers); 10712 } 10713 } 10714 if (removedAppId >= 0) { 10715 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10716 removedUsers); 10717 } 10718 } 10719 } 10720 10721 /* 10722 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10723 * flag is not set, the data directory is removed as well. 10724 * make sure this flag is set for partially installed apps. If not its meaningless to 10725 * delete a partially installed application. 10726 */ 10727 private void removePackageDataLI(PackageSetting ps, 10728 int[] allUserHandles, boolean[] perUserInstalled, 10729 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10730 String packageName = ps.name; 10731 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10732 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10733 // Retrieve object to delete permissions for shared user later on 10734 final PackageSetting deletedPs; 10735 // reader 10736 synchronized (mPackages) { 10737 deletedPs = mSettings.mPackages.get(packageName); 10738 if (outInfo != null) { 10739 outInfo.removedPackage = packageName; 10740 outInfo.removedUsers = deletedPs != null 10741 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10742 : null; 10743 } 10744 } 10745 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10746 removeDataDirsLI(packageName); 10747 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10748 } 10749 // writer 10750 synchronized (mPackages) { 10751 if (deletedPs != null) { 10752 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10753 if (outInfo != null) { 10754 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10755 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10756 } 10757 if (deletedPs != null) { 10758 updatePermissionsLPw(deletedPs.name, null, 0); 10759 if (deletedPs.sharedUser != null) { 10760 // remove permissions associated with package 10761 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10762 } 10763 } 10764 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10765 } 10766 // make sure to preserve per-user disabled state if this removal was just 10767 // a downgrade of a system app to the factory package 10768 if (allUserHandles != null && perUserInstalled != null) { 10769 if (DEBUG_REMOVE) { 10770 Slog.d(TAG, "Propagating install state across downgrade"); 10771 } 10772 for (int i = 0; i < allUserHandles.length; i++) { 10773 if (DEBUG_REMOVE) { 10774 Slog.d(TAG, " user " + allUserHandles[i] 10775 + " => " + perUserInstalled[i]); 10776 } 10777 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10778 } 10779 } 10780 } 10781 // can downgrade to reader 10782 if (writeSettings) { 10783 // Save settings now 10784 mSettings.writeLPr(); 10785 } 10786 } 10787 if (outInfo != null) { 10788 // A user ID was deleted here. Go through all users and remove it 10789 // from KeyStore. 10790 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10791 } 10792 } 10793 10794 static boolean locationIsPrivileged(File path) { 10795 try { 10796 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10797 .getCanonicalPath(); 10798 return path.getCanonicalPath().startsWith(privilegedAppDir); 10799 } catch (IOException e) { 10800 Slog.e(TAG, "Unable to access code path " + path); 10801 } 10802 return false; 10803 } 10804 10805 /* 10806 * Tries to delete system package. 10807 */ 10808 private boolean deleteSystemPackageLI(PackageSetting newPs, 10809 int[] allUserHandles, boolean[] perUserInstalled, 10810 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10811 final boolean applyUserRestrictions 10812 = (allUserHandles != null) && (perUserInstalled != null); 10813 PackageSetting disabledPs = null; 10814 // Confirm if the system package has been updated 10815 // An updated system app can be deleted. This will also have to restore 10816 // the system pkg from system partition 10817 // reader 10818 synchronized (mPackages) { 10819 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10820 } 10821 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10822 + " disabledPs=" + disabledPs); 10823 if (disabledPs == null) { 10824 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10825 return false; 10826 } else if (DEBUG_REMOVE) { 10827 Slog.d(TAG, "Deleting system pkg from data partition"); 10828 } 10829 if (DEBUG_REMOVE) { 10830 if (applyUserRestrictions) { 10831 Slog.d(TAG, "Remembering install states:"); 10832 for (int i = 0; i < allUserHandles.length; i++) { 10833 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10834 } 10835 } 10836 } 10837 // Delete the updated package 10838 outInfo.isRemovedPackageSystemUpdate = true; 10839 if (disabledPs.versionCode < newPs.versionCode) { 10840 // Delete data for downgrades 10841 flags &= ~PackageManager.DELETE_KEEP_DATA; 10842 } else { 10843 // Preserve data by setting flag 10844 flags |= PackageManager.DELETE_KEEP_DATA; 10845 } 10846 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10847 allUserHandles, perUserInstalled, outInfo, writeSettings); 10848 if (!ret) { 10849 return false; 10850 } 10851 // writer 10852 synchronized (mPackages) { 10853 // Reinstate the old system package 10854 mSettings.enableSystemPackageLPw(newPs.name); 10855 // Remove any native libraries from the upgraded package. 10856 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10857 } 10858 // Install the system package 10859 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10860 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10861 if (locationIsPrivileged(disabledPs.codePath)) { 10862 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10863 } 10864 10865 final PackageParser.Package newPkg; 10866 try { 10867 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, 10868 null, null); 10869 } catch (PackageManagerException e) { 10870 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10871 return false; 10872 } 10873 10874 // writer 10875 synchronized (mPackages) { 10876 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10877 updatePermissionsLPw(newPkg.packageName, newPkg, 10878 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10879 if (applyUserRestrictions) { 10880 if (DEBUG_REMOVE) { 10881 Slog.d(TAG, "Propagating install state across reinstall"); 10882 } 10883 for (int i = 0; i < allUserHandles.length; i++) { 10884 if (DEBUG_REMOVE) { 10885 Slog.d(TAG, " user " + allUserHandles[i] 10886 + " => " + perUserInstalled[i]); 10887 } 10888 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10889 } 10890 // Regardless of writeSettings we need to ensure that this restriction 10891 // state propagation is persisted 10892 mSettings.writeAllUsersPackageRestrictionsLPr(); 10893 } 10894 // can downgrade to reader here 10895 if (writeSettings) { 10896 mSettings.writeLPr(); 10897 } 10898 } 10899 return true; 10900 } 10901 10902 private boolean deleteInstalledPackageLI(PackageSetting ps, 10903 boolean deleteCodeAndResources, int flags, 10904 int[] allUserHandles, boolean[] perUserInstalled, 10905 PackageRemovedInfo outInfo, boolean writeSettings) { 10906 if (outInfo != null) { 10907 outInfo.uid = ps.appId; 10908 } 10909 10910 // Delete package data from internal structures and also remove data if flag is set 10911 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10912 10913 // Delete application code and resources 10914 if (deleteCodeAndResources && (outInfo != null)) { 10915 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10916 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10917 getAppDexInstructionSets(ps), isMultiArch(ps)); 10918 } 10919 return true; 10920 } 10921 10922 @Override 10923 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10924 int userId) { 10925 mContext.enforceCallingOrSelfPermission( 10926 android.Manifest.permission.DELETE_PACKAGES, null); 10927 synchronized (mPackages) { 10928 PackageSetting ps = mSettings.mPackages.get(packageName); 10929 if (ps == null) { 10930 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10931 return false; 10932 } 10933 if (!ps.getInstalled(userId)) { 10934 // Can't block uninstall for an app that is not installed or enabled. 10935 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10936 return false; 10937 } 10938 ps.setBlockUninstall(blockUninstall, userId); 10939 mSettings.writePackageRestrictionsLPr(userId); 10940 } 10941 return true; 10942 } 10943 10944 @Override 10945 public boolean getBlockUninstallForUser(String packageName, int userId) { 10946 synchronized (mPackages) { 10947 PackageSetting ps = mSettings.mPackages.get(packageName); 10948 if (ps == null) { 10949 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10950 return false; 10951 } 10952 return ps.getBlockUninstall(userId); 10953 } 10954 } 10955 10956 /* 10957 * This method handles package deletion in general 10958 */ 10959 private boolean deletePackageLI(String packageName, UserHandle user, 10960 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10961 int flags, PackageRemovedInfo outInfo, 10962 boolean writeSettings) { 10963 if (packageName == null) { 10964 Slog.w(TAG, "Attempt to delete null packageName."); 10965 return false; 10966 } 10967 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10968 PackageSetting ps; 10969 boolean dataOnly = false; 10970 int removeUser = -1; 10971 int appId = -1; 10972 synchronized (mPackages) { 10973 ps = mSettings.mPackages.get(packageName); 10974 if (ps == null) { 10975 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10976 return false; 10977 } 10978 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10979 && user.getIdentifier() != UserHandle.USER_ALL) { 10980 // The caller is asking that the package only be deleted for a single 10981 // user. To do this, we just mark its uninstalled state and delete 10982 // its data. If this is a system app, we only allow this to happen if 10983 // they have set the special DELETE_SYSTEM_APP which requests different 10984 // semantics than normal for uninstalling system apps. 10985 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10986 ps.setUserState(user.getIdentifier(), 10987 COMPONENT_ENABLED_STATE_DEFAULT, 10988 false, //installed 10989 true, //stopped 10990 true, //notLaunched 10991 false, //hidden 10992 null, null, null, 10993 false // blockUninstall 10994 ); 10995 if (!isSystemApp(ps)) { 10996 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10997 // Other user still have this package installed, so all 10998 // we need to do is clear this user's data and save that 10999 // it is uninstalled. 11000 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11001 removeUser = user.getIdentifier(); 11002 appId = ps.appId; 11003 mSettings.writePackageRestrictionsLPr(removeUser); 11004 } else { 11005 // We need to set it back to 'installed' so the uninstall 11006 // broadcasts will be sent correctly. 11007 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11008 ps.setInstalled(true, user.getIdentifier()); 11009 } 11010 } else { 11011 // This is a system app, so we assume that the 11012 // other users still have this package installed, so all 11013 // we need to do is clear this user's data and save that 11014 // it is uninstalled. 11015 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11016 removeUser = user.getIdentifier(); 11017 appId = ps.appId; 11018 mSettings.writePackageRestrictionsLPr(removeUser); 11019 } 11020 } 11021 } 11022 11023 if (removeUser >= 0) { 11024 // From above, we determined that we are deleting this only 11025 // for a single user. Continue the work here. 11026 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11027 if (outInfo != null) { 11028 outInfo.removedPackage = packageName; 11029 outInfo.removedAppId = appId; 11030 outInfo.removedUsers = new int[] {removeUser}; 11031 } 11032 mInstaller.clearUserData(packageName, removeUser); 11033 removeKeystoreDataIfNeeded(removeUser, appId); 11034 schedulePackageCleaning(packageName, removeUser, false); 11035 return true; 11036 } 11037 11038 if (dataOnly) { 11039 // Delete application data first 11040 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11041 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11042 return true; 11043 } 11044 11045 boolean ret = false; 11046 if (isSystemApp(ps)) { 11047 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11048 // When an updated system application is deleted we delete the existing resources as well and 11049 // fall back to existing code in system partition 11050 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11051 flags, outInfo, writeSettings); 11052 } else { 11053 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11054 // Kill application pre-emptively especially for apps on sd. 11055 killApplication(packageName, ps.appId, "uninstall pkg"); 11056 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11057 allUserHandles, perUserInstalled, 11058 outInfo, writeSettings); 11059 } 11060 11061 return ret; 11062 } 11063 11064 private final class ClearStorageConnection implements ServiceConnection { 11065 IMediaContainerService mContainerService; 11066 11067 @Override 11068 public void onServiceConnected(ComponentName name, IBinder service) { 11069 synchronized (this) { 11070 mContainerService = IMediaContainerService.Stub.asInterface(service); 11071 notifyAll(); 11072 } 11073 } 11074 11075 @Override 11076 public void onServiceDisconnected(ComponentName name) { 11077 } 11078 } 11079 11080 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11081 final boolean mounted; 11082 if (Environment.isExternalStorageEmulated()) { 11083 mounted = true; 11084 } else { 11085 final String status = Environment.getExternalStorageState(); 11086 11087 mounted = status.equals(Environment.MEDIA_MOUNTED) 11088 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11089 } 11090 11091 if (!mounted) { 11092 return; 11093 } 11094 11095 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11096 int[] users; 11097 if (userId == UserHandle.USER_ALL) { 11098 users = sUserManager.getUserIds(); 11099 } else { 11100 users = new int[] { userId }; 11101 } 11102 final ClearStorageConnection conn = new ClearStorageConnection(); 11103 if (mContext.bindServiceAsUser( 11104 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11105 try { 11106 for (int curUser : users) { 11107 long timeout = SystemClock.uptimeMillis() + 5000; 11108 synchronized (conn) { 11109 long now = SystemClock.uptimeMillis(); 11110 while (conn.mContainerService == null && now < timeout) { 11111 try { 11112 conn.wait(timeout - now); 11113 } catch (InterruptedException e) { 11114 } 11115 } 11116 } 11117 if (conn.mContainerService == null) { 11118 return; 11119 } 11120 11121 final UserEnvironment userEnv = new UserEnvironment(curUser); 11122 clearDirectory(conn.mContainerService, 11123 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11124 if (allData) { 11125 clearDirectory(conn.mContainerService, 11126 userEnv.buildExternalStorageAppDataDirs(packageName)); 11127 clearDirectory(conn.mContainerService, 11128 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11129 } 11130 } 11131 } finally { 11132 mContext.unbindService(conn); 11133 } 11134 } 11135 } 11136 11137 @Override 11138 public void clearApplicationUserData(final String packageName, 11139 final IPackageDataObserver observer, final int userId) { 11140 mContext.enforceCallingOrSelfPermission( 11141 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11142 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11143 // Queue up an async operation since the package deletion may take a little while. 11144 mHandler.post(new Runnable() { 11145 public void run() { 11146 mHandler.removeCallbacks(this); 11147 final boolean succeeded; 11148 synchronized (mInstallLock) { 11149 succeeded = clearApplicationUserDataLI(packageName, userId); 11150 } 11151 clearExternalStorageDataSync(packageName, userId, true); 11152 if (succeeded) { 11153 // invoke DeviceStorageMonitor's update method to clear any notifications 11154 DeviceStorageMonitorInternal 11155 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11156 if (dsm != null) { 11157 dsm.checkMemory(); 11158 } 11159 } 11160 if(observer != null) { 11161 try { 11162 observer.onRemoveCompleted(packageName, succeeded); 11163 } catch (RemoteException e) { 11164 Log.i(TAG, "Observer no longer exists."); 11165 } 11166 } //end if observer 11167 } //end run 11168 }); 11169 } 11170 11171 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11172 if (packageName == null) { 11173 Slog.w(TAG, "Attempt to delete null packageName."); 11174 return false; 11175 } 11176 PackageParser.Package p; 11177 boolean dataOnly = false; 11178 final int appId; 11179 synchronized (mPackages) { 11180 p = mPackages.get(packageName); 11181 if (p == null) { 11182 dataOnly = true; 11183 PackageSetting ps = mSettings.mPackages.get(packageName); 11184 if ((ps == null) || (ps.pkg == null)) { 11185 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11186 return false; 11187 } 11188 p = ps.pkg; 11189 } 11190 if (!dataOnly) { 11191 // need to check this only for fully installed applications 11192 if (p == null) { 11193 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11194 return false; 11195 } 11196 final ApplicationInfo applicationInfo = p.applicationInfo; 11197 if (applicationInfo == null) { 11198 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11199 return false; 11200 } 11201 } 11202 if (p != null && p.applicationInfo != null) { 11203 appId = p.applicationInfo.uid; 11204 } else { 11205 appId = -1; 11206 } 11207 } 11208 int retCode = mInstaller.clearUserData(packageName, userId); 11209 if (retCode < 0) { 11210 Slog.w(TAG, "Couldn't remove cache files for package: " 11211 + packageName); 11212 return false; 11213 } 11214 removeKeystoreDataIfNeeded(userId, appId); 11215 return true; 11216 } 11217 11218 /** 11219 * Remove entries from the keystore daemon. Will only remove it if the 11220 * {@code appId} is valid. 11221 */ 11222 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11223 if (appId < 0) { 11224 return; 11225 } 11226 11227 final KeyStore keyStore = KeyStore.getInstance(); 11228 if (keyStore != null) { 11229 if (userId == UserHandle.USER_ALL) { 11230 for (final int individual : sUserManager.getUserIds()) { 11231 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11232 } 11233 } else { 11234 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11235 } 11236 } else { 11237 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11238 } 11239 } 11240 11241 @Override 11242 public void deleteApplicationCacheFiles(final String packageName, 11243 final IPackageDataObserver observer) { 11244 mContext.enforceCallingOrSelfPermission( 11245 android.Manifest.permission.DELETE_CACHE_FILES, null); 11246 // Queue up an async operation since the package deletion may take a little while. 11247 final int userId = UserHandle.getCallingUserId(); 11248 mHandler.post(new Runnable() { 11249 public void run() { 11250 mHandler.removeCallbacks(this); 11251 final boolean succeded; 11252 synchronized (mInstallLock) { 11253 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11254 } 11255 clearExternalStorageDataSync(packageName, userId, false); 11256 if(observer != null) { 11257 try { 11258 observer.onRemoveCompleted(packageName, succeded); 11259 } catch (RemoteException e) { 11260 Log.i(TAG, "Observer no longer exists."); 11261 } 11262 } //end if observer 11263 } //end run 11264 }); 11265 } 11266 11267 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11268 if (packageName == null) { 11269 Slog.w(TAG, "Attempt to delete null packageName."); 11270 return false; 11271 } 11272 PackageParser.Package p; 11273 synchronized (mPackages) { 11274 p = mPackages.get(packageName); 11275 } 11276 if (p == null) { 11277 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11278 return false; 11279 } 11280 final ApplicationInfo applicationInfo = p.applicationInfo; 11281 if (applicationInfo == null) { 11282 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11283 return false; 11284 } 11285 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11286 if (retCode < 0) { 11287 Slog.w(TAG, "Couldn't remove cache files for package: " 11288 + packageName + " u" + userId); 11289 return false; 11290 } 11291 return true; 11292 } 11293 11294 @Override 11295 public void getPackageSizeInfo(final String packageName, int userHandle, 11296 final IPackageStatsObserver observer) { 11297 mContext.enforceCallingOrSelfPermission( 11298 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11299 if (packageName == null) { 11300 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11301 } 11302 11303 PackageStats stats = new PackageStats(packageName, userHandle); 11304 11305 /* 11306 * Queue up an async operation since the package measurement may take a 11307 * little while. 11308 */ 11309 Message msg = mHandler.obtainMessage(INIT_COPY); 11310 msg.obj = new MeasureParams(stats, observer); 11311 mHandler.sendMessage(msg); 11312 } 11313 11314 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11315 PackageStats pStats) { 11316 if (packageName == null) { 11317 Slog.w(TAG, "Attempt to get size of null packageName."); 11318 return false; 11319 } 11320 PackageParser.Package p; 11321 boolean dataOnly = false; 11322 String libDirRoot = null; 11323 String asecPath = null; 11324 PackageSetting ps = null; 11325 synchronized (mPackages) { 11326 p = mPackages.get(packageName); 11327 ps = mSettings.mPackages.get(packageName); 11328 if(p == null) { 11329 dataOnly = true; 11330 if((ps == null) || (ps.pkg == null)) { 11331 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11332 return false; 11333 } 11334 p = ps.pkg; 11335 } 11336 if (ps != null) { 11337 libDirRoot = ps.legacyNativeLibraryPathString; 11338 } 11339 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11340 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11341 if (secureContainerId != null) { 11342 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11343 } 11344 } 11345 } 11346 String publicSrcDir = null; 11347 if(!dataOnly) { 11348 final ApplicationInfo applicationInfo = p.applicationInfo; 11349 if (applicationInfo == null) { 11350 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11351 return false; 11352 } 11353 if (isForwardLocked(p)) { 11354 publicSrcDir = applicationInfo.getBaseResourcePath(); 11355 } 11356 } 11357 // TODO: extend to measure size of split APKs 11358 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11359 // not just the first level. 11360 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11361 // just the primary. 11362 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11363 publicSrcDir, asecPath, getAppDexInstructionSets(ps), 11364 pStats); 11365 if (res < 0) { 11366 return false; 11367 } 11368 11369 // Fix-up for forward-locked applications in ASEC containers. 11370 if (!isExternal(p)) { 11371 pStats.codeSize += pStats.externalCodeSize; 11372 pStats.externalCodeSize = 0L; 11373 } 11374 11375 return true; 11376 } 11377 11378 11379 @Override 11380 public void addPackageToPreferred(String packageName) { 11381 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11382 } 11383 11384 @Override 11385 public void removePackageFromPreferred(String packageName) { 11386 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11387 } 11388 11389 @Override 11390 public List<PackageInfo> getPreferredPackages(int flags) { 11391 return new ArrayList<PackageInfo>(); 11392 } 11393 11394 private int getUidTargetSdkVersionLockedLPr(int uid) { 11395 Object obj = mSettings.getUserIdLPr(uid); 11396 if (obj instanceof SharedUserSetting) { 11397 final SharedUserSetting sus = (SharedUserSetting) obj; 11398 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11399 final Iterator<PackageSetting> it = sus.packages.iterator(); 11400 while (it.hasNext()) { 11401 final PackageSetting ps = it.next(); 11402 if (ps.pkg != null) { 11403 int v = ps.pkg.applicationInfo.targetSdkVersion; 11404 if (v < vers) vers = v; 11405 } 11406 } 11407 return vers; 11408 } else if (obj instanceof PackageSetting) { 11409 final PackageSetting ps = (PackageSetting) obj; 11410 if (ps.pkg != null) { 11411 return ps.pkg.applicationInfo.targetSdkVersion; 11412 } 11413 } 11414 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11415 } 11416 11417 @Override 11418 public void addPreferredActivity(IntentFilter filter, int match, 11419 ComponentName[] set, ComponentName activity, int userId) { 11420 addPreferredActivityInternal(filter, match, set, activity, true, userId); 11421 } 11422 11423 private void addPreferredActivityInternal(IntentFilter filter, int match, 11424 ComponentName[] set, ComponentName activity, boolean always, int userId) { 11425 // writer 11426 int callingUid = Binder.getCallingUid(); 11427 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11428 if (filter.countActions() == 0) { 11429 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11430 return; 11431 } 11432 synchronized (mPackages) { 11433 if (mContext.checkCallingOrSelfPermission( 11434 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11435 != PackageManager.PERMISSION_GRANTED) { 11436 if (getUidTargetSdkVersionLockedLPr(callingUid) 11437 < Build.VERSION_CODES.FROYO) { 11438 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11439 + callingUid); 11440 return; 11441 } 11442 mContext.enforceCallingOrSelfPermission( 11443 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11444 } 11445 11446 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 11447 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11448 mSettings.editPreferredActivitiesLPw(userId).addFilter( 11449 new PreferredActivity(filter, match, set, activity, always)); 11450 mSettings.writePackageRestrictionsLPr(userId); 11451 } 11452 } 11453 11454 @Override 11455 public void replacePreferredActivity(IntentFilter filter, int match, 11456 ComponentName[] set, ComponentName activity, int userId) { 11457 if (filter.countActions() != 1) { 11458 throw new IllegalArgumentException( 11459 "replacePreferredActivity expects filter to have only 1 action."); 11460 } 11461 if (filter.countDataAuthorities() != 0 11462 || filter.countDataPaths() != 0 11463 || filter.countDataSchemes() > 1 11464 || filter.countDataTypes() != 0) { 11465 throw new IllegalArgumentException( 11466 "replacePreferredActivity expects filter to have no data authorities, " + 11467 "paths, or types; and at most one scheme."); 11468 } 11469 11470 final int callingUid = Binder.getCallingUid(); 11471 enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity"); 11472 final int callingUserId = UserHandle.getUserId(callingUid); 11473 synchronized (mPackages) { 11474 if (mContext.checkCallingOrSelfPermission( 11475 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11476 != PackageManager.PERMISSION_GRANTED) { 11477 if (getUidTargetSdkVersionLockedLPr(callingUid) 11478 < Build.VERSION_CODES.FROYO) { 11479 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11480 + Binder.getCallingUid()); 11481 return; 11482 } 11483 mContext.enforceCallingOrSelfPermission( 11484 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11485 } 11486 11487 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 11488 if (pir != null) { 11489 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 11490 if (filter.countDataSchemes() == 1) { 11491 Uri.Builder builder = new Uri.Builder(); 11492 builder.scheme(filter.getDataScheme(0)); 11493 intent.setData(builder.build()); 11494 } 11495 List<PreferredActivity> matches = pir.queryIntent( 11496 intent, null, true, callingUserId); 11497 if (DEBUG_PREFERRED) { 11498 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 11499 } 11500 for (int i = 0; i < matches.size(); i++) { 11501 PreferredActivity pa = matches.get(i); 11502 if (DEBUG_PREFERRED) { 11503 Slog.i(TAG, "Removing preferred activity " 11504 + pa.mPref.mComponent + ":"); 11505 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11506 } 11507 pir.removeFilter(pa); 11508 } 11509 } 11510 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 11511 } 11512 } 11513 11514 @Override 11515 public void clearPackagePreferredActivities(String packageName) { 11516 final int uid = Binder.getCallingUid(); 11517 // writer 11518 synchronized (mPackages) { 11519 PackageParser.Package pkg = mPackages.get(packageName); 11520 if (pkg == null || pkg.applicationInfo.uid != uid) { 11521 if (mContext.checkCallingOrSelfPermission( 11522 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11523 != PackageManager.PERMISSION_GRANTED) { 11524 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11525 < Build.VERSION_CODES.FROYO) { 11526 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11527 + Binder.getCallingUid()); 11528 return; 11529 } 11530 mContext.enforceCallingOrSelfPermission( 11531 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11532 } 11533 } 11534 11535 int user = UserHandle.getCallingUserId(); 11536 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11537 mSettings.writePackageRestrictionsLPr(user); 11538 scheduleWriteSettingsLocked(); 11539 } 11540 } 11541 } 11542 11543 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11544 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11545 ArrayList<PreferredActivity> removed = null; 11546 boolean changed = false; 11547 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11548 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11549 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11550 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11551 continue; 11552 } 11553 Iterator<PreferredActivity> it = pir.filterIterator(); 11554 while (it.hasNext()) { 11555 PreferredActivity pa = it.next(); 11556 // Mark entry for removal only if it matches the package name 11557 // and the entry is of type "always". 11558 if (packageName == null || 11559 (pa.mPref.mComponent.getPackageName().equals(packageName) 11560 && pa.mPref.mAlways)) { 11561 if (removed == null) { 11562 removed = new ArrayList<PreferredActivity>(); 11563 } 11564 removed.add(pa); 11565 } 11566 } 11567 if (removed != null) { 11568 for (int j=0; j<removed.size(); j++) { 11569 PreferredActivity pa = removed.get(j); 11570 pir.removeFilter(pa); 11571 } 11572 changed = true; 11573 } 11574 } 11575 return changed; 11576 } 11577 11578 @Override 11579 public void resetPreferredActivities(int userId) { 11580 mContext.enforceCallingOrSelfPermission( 11581 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11582 // writer 11583 synchronized (mPackages) { 11584 int user = UserHandle.getCallingUserId(); 11585 clearPackagePreferredActivitiesLPw(null, user); 11586 mSettings.readDefaultPreferredAppsLPw(this, user); 11587 mSettings.writePackageRestrictionsLPr(user); 11588 scheduleWriteSettingsLocked(); 11589 } 11590 } 11591 11592 @Override 11593 public int getPreferredActivities(List<IntentFilter> outFilters, 11594 List<ComponentName> outActivities, String packageName) { 11595 11596 int num = 0; 11597 final int userId = UserHandle.getCallingUserId(); 11598 // reader 11599 synchronized (mPackages) { 11600 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11601 if (pir != null) { 11602 final Iterator<PreferredActivity> it = pir.filterIterator(); 11603 while (it.hasNext()) { 11604 final PreferredActivity pa = it.next(); 11605 if (packageName == null 11606 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11607 && pa.mPref.mAlways)) { 11608 if (outFilters != null) { 11609 outFilters.add(new IntentFilter(pa)); 11610 } 11611 if (outActivities != null) { 11612 outActivities.add(pa.mPref.mComponent); 11613 } 11614 } 11615 } 11616 } 11617 } 11618 11619 return num; 11620 } 11621 11622 @Override 11623 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11624 int userId) { 11625 int callingUid = Binder.getCallingUid(); 11626 if (callingUid != Process.SYSTEM_UID) { 11627 throw new SecurityException( 11628 "addPersistentPreferredActivity can only be run by the system"); 11629 } 11630 if (filter.countActions() == 0) { 11631 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11632 return; 11633 } 11634 synchronized (mPackages) { 11635 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11636 " :"); 11637 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11638 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11639 new PersistentPreferredActivity(filter, activity)); 11640 mSettings.writePackageRestrictionsLPr(userId); 11641 } 11642 } 11643 11644 @Override 11645 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11646 int callingUid = Binder.getCallingUid(); 11647 if (callingUid != Process.SYSTEM_UID) { 11648 throw new SecurityException( 11649 "clearPackagePersistentPreferredActivities can only be run by the system"); 11650 } 11651 ArrayList<PersistentPreferredActivity> removed = null; 11652 boolean changed = false; 11653 synchronized (mPackages) { 11654 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11655 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11656 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11657 .valueAt(i); 11658 if (userId != thisUserId) { 11659 continue; 11660 } 11661 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11662 while (it.hasNext()) { 11663 PersistentPreferredActivity ppa = it.next(); 11664 // Mark entry for removal only if it matches the package name. 11665 if (ppa.mComponent.getPackageName().equals(packageName)) { 11666 if (removed == null) { 11667 removed = new ArrayList<PersistentPreferredActivity>(); 11668 } 11669 removed.add(ppa); 11670 } 11671 } 11672 if (removed != null) { 11673 for (int j=0; j<removed.size(); j++) { 11674 PersistentPreferredActivity ppa = removed.get(j); 11675 ppir.removeFilter(ppa); 11676 } 11677 changed = true; 11678 } 11679 } 11680 11681 if (changed) { 11682 mSettings.writePackageRestrictionsLPr(userId); 11683 } 11684 } 11685 } 11686 11687 @Override 11688 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11689 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11690 mContext.enforceCallingOrSelfPermission( 11691 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11692 int callingUid = Binder.getCallingUid(); 11693 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11694 if (intentFilter.countActions() == 0) { 11695 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11696 return; 11697 } 11698 synchronized (mPackages) { 11699 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11700 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11701 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11702 mSettings.writePackageRestrictionsLPr(sourceUserId); 11703 } 11704 } 11705 11706 @Override 11707 public void addCrossProfileIntentsForPackage(String packageName, 11708 int sourceUserId, int targetUserId) { 11709 mContext.enforceCallingOrSelfPermission( 11710 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11711 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11712 mSettings.writePackageRestrictionsLPr(sourceUserId); 11713 } 11714 11715 @Override 11716 public void removeCrossProfileIntentsForPackage(String packageName, 11717 int sourceUserId, int targetUserId) { 11718 mContext.enforceCallingOrSelfPermission( 11719 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11720 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11721 mSettings.writePackageRestrictionsLPr(sourceUserId); 11722 } 11723 11724 @Override 11725 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11726 int ownerUserId) { 11727 mContext.enforceCallingOrSelfPermission( 11728 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11729 int callingUid = Binder.getCallingUid(); 11730 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11731 int callingUserId = UserHandle.getUserId(callingUid); 11732 synchronized (mPackages) { 11733 CrossProfileIntentResolver resolver = 11734 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11735 HashSet<CrossProfileIntentFilter> set = 11736 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11737 for (CrossProfileIntentFilter filter : set) { 11738 if (filter.getOwnerPackage().equals(ownerPackage) 11739 && filter.getOwnerUserId() == callingUserId) { 11740 resolver.removeFilter(filter); 11741 } 11742 } 11743 mSettings.writePackageRestrictionsLPr(sourceUserId); 11744 } 11745 } 11746 11747 // Enforcing that callingUid is owning pkg on userId 11748 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11749 // The system owns everything. 11750 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11751 return; 11752 } 11753 int callingUserId = UserHandle.getUserId(callingUid); 11754 if (callingUserId != userId) { 11755 throw new SecurityException("calling uid " + callingUid 11756 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11757 + callingUserId); 11758 } 11759 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11760 if (pi == null) { 11761 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11762 + callingUserId); 11763 } 11764 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11765 throw new SecurityException("Calling uid " + callingUid 11766 + " does not own package " + pkg); 11767 } 11768 } 11769 11770 @Override 11771 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11772 Intent intent = new Intent(Intent.ACTION_MAIN); 11773 intent.addCategory(Intent.CATEGORY_HOME); 11774 11775 final int callingUserId = UserHandle.getCallingUserId(); 11776 List<ResolveInfo> list = queryIntentActivities(intent, null, 11777 PackageManager.GET_META_DATA, callingUserId); 11778 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11779 true, false, false, callingUserId); 11780 11781 allHomeCandidates.clear(); 11782 if (list != null) { 11783 for (ResolveInfo ri : list) { 11784 allHomeCandidates.add(ri); 11785 } 11786 } 11787 return (preferred == null || preferred.activityInfo == null) 11788 ? null 11789 : new ComponentName(preferred.activityInfo.packageName, 11790 preferred.activityInfo.name); 11791 } 11792 11793 /** 11794 * Check if calling UID is the current home app. This handles both the case 11795 * where the user has selected a specific home app, and where there is only 11796 * one home app. 11797 */ 11798 public boolean checkCallerIsHomeApp() { 11799 final Intent intent = new Intent(Intent.ACTION_MAIN); 11800 intent.addCategory(Intent.CATEGORY_HOME); 11801 11802 final int callingUid = Binder.getCallingUid(); 11803 final int callingUserId = UserHandle.getCallingUserId(); 11804 final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId); 11805 final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true, 11806 false, false, callingUserId); 11807 11808 if (preferredHome != null) { 11809 if (callingUid == preferredHome.activityInfo.applicationInfo.uid) { 11810 return true; 11811 } 11812 } else { 11813 for (ResolveInfo info : allHomes) { 11814 if (callingUid == info.activityInfo.applicationInfo.uid) { 11815 return true; 11816 } 11817 } 11818 } 11819 11820 return false; 11821 } 11822 11823 /** 11824 * Enforce that calling UID is the current home app. This handles both the 11825 * case where the user has selected a specific home app, and where there is 11826 * only one home app. 11827 */ 11828 public void enforceCallerIsHomeApp() { 11829 if (!checkCallerIsHomeApp()) { 11830 throw new SecurityException("Caller is not currently selected home app"); 11831 } 11832 } 11833 11834 @Override 11835 public void setApplicationEnabledSetting(String appPackageName, 11836 int newState, int flags, int userId, String callingPackage) { 11837 if (!sUserManager.exists(userId)) return; 11838 if (callingPackage == null) { 11839 callingPackage = Integer.toString(Binder.getCallingUid()); 11840 } 11841 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11842 } 11843 11844 @Override 11845 public void setComponentEnabledSetting(ComponentName componentName, 11846 int newState, int flags, int userId) { 11847 if (!sUserManager.exists(userId)) return; 11848 setEnabledSetting(componentName.getPackageName(), 11849 componentName.getClassName(), newState, flags, userId, null); 11850 } 11851 11852 private void setEnabledSetting(final String packageName, String className, int newState, 11853 final int flags, int userId, String callingPackage) { 11854 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11855 || newState == COMPONENT_ENABLED_STATE_ENABLED 11856 || newState == COMPONENT_ENABLED_STATE_DISABLED 11857 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11858 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11859 throw new IllegalArgumentException("Invalid new component state: " 11860 + newState); 11861 } 11862 PackageSetting pkgSetting; 11863 final int uid = Binder.getCallingUid(); 11864 final int permission = mContext.checkCallingOrSelfPermission( 11865 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11866 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11867 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11868 boolean sendNow = false; 11869 boolean isApp = (className == null); 11870 String componentName = isApp ? packageName : className; 11871 int packageUid = -1; 11872 ArrayList<String> components; 11873 11874 // writer 11875 synchronized (mPackages) { 11876 pkgSetting = mSettings.mPackages.get(packageName); 11877 if (pkgSetting == null) { 11878 if (className == null) { 11879 throw new IllegalArgumentException( 11880 "Unknown package: " + packageName); 11881 } 11882 throw new IllegalArgumentException( 11883 "Unknown component: " + packageName 11884 + "/" + className); 11885 } 11886 // Allow root and verify that userId is not being specified by a different user 11887 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11888 throw new SecurityException( 11889 "Permission Denial: attempt to change component state from pid=" 11890 + Binder.getCallingPid() 11891 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11892 } 11893 if (className == null) { 11894 // We're dealing with an application/package level state change 11895 if (pkgSetting.getEnabled(userId) == newState) { 11896 // Nothing to do 11897 return; 11898 } 11899 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11900 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11901 // Don't care about who enables an app. 11902 callingPackage = null; 11903 } 11904 pkgSetting.setEnabled(newState, userId, callingPackage); 11905 // pkgSetting.pkg.mSetEnabled = newState; 11906 } else { 11907 // We're dealing with a component level state change 11908 // First, verify that this is a valid class name. 11909 PackageParser.Package pkg = pkgSetting.pkg; 11910 if (pkg == null || !pkg.hasComponentClassName(className)) { 11911 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11912 throw new IllegalArgumentException("Component class " + className 11913 + " does not exist in " + packageName); 11914 } else { 11915 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11916 + className + " does not exist in " + packageName); 11917 } 11918 } 11919 switch (newState) { 11920 case COMPONENT_ENABLED_STATE_ENABLED: 11921 if (!pkgSetting.enableComponentLPw(className, userId)) { 11922 return; 11923 } 11924 break; 11925 case COMPONENT_ENABLED_STATE_DISABLED: 11926 if (!pkgSetting.disableComponentLPw(className, userId)) { 11927 return; 11928 } 11929 break; 11930 case COMPONENT_ENABLED_STATE_DEFAULT: 11931 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11932 return; 11933 } 11934 break; 11935 default: 11936 Slog.e(TAG, "Invalid new component state: " + newState); 11937 return; 11938 } 11939 } 11940 mSettings.writePackageRestrictionsLPr(userId); 11941 components = mPendingBroadcasts.get(userId, packageName); 11942 final boolean newPackage = components == null; 11943 if (newPackage) { 11944 components = new ArrayList<String>(); 11945 } 11946 if (!components.contains(componentName)) { 11947 components.add(componentName); 11948 } 11949 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11950 sendNow = true; 11951 // Purge entry from pending broadcast list if another one exists already 11952 // since we are sending one right away. 11953 mPendingBroadcasts.remove(userId, packageName); 11954 } else { 11955 if (newPackage) { 11956 mPendingBroadcasts.put(userId, packageName, components); 11957 } 11958 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11959 // Schedule a message 11960 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11961 } 11962 } 11963 } 11964 11965 long callingId = Binder.clearCallingIdentity(); 11966 try { 11967 if (sendNow) { 11968 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11969 sendPackageChangedBroadcast(packageName, 11970 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11971 } 11972 } finally { 11973 Binder.restoreCallingIdentity(callingId); 11974 } 11975 } 11976 11977 private void sendPackageChangedBroadcast(String packageName, 11978 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11979 if (DEBUG_INSTALL) 11980 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11981 + componentNames); 11982 Bundle extras = new Bundle(4); 11983 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11984 String nameList[] = new String[componentNames.size()]; 11985 componentNames.toArray(nameList); 11986 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11987 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11988 extras.putInt(Intent.EXTRA_UID, packageUid); 11989 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11990 new int[] {UserHandle.getUserId(packageUid)}); 11991 } 11992 11993 @Override 11994 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11995 if (!sUserManager.exists(userId)) return; 11996 final int uid = Binder.getCallingUid(); 11997 final int permission = mContext.checkCallingOrSelfPermission( 11998 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11999 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12000 enforceCrossUserPermission(uid, userId, true, "stop package"); 12001 // writer 12002 synchronized (mPackages) { 12003 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12004 uid, userId)) { 12005 scheduleWritePackageRestrictionsLocked(userId); 12006 } 12007 } 12008 } 12009 12010 @Override 12011 public String getInstallerPackageName(String packageName) { 12012 // reader 12013 synchronized (mPackages) { 12014 return mSettings.getInstallerPackageNameLPr(packageName); 12015 } 12016 } 12017 12018 @Override 12019 public int getApplicationEnabledSetting(String packageName, int userId) { 12020 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12021 int uid = Binder.getCallingUid(); 12022 enforceCrossUserPermission(uid, userId, false, "get enabled"); 12023 // reader 12024 synchronized (mPackages) { 12025 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12026 } 12027 } 12028 12029 @Override 12030 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12031 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12032 int uid = Binder.getCallingUid(); 12033 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 12034 // reader 12035 synchronized (mPackages) { 12036 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12037 } 12038 } 12039 12040 @Override 12041 public void enterSafeMode() { 12042 enforceSystemOrRoot("Only the system can request entering safe mode"); 12043 12044 if (!mSystemReady) { 12045 mSafeMode = true; 12046 } 12047 } 12048 12049 @Override 12050 public void systemReady() { 12051 mSystemReady = true; 12052 12053 // Read the compatibilty setting when the system is ready. 12054 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12055 mContext.getContentResolver(), 12056 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12057 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12058 if (DEBUG_SETTINGS) { 12059 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12060 } 12061 12062 synchronized (mPackages) { 12063 // Verify that all of the preferred activity components actually 12064 // exist. It is possible for applications to be updated and at 12065 // that point remove a previously declared activity component that 12066 // had been set as a preferred activity. We try to clean this up 12067 // the next time we encounter that preferred activity, but it is 12068 // possible for the user flow to never be able to return to that 12069 // situation so here we do a sanity check to make sure we haven't 12070 // left any junk around. 12071 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12072 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12073 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12074 removed.clear(); 12075 for (PreferredActivity pa : pir.filterSet()) { 12076 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12077 removed.add(pa); 12078 } 12079 } 12080 if (removed.size() > 0) { 12081 for (int r=0; r<removed.size(); r++) { 12082 PreferredActivity pa = removed.get(r); 12083 Slog.w(TAG, "Removing dangling preferred activity: " 12084 + pa.mPref.mComponent); 12085 pir.removeFilter(pa); 12086 } 12087 mSettings.writePackageRestrictionsLPr( 12088 mSettings.mPreferredActivities.keyAt(i)); 12089 } 12090 } 12091 } 12092 sUserManager.systemReady(); 12093 } 12094 12095 @Override 12096 public boolean isSafeMode() { 12097 return mSafeMode; 12098 } 12099 12100 @Override 12101 public boolean hasSystemUidErrors() { 12102 return mHasSystemUidErrors; 12103 } 12104 12105 static String arrayToString(int[] array) { 12106 StringBuffer buf = new StringBuffer(128); 12107 buf.append('['); 12108 if (array != null) { 12109 for (int i=0; i<array.length; i++) { 12110 if (i > 0) buf.append(", "); 12111 buf.append(array[i]); 12112 } 12113 } 12114 buf.append(']'); 12115 return buf.toString(); 12116 } 12117 12118 static class DumpState { 12119 public static final int DUMP_LIBS = 1 << 0; 12120 public static final int DUMP_FEATURES = 1 << 1; 12121 public static final int DUMP_RESOLVERS = 1 << 2; 12122 public static final int DUMP_PERMISSIONS = 1 << 3; 12123 public static final int DUMP_PACKAGES = 1 << 4; 12124 public static final int DUMP_SHARED_USERS = 1 << 5; 12125 public static final int DUMP_MESSAGES = 1 << 6; 12126 public static final int DUMP_PROVIDERS = 1 << 7; 12127 public static final int DUMP_VERIFIERS = 1 << 8; 12128 public static final int DUMP_PREFERRED = 1 << 9; 12129 public static final int DUMP_PREFERRED_XML = 1 << 10; 12130 public static final int DUMP_KEYSETS = 1 << 11; 12131 public static final int DUMP_VERSION = 1 << 12; 12132 public static final int DUMP_INSTALLS = 1 << 13; 12133 12134 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12135 12136 private int mTypes; 12137 12138 private int mOptions; 12139 12140 private boolean mTitlePrinted; 12141 12142 private SharedUserSetting mSharedUser; 12143 12144 public boolean isDumping(int type) { 12145 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12146 return true; 12147 } 12148 12149 return (mTypes & type) != 0; 12150 } 12151 12152 public void setDump(int type) { 12153 mTypes |= type; 12154 } 12155 12156 public boolean isOptionEnabled(int option) { 12157 return (mOptions & option) != 0; 12158 } 12159 12160 public void setOptionEnabled(int option) { 12161 mOptions |= option; 12162 } 12163 12164 public boolean onTitlePrinted() { 12165 final boolean printed = mTitlePrinted; 12166 mTitlePrinted = true; 12167 return printed; 12168 } 12169 12170 public boolean getTitlePrinted() { 12171 return mTitlePrinted; 12172 } 12173 12174 public void setTitlePrinted(boolean enabled) { 12175 mTitlePrinted = enabled; 12176 } 12177 12178 public SharedUserSetting getSharedUser() { 12179 return mSharedUser; 12180 } 12181 12182 public void setSharedUser(SharedUserSetting user) { 12183 mSharedUser = user; 12184 } 12185 } 12186 12187 @Override 12188 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12189 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12190 != PackageManager.PERMISSION_GRANTED) { 12191 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12192 + Binder.getCallingPid() 12193 + ", uid=" + Binder.getCallingUid() 12194 + " without permission " 12195 + android.Manifest.permission.DUMP); 12196 return; 12197 } 12198 12199 DumpState dumpState = new DumpState(); 12200 boolean fullPreferred = false; 12201 boolean checkin = false; 12202 12203 String packageName = null; 12204 12205 int opti = 0; 12206 while (opti < args.length) { 12207 String opt = args[opti]; 12208 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12209 break; 12210 } 12211 opti++; 12212 if ("-a".equals(opt)) { 12213 // Right now we only know how to print all. 12214 } else if ("-h".equals(opt)) { 12215 pw.println("Package manager dump options:"); 12216 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12217 pw.println(" --checkin: dump for a checkin"); 12218 pw.println(" -f: print details of intent filters"); 12219 pw.println(" -h: print this help"); 12220 pw.println(" cmd may be one of:"); 12221 pw.println(" l[ibraries]: list known shared libraries"); 12222 pw.println(" f[ibraries]: list device features"); 12223 pw.println(" k[eysets]: print known keysets"); 12224 pw.println(" r[esolvers]: dump intent resolvers"); 12225 pw.println(" perm[issions]: dump permissions"); 12226 pw.println(" pref[erred]: print preferred package settings"); 12227 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12228 pw.println(" prov[iders]: dump content providers"); 12229 pw.println(" p[ackages]: dump installed packages"); 12230 pw.println(" s[hared-users]: dump shared user IDs"); 12231 pw.println(" m[essages]: print collected runtime messages"); 12232 pw.println(" v[erifiers]: print package verifier info"); 12233 pw.println(" version: print database version info"); 12234 pw.println(" write: write current settings now"); 12235 pw.println(" <package.name>: info about given package"); 12236 pw.println(" installs: details about install sessions"); 12237 return; 12238 } else if ("--checkin".equals(opt)) { 12239 checkin = true; 12240 } else if ("-f".equals(opt)) { 12241 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12242 } else { 12243 pw.println("Unknown argument: " + opt + "; use -h for help"); 12244 } 12245 } 12246 12247 // Is the caller requesting to dump a particular piece of data? 12248 if (opti < args.length) { 12249 String cmd = args[opti]; 12250 opti++; 12251 // Is this a package name? 12252 if ("android".equals(cmd) || cmd.contains(".")) { 12253 packageName = cmd; 12254 // When dumping a single package, we always dump all of its 12255 // filter information since the amount of data will be reasonable. 12256 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12257 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12258 dumpState.setDump(DumpState.DUMP_LIBS); 12259 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12260 dumpState.setDump(DumpState.DUMP_FEATURES); 12261 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12262 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12263 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12264 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12265 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12266 dumpState.setDump(DumpState.DUMP_PREFERRED); 12267 } else if ("preferred-xml".equals(cmd)) { 12268 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12269 if (opti < args.length && "--full".equals(args[opti])) { 12270 fullPreferred = true; 12271 opti++; 12272 } 12273 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12274 dumpState.setDump(DumpState.DUMP_PACKAGES); 12275 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12276 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12277 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12278 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12279 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12280 dumpState.setDump(DumpState.DUMP_MESSAGES); 12281 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12282 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12283 } else if ("version".equals(cmd)) { 12284 dumpState.setDump(DumpState.DUMP_VERSION); 12285 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12286 dumpState.setDump(DumpState.DUMP_KEYSETS); 12287 } else if ("write".equals(cmd)) { 12288 synchronized (mPackages) { 12289 mSettings.writeLPr(); 12290 pw.println("Settings written."); 12291 return; 12292 } 12293 } else if ("installs".equals(cmd)) { 12294 dumpState.setDump(DumpState.DUMP_INSTALLS); 12295 } 12296 } 12297 12298 if (checkin) { 12299 pw.println("vers,1"); 12300 } 12301 12302 // reader 12303 synchronized (mPackages) { 12304 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12305 if (!checkin) { 12306 if (dumpState.onTitlePrinted()) 12307 pw.println(); 12308 pw.println("Database versions:"); 12309 pw.print(" SDK Version:"); 12310 pw.print(" internal="); 12311 pw.print(mSettings.mInternalSdkPlatform); 12312 pw.print(" external="); 12313 pw.println(mSettings.mExternalSdkPlatform); 12314 pw.print(" DB Version:"); 12315 pw.print(" internal="); 12316 pw.print(mSettings.mInternalDatabaseVersion); 12317 pw.print(" external="); 12318 pw.println(mSettings.mExternalDatabaseVersion); 12319 } 12320 } 12321 12322 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12323 if (!checkin) { 12324 if (dumpState.onTitlePrinted()) 12325 pw.println(); 12326 pw.println("Verifiers:"); 12327 pw.print(" Required: "); 12328 pw.print(mRequiredVerifierPackage); 12329 pw.print(" (uid="); 12330 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12331 pw.println(")"); 12332 } else if (mRequiredVerifierPackage != null) { 12333 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12334 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12335 } 12336 } 12337 12338 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12339 boolean printedHeader = false; 12340 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12341 while (it.hasNext()) { 12342 String name = it.next(); 12343 SharedLibraryEntry ent = mSharedLibraries.get(name); 12344 if (!checkin) { 12345 if (!printedHeader) { 12346 if (dumpState.onTitlePrinted()) 12347 pw.println(); 12348 pw.println("Libraries:"); 12349 printedHeader = true; 12350 } 12351 pw.print(" "); 12352 } else { 12353 pw.print("lib,"); 12354 } 12355 pw.print(name); 12356 if (!checkin) { 12357 pw.print(" -> "); 12358 } 12359 if (ent.path != null) { 12360 if (!checkin) { 12361 pw.print("(jar) "); 12362 pw.print(ent.path); 12363 } else { 12364 pw.print(",jar,"); 12365 pw.print(ent.path); 12366 } 12367 } else { 12368 if (!checkin) { 12369 pw.print("(apk) "); 12370 pw.print(ent.apk); 12371 } else { 12372 pw.print(",apk,"); 12373 pw.print(ent.apk); 12374 } 12375 } 12376 pw.println(); 12377 } 12378 } 12379 12380 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12381 if (dumpState.onTitlePrinted()) 12382 pw.println(); 12383 if (!checkin) { 12384 pw.println("Features:"); 12385 } 12386 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12387 while (it.hasNext()) { 12388 String name = it.next(); 12389 if (!checkin) { 12390 pw.print(" "); 12391 } else { 12392 pw.print("feat,"); 12393 } 12394 pw.println(name); 12395 } 12396 } 12397 12398 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12399 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12400 : "Activity Resolver Table:", " ", packageName, 12401 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12402 dumpState.setTitlePrinted(true); 12403 } 12404 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12405 : "Receiver Resolver Table:", " ", packageName, 12406 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12407 dumpState.setTitlePrinted(true); 12408 } 12409 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12410 : "Service Resolver Table:", " ", packageName, 12411 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12412 dumpState.setTitlePrinted(true); 12413 } 12414 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12415 : "Provider Resolver Table:", " ", packageName, 12416 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12417 dumpState.setTitlePrinted(true); 12418 } 12419 } 12420 12421 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12422 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12423 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12424 int user = mSettings.mPreferredActivities.keyAt(i); 12425 if (pir.dump(pw, 12426 dumpState.getTitlePrinted() 12427 ? "\nPreferred Activities User " + user + ":" 12428 : "Preferred Activities User " + user + ":", " ", 12429 packageName, true)) { 12430 dumpState.setTitlePrinted(true); 12431 } 12432 } 12433 } 12434 12435 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12436 pw.flush(); 12437 FileOutputStream fout = new FileOutputStream(fd); 12438 BufferedOutputStream str = new BufferedOutputStream(fout); 12439 XmlSerializer serializer = new FastXmlSerializer(); 12440 try { 12441 serializer.setOutput(str, "utf-8"); 12442 serializer.startDocument(null, true); 12443 serializer.setFeature( 12444 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12445 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12446 serializer.endDocument(); 12447 serializer.flush(); 12448 } catch (IllegalArgumentException e) { 12449 pw.println("Failed writing: " + e); 12450 } catch (IllegalStateException e) { 12451 pw.println("Failed writing: " + e); 12452 } catch (IOException e) { 12453 pw.println("Failed writing: " + e); 12454 } 12455 } 12456 12457 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12458 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12459 if (packageName == null) { 12460 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12461 if (iperm == 0) { 12462 if (dumpState.onTitlePrinted()) 12463 pw.println(); 12464 pw.println("AppOp Permissions:"); 12465 } 12466 pw.print(" AppOp Permission "); 12467 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12468 pw.println(":"); 12469 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12470 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12471 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12472 } 12473 } 12474 } 12475 } 12476 12477 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12478 boolean printedSomething = false; 12479 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12480 if (packageName != null && !packageName.equals(p.info.packageName)) { 12481 continue; 12482 } 12483 if (!printedSomething) { 12484 if (dumpState.onTitlePrinted()) 12485 pw.println(); 12486 pw.println("Registered ContentProviders:"); 12487 printedSomething = true; 12488 } 12489 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12490 pw.print(" "); pw.println(p.toString()); 12491 } 12492 printedSomething = false; 12493 for (Map.Entry<String, PackageParser.Provider> entry : 12494 mProvidersByAuthority.entrySet()) { 12495 PackageParser.Provider p = entry.getValue(); 12496 if (packageName != null && !packageName.equals(p.info.packageName)) { 12497 continue; 12498 } 12499 if (!printedSomething) { 12500 if (dumpState.onTitlePrinted()) 12501 pw.println(); 12502 pw.println("ContentProvider Authorities:"); 12503 printedSomething = true; 12504 } 12505 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12506 pw.print(" "); pw.println(p.toString()); 12507 if (p.info != null && p.info.applicationInfo != null) { 12508 final String appInfo = p.info.applicationInfo.toString(); 12509 pw.print(" applicationInfo="); pw.println(appInfo); 12510 } 12511 } 12512 } 12513 12514 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12515 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12516 } 12517 12518 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12519 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12520 } 12521 12522 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12523 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12524 } 12525 12526 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) { 12527 if (dumpState.onTitlePrinted()) pw.println(); 12528 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12529 } 12530 12531 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12532 if (dumpState.onTitlePrinted()) pw.println(); 12533 mSettings.dumpReadMessagesLPr(pw, dumpState); 12534 12535 pw.println(); 12536 pw.println("Package warning messages:"); 12537 final File fname = getSettingsProblemFile(); 12538 FileInputStream in = null; 12539 try { 12540 in = new FileInputStream(fname); 12541 final int avail = in.available(); 12542 final byte[] data = new byte[avail]; 12543 in.read(data); 12544 pw.print(new String(data)); 12545 } catch (FileNotFoundException e) { 12546 } catch (IOException e) { 12547 } finally { 12548 if (in != null) { 12549 try { 12550 in.close(); 12551 } catch (IOException e) { 12552 } 12553 } 12554 } 12555 } 12556 } 12557 } 12558 12559 // ------- apps on sdcard specific code ------- 12560 static final boolean DEBUG_SD_INSTALL = false; 12561 12562 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12563 12564 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12565 12566 private boolean mMediaMounted = false; 12567 12568 private String getEncryptKey() { 12569 try { 12570 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12571 SD_ENCRYPTION_KEYSTORE_NAME); 12572 if (sdEncKey == null) { 12573 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12574 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12575 if (sdEncKey == null) { 12576 Slog.e(TAG, "Failed to create encryption keys"); 12577 return null; 12578 } 12579 } 12580 return sdEncKey; 12581 } catch (NoSuchAlgorithmException nsae) { 12582 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12583 return null; 12584 } catch (IOException ioe) { 12585 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12586 return null; 12587 } 12588 12589 } 12590 12591 /* package */static String getTempContainerId() { 12592 int tmpIdx = 1; 12593 String list[] = PackageHelper.getSecureContainerList(); 12594 if (list != null) { 12595 for (final String name : list) { 12596 // Ignore null and non-temporary container entries 12597 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12598 continue; 12599 } 12600 12601 String subStr = name.substring(mTempContainerPrefix.length()); 12602 try { 12603 int cid = Integer.parseInt(subStr); 12604 if (cid >= tmpIdx) { 12605 tmpIdx = cid + 1; 12606 } 12607 } catch (NumberFormatException e) { 12608 } 12609 } 12610 } 12611 return mTempContainerPrefix + tmpIdx; 12612 } 12613 12614 /* 12615 * Update media status on PackageManager. 12616 */ 12617 @Override 12618 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12619 int callingUid = Binder.getCallingUid(); 12620 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12621 throw new SecurityException("Media status can only be updated by the system"); 12622 } 12623 // reader; this apparently protects mMediaMounted, but should probably 12624 // be a different lock in that case. 12625 synchronized (mPackages) { 12626 Log.i(TAG, "Updating external media status from " 12627 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12628 + (mediaStatus ? "mounted" : "unmounted")); 12629 if (DEBUG_SD_INSTALL) 12630 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12631 + ", mMediaMounted=" + mMediaMounted); 12632 if (mediaStatus == mMediaMounted) { 12633 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12634 : 0, -1); 12635 mHandler.sendMessage(msg); 12636 return; 12637 } 12638 mMediaMounted = mediaStatus; 12639 } 12640 // Queue up an async operation since the package installation may take a 12641 // little while. 12642 mHandler.post(new Runnable() { 12643 public void run() { 12644 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12645 } 12646 }); 12647 } 12648 12649 /** 12650 * Called by MountService when the initial ASECs to scan are available. 12651 * Should block until all the ASEC containers are finished being scanned. 12652 */ 12653 public void scanAvailableAsecs() { 12654 updateExternalMediaStatusInner(true, false, false); 12655 if (mShouldRestoreconData) { 12656 SELinuxMMAC.setRestoreconDone(); 12657 mShouldRestoreconData = false; 12658 } 12659 } 12660 12661 /* 12662 * Collect information of applications on external media, map them against 12663 * existing containers and update information based on current mount status. 12664 * Please note that we always have to report status if reportStatus has been 12665 * set to true especially when unloading packages. 12666 */ 12667 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12668 boolean externalStorage) { 12669 // Collection of uids 12670 int uidArr[] = null; 12671 // Collection of stale containers 12672 HashSet<String> removeCids = new HashSet<String>(); 12673 // Collection of packages on external media with valid containers. 12674 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12675 // Get list of secure containers. 12676 final String list[] = PackageHelper.getSecureContainerList(); 12677 if (list == null || list.length == 0) { 12678 Log.i(TAG, "No secure containers on sdcard"); 12679 } else { 12680 // Process list of secure containers and categorize them 12681 // as active or stale based on their package internal state. 12682 int uidList[] = new int[list.length]; 12683 int num = 0; 12684 // reader 12685 synchronized (mPackages) { 12686 for (String cid : list) { 12687 if (DEBUG_SD_INSTALL) 12688 Log.i(TAG, "Processing container " + cid); 12689 String pkgName = getAsecPackageName(cid); 12690 if (pkgName == null) { 12691 if (DEBUG_SD_INSTALL) 12692 Log.i(TAG, "Container : " + cid + " stale"); 12693 removeCids.add(cid); 12694 continue; 12695 } 12696 if (DEBUG_SD_INSTALL) 12697 Log.i(TAG, "Looking for pkg : " + pkgName); 12698 12699 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12700 if (ps == null) { 12701 Log.i(TAG, "Deleting container with no matching settings " + cid); 12702 removeCids.add(cid); 12703 continue; 12704 } 12705 12706 /* 12707 * Skip packages that are not external if we're unmounting 12708 * external storage. 12709 */ 12710 if (externalStorage && !isMounted && !isExternal(ps)) { 12711 continue; 12712 } 12713 12714 final AsecInstallArgs args = new AsecInstallArgs(cid, 12715 getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps)); 12716 // The package status is changed only if the code path 12717 // matches between settings and the container id. 12718 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12719 if (DEBUG_SD_INSTALL) { 12720 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12721 + " at code path: " + ps.codePathString); 12722 } 12723 12724 // We do have a valid package installed on sdcard 12725 processCids.put(args, ps.codePathString); 12726 final int uid = ps.appId; 12727 if (uid != -1) { 12728 uidList[num++] = uid; 12729 } 12730 } else { 12731 Log.i(TAG, "Deleting stale container for " + cid); 12732 removeCids.add(cid); 12733 } 12734 } 12735 } 12736 12737 if (num > 0) { 12738 // Sort uid list 12739 Arrays.sort(uidList, 0, num); 12740 // Throw away duplicates 12741 uidArr = new int[num]; 12742 uidArr[0] = uidList[0]; 12743 int di = 0; 12744 for (int i = 1; i < num; i++) { 12745 if (uidList[i - 1] != uidList[i]) { 12746 uidArr[di++] = uidList[i]; 12747 } 12748 } 12749 } 12750 } 12751 // Process packages with valid entries. 12752 if (isMounted) { 12753 if (DEBUG_SD_INSTALL) 12754 Log.i(TAG, "Loading packages"); 12755 loadMediaPackages(processCids, uidArr, removeCids); 12756 startCleaningPackages(); 12757 } else { 12758 if (DEBUG_SD_INSTALL) 12759 Log.i(TAG, "Unloading packages"); 12760 unloadMediaPackages(processCids, uidArr, reportStatus); 12761 } 12762 } 12763 12764 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12765 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12766 int size = pkgList.size(); 12767 if (size > 0) { 12768 // Send broadcasts here 12769 Bundle extras = new Bundle(); 12770 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12771 .toArray(new String[size])); 12772 if (uidArr != null) { 12773 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12774 } 12775 if (replacing) { 12776 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12777 } 12778 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12779 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12780 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12781 } 12782 } 12783 12784 /* 12785 * Look at potentially valid container ids from processCids If package 12786 * information doesn't match the one on record or package scanning fails, 12787 * the cid is added to list of removeCids. We currently don't delete stale 12788 * containers. 12789 */ 12790 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12791 HashSet<String> removeCids) { 12792 ArrayList<String> pkgList = new ArrayList<String>(); 12793 Set<AsecInstallArgs> keys = processCids.keySet(); 12794 boolean doGc = false; 12795 for (AsecInstallArgs args : keys) { 12796 String codePath = processCids.get(args); 12797 if (DEBUG_SD_INSTALL) 12798 Log.i(TAG, "Loading container : " + args.cid); 12799 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12800 try { 12801 // Make sure there are no container errors first. 12802 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12803 Slog.e(TAG, "Failed to mount cid : " + args.cid 12804 + " when installing from sdcard"); 12805 continue; 12806 } 12807 // Check code path here. 12808 if (codePath == null || !codePath.equals(args.getCodePath())) { 12809 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12810 + " does not match one in settings " + codePath); 12811 continue; 12812 } 12813 // Parse package 12814 int parseFlags = mDefParseFlags; 12815 if (args.isExternal()) { 12816 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12817 } 12818 if (args.isFwdLocked()) { 12819 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12820 } 12821 12822 doGc = true; 12823 synchronized (mInstallLock) { 12824 PackageParser.Package pkg = null; 12825 try { 12826 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null, null); 12827 } catch (PackageManagerException e) { 12828 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12829 } 12830 // Scan the package 12831 if (pkg != null) { 12832 /* 12833 * TODO why is the lock being held? doPostInstall is 12834 * called in other places without the lock. This needs 12835 * to be straightened out. 12836 */ 12837 // writer 12838 synchronized (mPackages) { 12839 retCode = PackageManager.INSTALL_SUCCEEDED; 12840 pkgList.add(pkg.packageName); 12841 // Post process args 12842 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12843 pkg.applicationInfo.uid); 12844 } 12845 } else { 12846 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12847 } 12848 } 12849 12850 } finally { 12851 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12852 // Don't destroy container here. Wait till gc clears things 12853 // up. 12854 removeCids.add(args.cid); 12855 } 12856 } 12857 } 12858 // writer 12859 synchronized (mPackages) { 12860 // If the platform SDK has changed since the last time we booted, 12861 // we need to re-grant app permission to catch any new ones that 12862 // appear. This is really a hack, and means that apps can in some 12863 // cases get permissions that the user didn't initially explicitly 12864 // allow... it would be nice to have some better way to handle 12865 // this situation. 12866 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12867 if (regrantPermissions) 12868 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12869 + mSdkVersion + "; regranting permissions for external storage"); 12870 mSettings.mExternalSdkPlatform = mSdkVersion; 12871 12872 // Make sure group IDs have been assigned, and any permission 12873 // changes in other apps are accounted for 12874 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12875 | (regrantPermissions 12876 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12877 : 0)); 12878 12879 mSettings.updateExternalDatabaseVersion(); 12880 12881 // can downgrade to reader 12882 // Persist settings 12883 mSettings.writeLPr(); 12884 } 12885 // Send a broadcast to let everyone know we are done processing 12886 if (pkgList.size() > 0) { 12887 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12888 } 12889 // Force gc to avoid any stale parser references that we might have. 12890 if (doGc) { 12891 Runtime.getRuntime().gc(); 12892 } 12893 // List stale containers and destroy stale temporary containers. 12894 if (removeCids != null) { 12895 for (String cid : removeCids) { 12896 if (cid.startsWith(mTempContainerPrefix)) { 12897 Log.i(TAG, "Destroying stale temporary container " + cid); 12898 PackageHelper.destroySdDir(cid); 12899 } else { 12900 Log.w(TAG, "Container " + cid + " is stale"); 12901 } 12902 } 12903 } 12904 } 12905 12906 /* 12907 * Utility method to unload a list of specified containers 12908 */ 12909 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12910 // Just unmount all valid containers. 12911 for (AsecInstallArgs arg : cidArgs) { 12912 synchronized (mInstallLock) { 12913 arg.doPostDeleteLI(false); 12914 } 12915 } 12916 } 12917 12918 /* 12919 * Unload packages mounted on external media. This involves deleting package 12920 * data from internal structures, sending broadcasts about diabled packages, 12921 * gc'ing to free up references, unmounting all secure containers 12922 * corresponding to packages on external media, and posting a 12923 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12924 * that we always have to post this message if status has been requested no 12925 * matter what. 12926 */ 12927 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12928 final boolean reportStatus) { 12929 if (DEBUG_SD_INSTALL) 12930 Log.i(TAG, "unloading media packages"); 12931 ArrayList<String> pkgList = new ArrayList<String>(); 12932 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12933 final Set<AsecInstallArgs> keys = processCids.keySet(); 12934 for (AsecInstallArgs args : keys) { 12935 String pkgName = args.getPackageName(); 12936 if (DEBUG_SD_INSTALL) 12937 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12938 // Delete package internally 12939 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12940 synchronized (mInstallLock) { 12941 boolean res = deletePackageLI(pkgName, null, false, null, null, 12942 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12943 if (res) { 12944 pkgList.add(pkgName); 12945 } else { 12946 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12947 failedList.add(args); 12948 } 12949 } 12950 } 12951 12952 // reader 12953 synchronized (mPackages) { 12954 // We didn't update the settings after removing each package; 12955 // write them now for all packages. 12956 mSettings.writeLPr(); 12957 } 12958 12959 // We have to absolutely send UPDATED_MEDIA_STATUS only 12960 // after confirming that all the receivers processed the ordered 12961 // broadcast when packages get disabled, force a gc to clean things up. 12962 // and unload all the containers. 12963 if (pkgList.size() > 0) { 12964 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12965 new IIntentReceiver.Stub() { 12966 public void performReceive(Intent intent, int resultCode, String data, 12967 Bundle extras, boolean ordered, boolean sticky, 12968 int sendingUser) throws RemoteException { 12969 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12970 reportStatus ? 1 : 0, 1, keys); 12971 mHandler.sendMessage(msg); 12972 } 12973 }); 12974 } else { 12975 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12976 keys); 12977 mHandler.sendMessage(msg); 12978 } 12979 } 12980 12981 /** Binder call */ 12982 @Override 12983 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12984 final int flags) { 12985 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12986 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12987 int returnCode = PackageManager.MOVE_SUCCEEDED; 12988 int currFlags = 0; 12989 int newFlags = 0; 12990 // reader 12991 synchronized (mPackages) { 12992 PackageParser.Package pkg = mPackages.get(packageName); 12993 if (pkg == null) { 12994 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12995 } else { 12996 // Disable moving fwd locked apps and system packages 12997 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12998 Slog.w(TAG, "Cannot move system application"); 12999 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13000 } else if (pkg.mOperationPending) { 13001 Slog.w(TAG, "Attempt to move package which has pending operations"); 13002 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13003 } else { 13004 // Find install location first 13005 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13006 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13007 Slog.w(TAG, "Ambigous flags specified for move location."); 13008 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13009 } else { 13010 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 13011 : PackageManager.INSTALL_INTERNAL; 13012 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 13013 : PackageManager.INSTALL_INTERNAL; 13014 13015 if (newFlags == currFlags) { 13016 Slog.w(TAG, "No move required. Trying to move to same location"); 13017 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13018 } else { 13019 if (isForwardLocked(pkg)) { 13020 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13021 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13022 } 13023 } 13024 } 13025 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13026 pkg.mOperationPending = true; 13027 } 13028 } 13029 } 13030 13031 /* 13032 * TODO this next block probably shouldn't be inside the lock. We 13033 * can't guarantee these won't change after this is fired off 13034 * anyway. 13035 */ 13036 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13037 processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false), 13038 returnCode); 13039 } else { 13040 Message msg = mHandler.obtainMessage(INIT_COPY); 13041 final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 13042 final boolean multiArch = isMultiArch(pkg.applicationInfo); 13043 InstallArgs srcArgs = createInstallArgsForExisting(currFlags, 13044 pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(), 13045 pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch); 13046 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 13047 instructionSets, pkg.applicationInfo.uid, user, multiArch); 13048 msg.obj = mp; 13049 mHandler.sendMessage(msg); 13050 } 13051 } 13052 } 13053 13054 private void processPendingMove(final MoveParams mp, final int currentStatus) { 13055 // Queue up an async operation since the package deletion may take a 13056 // little while. 13057 mHandler.post(new Runnable() { 13058 public void run() { 13059 // TODO fix this; this does nothing. 13060 mHandler.removeCallbacks(this); 13061 int returnCode = currentStatus; 13062 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 13063 int uidArr[] = null; 13064 ArrayList<String> pkgList = null; 13065 synchronized (mPackages) { 13066 PackageParser.Package pkg = mPackages.get(mp.packageName); 13067 if (pkg == null) { 13068 Slog.w(TAG, " Package " + mp.packageName 13069 + " doesn't exist. Aborting move"); 13070 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13071 } else if (!mp.srcArgs.getCodePath().equals( 13072 pkg.applicationInfo.getCodePath())) { 13073 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 13074 + mp.srcArgs.getCodePath() + " to " 13075 + pkg.applicationInfo.getCodePath() 13076 + " Aborting move and returning error"); 13077 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13078 } else { 13079 uidArr = new int[] { 13080 pkg.applicationInfo.uid 13081 }; 13082 pkgList = new ArrayList<String>(); 13083 pkgList.add(mp.packageName); 13084 } 13085 } 13086 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13087 // Send resources unavailable broadcast 13088 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 13089 // Update package code and resource paths 13090 synchronized (mInstallLock) { 13091 synchronized (mPackages) { 13092 PackageParser.Package pkg = mPackages.get(mp.packageName); 13093 // Recheck for package again. 13094 if (pkg == null) { 13095 Slog.w(TAG, " Package " + mp.packageName 13096 + " doesn't exist. Aborting move"); 13097 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13098 } else if (!mp.srcArgs.getCodePath().equals( 13099 pkg.applicationInfo.getCodePath())) { 13100 Slog.w(TAG, "Package " + mp.packageName 13101 + " code path changed from " + mp.srcArgs.getCodePath() 13102 + " to " + pkg.applicationInfo.getCodePath() 13103 + " Aborting move and returning error"); 13104 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13105 } else { 13106 final String oldCodePath = pkg.codePath; 13107 final String newCodePath = mp.targetArgs.getCodePath(); 13108 final String newResPath = mp.targetArgs.getResourcePath(); 13109 // TODO: This assumes the new style of installation. 13110 // should we look at legacyNativeLibraryPath ? 13111 final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath(); 13112 final File newNativeDir = new File(newNativeRoot); 13113 13114 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 13115 // TODO(multiArch): Fix this so that it looks at the existing 13116 // recorded CPU abis from the package. There's no need for a separate 13117 // round of ABI scanning here. 13118 NativeLibraryHelper.Handle handle = null; 13119 try { 13120 handle = NativeLibraryHelper.Handle.create( 13121 new File(newCodePath)); 13122 final int abi = NativeLibraryHelper.findSupportedAbi( 13123 handle, Build.SUPPORTED_ABIS); 13124 if (abi >= 0) { 13125 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 13126 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 13127 } 13128 } catch (IOException ioe) { 13129 Slog.w(TAG, "Unable to extract native libs for package :" 13130 + mp.packageName, ioe); 13131 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13132 } finally { 13133 IoUtils.closeQuietly(handle); 13134 } 13135 } 13136 13137 final int[] users = sUserManager.getUserIds(); 13138 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13139 for (int user : users) { 13140 // TODO(multiArch): Fix this so that it links to the 13141 // correct directory. We're currently pointing to root. but we 13142 // must point to the arch specific subdirectory (if applicable). 13143 // 13144 // TODO(multiArch): Bogus reference to nativeLibraryDir. 13145 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 13146 newNativeRoot, user) < 0) { 13147 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13148 } 13149 } 13150 } 13151 13152 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13153 pkg.codePath = newCodePath; 13154 pkg.baseCodePath = newCodePath; 13155 // Move dex files around 13156 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 13157 // Moving of dex files failed. Set 13158 // error code and abort move. 13159 pkg.codePath = oldCodePath; 13160 pkg.baseCodePath = oldCodePath; 13161 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13162 } 13163 } 13164 13165 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13166 pkg.applicationInfo.setCodePath(newCodePath); 13167 pkg.applicationInfo.setBaseCodePath(newCodePath); 13168 pkg.applicationInfo.setSplitCodePaths(null); 13169 pkg.applicationInfo.setResourcePath(newResPath); 13170 pkg.applicationInfo.setBaseResourcePath(newResPath); 13171 pkg.applicationInfo.setSplitResourcePaths(null); 13172 13173 PackageSetting ps = (PackageSetting) pkg.mExtras; 13174 ps.codePath = new File(pkg.applicationInfo.getCodePath()); 13175 ps.codePathString = ps.codePath.getPath(); 13176 ps.resourcePath = new File(pkg.applicationInfo.getResourcePath()); 13177 ps.resourcePathString = ps.resourcePath.getPath(); 13178 13179 // Note that we don't have to recalculate the primary and secondary 13180 // CPU ABIs because they must already have been calculated during the 13181 // initial install of the app. 13182 ps.legacyNativeLibraryPathString = null; 13183 13184 // Set the application info flag 13185 // correctly. 13186 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 13187 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13188 } else { 13189 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13190 } 13191 ps.setFlags(pkg.applicationInfo.flags); 13192 mAppDirs.remove(oldCodePath); 13193 mAppDirs.put(newCodePath, pkg); 13194 // Persist settings 13195 mSettings.writeLPr(); 13196 } 13197 } 13198 } 13199 } 13200 // Send resources available broadcast 13201 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13202 } 13203 } 13204 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13205 // Clean up failed installation 13206 if (mp.targetArgs != null) { 13207 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 13208 -1); 13209 } 13210 } else { 13211 // Force a gc to clear things up. 13212 Runtime.getRuntime().gc(); 13213 // Delete older code 13214 synchronized (mInstallLock) { 13215 mp.srcArgs.doPostDeleteLI(true); 13216 } 13217 } 13218 13219 // Allow more operations on this file if we didn't fail because 13220 // an operation was already pending for this package. 13221 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 13222 synchronized (mPackages) { 13223 PackageParser.Package pkg = mPackages.get(mp.packageName); 13224 if (pkg != null) { 13225 pkg.mOperationPending = false; 13226 } 13227 } 13228 } 13229 13230 IPackageMoveObserver observer = mp.observer; 13231 if (observer != null) { 13232 try { 13233 observer.packageMoved(mp.packageName, returnCode); 13234 } catch (RemoteException e) { 13235 Log.i(TAG, "Observer no longer exists."); 13236 } 13237 } 13238 } 13239 }); 13240 } 13241 13242 @Override 13243 public boolean setInstallLocation(int loc) { 13244 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13245 null); 13246 if (getInstallLocation() == loc) { 13247 return true; 13248 } 13249 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13250 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13251 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13252 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13253 return true; 13254 } 13255 return false; 13256 } 13257 13258 @Override 13259 public int getInstallLocation() { 13260 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13261 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13262 PackageHelper.APP_INSTALL_AUTO); 13263 } 13264 13265 /** Called by UserManagerService */ 13266 void cleanUpUserLILPw(int userHandle) { 13267 mDirtyUsers.remove(userHandle); 13268 mSettings.removeUserLPw(userHandle); 13269 mPendingBroadcasts.remove(userHandle); 13270 if (mInstaller != null) { 13271 // Technically, we shouldn't be doing this with the package lock 13272 // held. However, this is very rare, and there is already so much 13273 // other disk I/O going on, that we'll let it slide for now. 13274 mInstaller.removeUserDataDirs(userHandle); 13275 } 13276 mUserNeedsBadging.delete(userHandle); 13277 } 13278 13279 /** Called by UserManagerService */ 13280 void createNewUserLILPw(int userHandle, File path) { 13281 if (mInstaller != null) { 13282 mInstaller.createUserConfig(userHandle); 13283 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13284 } 13285 } 13286 13287 @Override 13288 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13289 mContext.enforceCallingOrSelfPermission( 13290 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13291 "Only package verification agents can read the verifier device identity"); 13292 13293 synchronized (mPackages) { 13294 return mSettings.getVerifierDeviceIdentityLPw(); 13295 } 13296 } 13297 13298 @Override 13299 public void setPermissionEnforced(String permission, boolean enforced) { 13300 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13301 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13302 synchronized (mPackages) { 13303 if (mSettings.mReadExternalStorageEnforced == null 13304 || mSettings.mReadExternalStorageEnforced != enforced) { 13305 mSettings.mReadExternalStorageEnforced = enforced; 13306 mSettings.writeLPr(); 13307 } 13308 } 13309 // kill any non-foreground processes so we restart them and 13310 // grant/revoke the GID. 13311 final IActivityManager am = ActivityManagerNative.getDefault(); 13312 if (am != null) { 13313 final long token = Binder.clearCallingIdentity(); 13314 try { 13315 am.killProcessesBelowForeground("setPermissionEnforcement"); 13316 } catch (RemoteException e) { 13317 } finally { 13318 Binder.restoreCallingIdentity(token); 13319 } 13320 } 13321 } else { 13322 throw new IllegalArgumentException("No selective enforcement for " + permission); 13323 } 13324 } 13325 13326 @Override 13327 @Deprecated 13328 public boolean isPermissionEnforced(String permission) { 13329 return true; 13330 } 13331 13332 @Override 13333 public boolean isStorageLow() { 13334 final long token = Binder.clearCallingIdentity(); 13335 try { 13336 final DeviceStorageMonitorInternal 13337 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13338 if (dsm != null) { 13339 return dsm.isMemoryLow(); 13340 } else { 13341 return false; 13342 } 13343 } finally { 13344 Binder.restoreCallingIdentity(token); 13345 } 13346 } 13347 13348 @Override 13349 public IPackageInstaller getPackageInstaller() { 13350 return mInstallerService; 13351 } 13352 13353 private boolean userNeedsBadging(int userId) { 13354 int index = mUserNeedsBadging.indexOfKey(userId); 13355 if (index < 0) { 13356 final UserInfo userInfo; 13357 final long token = Binder.clearCallingIdentity(); 13358 try { 13359 userInfo = sUserManager.getUserInfo(userId); 13360 } finally { 13361 Binder.restoreCallingIdentity(token); 13362 } 13363 final boolean b; 13364 if (userInfo != null && userInfo.isManagedProfile()) { 13365 b = true; 13366 } else { 13367 b = false; 13368 } 13369 mUserNeedsBadging.put(userId, b); 13370 return b; 13371 } 13372 return mUserNeedsBadging.valueAt(index); 13373 } 13374 13375 @Override 13376 public KeySetHandle getKeySetByAlias(String packageName, String alias) { 13377 if (packageName == null || alias == null) { 13378 return null; 13379 } 13380 synchronized(mPackages) { 13381 final PackageParser.Package pkg = mPackages.get(packageName); 13382 if (pkg == null) { 13383 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13384 throw new IllegalArgumentException("Unknown package: " + packageName); 13385 } 13386 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13387 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13388 throw new SecurityException("May not access KeySets defined by" 13389 + " aliases in other applications."); 13390 } 13391 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13392 return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias); 13393 } 13394 } 13395 13396 @Override 13397 public KeySetHandle getSigningKeySet(String packageName) { 13398 if (packageName == null) { 13399 return null; 13400 } 13401 synchronized(mPackages) { 13402 final PackageParser.Package pkg = mPackages.get(packageName); 13403 if (pkg == null) { 13404 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13405 throw new IllegalArgumentException("Unknown package: " + packageName); 13406 } 13407 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13408 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13409 throw new SecurityException("May not access signing KeySet of other apps."); 13410 } 13411 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13412 return ksms.getSigningKeySetByPackageNameLPr(packageName); 13413 } 13414 } 13415 13416 @Override 13417 public boolean isPackageSignedByKeySet(String packageName, IBinder ks) { 13418 if (packageName == null || ks == null) { 13419 return false; 13420 } 13421 synchronized(mPackages) { 13422 final PackageParser.Package pkg = mPackages.get(packageName); 13423 if (pkg == null) { 13424 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13425 throw new IllegalArgumentException("Unknown package: " + packageName); 13426 } 13427 if (ks instanceof KeySetHandle) { 13428 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13429 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks); 13430 } 13431 return false; 13432 } 13433 } 13434 13435 @Override 13436 public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) { 13437 if (packageName == null || ks == null) { 13438 return false; 13439 } 13440 synchronized(mPackages) { 13441 final PackageParser.Package pkg = mPackages.get(packageName); 13442 if (pkg == null) { 13443 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13444 throw new IllegalArgumentException("Unknown package: " + packageName); 13445 } 13446 if (ks instanceof KeySetHandle) { 13447 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13448 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks); 13449 } 13450 return false; 13451 } 13452 } 13453 13454 private static class LegacyPackageDeleteObserver extends PackageDeleteObserver { 13455 private final IPackageDeleteObserver mLegacy; 13456 13457 public LegacyPackageDeleteObserver(IPackageDeleteObserver legacy) { 13458 mLegacy = legacy; 13459 } 13460 13461 @Override 13462 public void onPackageDeleted(String basePackageName, int returnCode, String msg) { 13463 try { 13464 mLegacy.packageDeleted(basePackageName, returnCode); 13465 } catch (RemoteException ignored) { 13466 } 13467 } 13468 } 13469} 13470