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