PackageManagerService.java revision 57137289a2798b8c19f1e9f16bd3f0a71f1b916a
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.InstrumentationInfo; 111import android.content.pm.ManifestDigest; 112import android.content.pm.PackageCleanItem; 113import android.content.pm.PackageInfo; 114import android.content.pm.PackageInfoLite; 115import android.content.pm.PackageInstaller; 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 // Special value for {@code PackageParser.Package#cpuAbiOverride} to indicate 257 // that the cpuAbiOverride must be clear. 258 private static final String CLEAR_ABI_OVERRIDE = "-"; 259 260 static final int SCAN_MONITOR = 1<<0; 261 static final int SCAN_NO_DEX = 1<<1; 262 static final int SCAN_FORCE_DEX = 1<<2; 263 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 264 static final int SCAN_NEW_INSTALL = 1<<4; 265 static final int SCAN_NO_PATHS = 1<<5; 266 static final int SCAN_UPDATE_TIME = 1<<6; 267 static final int SCAN_DEFER_DEX = 1<<7; 268 static final int SCAN_BOOTING = 1<<8; 269 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 270 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 271 272 static final int REMOVE_CHATTY = 1<<16; 273 274 /** 275 * Timeout (in milliseconds) after which the watchdog should declare that 276 * our handler thread is wedged. The usual default for such things is one 277 * minute but we sometimes do very lengthy I/O operations on this thread, 278 * such as installing multi-gigabyte applications, so ours needs to be longer. 279 */ 280 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 281 282 /** 283 * Whether verification is enabled by default. 284 */ 285 private static final boolean DEFAULT_VERIFY_ENABLE = true; 286 287 /** 288 * The default maximum time to wait for the verification agent to return in 289 * milliseconds. 290 */ 291 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 292 293 /** 294 * The default response for package verification timeout. 295 * 296 * This can be either PackageManager.VERIFICATION_ALLOW or 297 * PackageManager.VERIFICATION_REJECT. 298 */ 299 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 300 301 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 302 303 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 304 DEFAULT_CONTAINER_PACKAGE, 305 "com.android.defcontainer.DefaultContainerService"); 306 307 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 308 309 private static final String LIB_DIR_NAME = "lib"; 310 private static final String LIB64_DIR_NAME = "lib64"; 311 312 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 313 314 static final String mTempContainerPrefix = "smdl2tmp"; 315 316 private static String sPreferredInstructionSet; 317 318 final ServiceThread mHandlerThread; 319 320 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 321 private static final String IDMAP_SUFFIX = "@idmap"; 322 323 final PackageHandler mHandler; 324 325 final int mSdkVersion = Build.VERSION.SDK_INT; 326 327 final Context mContext; 328 final boolean mFactoryTest; 329 final boolean mOnlyCore; 330 final DisplayMetrics mMetrics; 331 final int mDefParseFlags; 332 final String[] mSeparateProcesses; 333 334 // This is where all application persistent data goes. 335 final File mAppDataDir; 336 337 // This is where all application persistent data goes for secondary users. 338 final File mUserAppDataDir; 339 340 /** The location for ASEC container files on internal storage. */ 341 final String mAsecInternalPath; 342 343 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 344 // LOCK HELD. Can be called with mInstallLock held. 345 final Installer mInstaller; 346 347 /** Directory where installed third-party apps stored */ 348 final File mAppInstallDir; 349 350 /** 351 * Directory to which applications installed internally have their 352 * 32 bit native libraries copied. 353 */ 354 private File mAppLib32InstallDir; 355 356 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 357 // apps. 358 final File mDrmAppPrivateInstallDir; 359 360 // ---------------------------------------------------------------- 361 362 // Lock for state used when installing and doing other long running 363 // operations. Methods that must be called with this lock held have 364 // the suffix "LI". 365 final Object mInstallLock = new Object(); 366 367 // These are the directories in the 3rd party applications installed dir 368 // that we have currently loaded packages from. Keys are the application's 369 // installed zip file (absolute codePath), and values are Package. 370 final HashMap<String, PackageParser.Package> mAppDirs = 371 new HashMap<String, PackageParser.Package>(); 372 373 // ---------------------------------------------------------------- 374 375 // Keys are String (package name), values are Package. This also serves 376 // as the lock for the global state. Methods that must be called with 377 // this lock held have the prefix "LP". 378 final HashMap<String, PackageParser.Package> mPackages = 379 new HashMap<String, PackageParser.Package>(); 380 381 // Tracks available target package names -> overlay package paths. 382 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 383 new HashMap<String, HashMap<String, PackageParser.Package>>(); 384 385 final Settings mSettings; 386 boolean mRestoredSettings; 387 388 // System configuration read by SystemConfig. 389 final int[] mGlobalGids; 390 final SparseArray<HashSet<String>> mSystemPermissions; 391 final HashMap<String, FeatureInfo> mAvailableFeatures; 392 393 // If mac_permissions.xml was found for seinfo labeling. 394 boolean mFoundPolicyFile; 395 396 // If a recursive restorecon of /data/data/<pkg> is needed. 397 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 398 399 public static final class SharedLibraryEntry { 400 public final String path; 401 public final String apk; 402 403 SharedLibraryEntry(String _path, String _apk) { 404 path = _path; 405 apk = _apk; 406 } 407 } 408 409 // Currently known shared libraries. 410 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 411 new HashMap<String, SharedLibraryEntry>(); 412 413 // All available activities, for your resolving pleasure. 414 final ActivityIntentResolver mActivities = 415 new ActivityIntentResolver(); 416 417 // All available receivers, for your resolving pleasure. 418 final ActivityIntentResolver mReceivers = 419 new ActivityIntentResolver(); 420 421 // All available services, for your resolving pleasure. 422 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 423 424 // All available providers, for your resolving pleasure. 425 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 426 427 // Mapping from provider base names (first directory in content URI codePath) 428 // to the provider information. 429 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 430 new HashMap<String, PackageParser.Provider>(); 431 432 // Mapping from instrumentation class names to info about them. 433 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 434 new HashMap<ComponentName, PackageParser.Instrumentation>(); 435 436 // Mapping from permission names to info about them. 437 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 438 new HashMap<String, PackageParser.PermissionGroup>(); 439 440 // Packages whose data we have transfered into another package, thus 441 // should no longer exist. 442 final HashSet<String> mTransferedPackages = new HashSet<String>(); 443 444 // Broadcast actions that are only available to the system. 445 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 446 447 /** List of packages waiting for verification. */ 448 final SparseArray<PackageVerificationState> mPendingVerification 449 = new SparseArray<PackageVerificationState>(); 450 451 /** Set of packages associated with each app op permission. */ 452 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 453 454 final PackageInstallerService mInstallerService; 455 456 HashSet<PackageParser.Package> mDeferredDexOpt = null; 457 458 // Cache of users who need badging. 459 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 460 461 /** Token for keys in mPendingVerification. */ 462 private int mPendingVerificationToken = 0; 463 464 boolean mSystemReady; 465 boolean mSafeMode; 466 boolean mHasSystemUidErrors; 467 468 ApplicationInfo mAndroidApplication; 469 final ActivityInfo mResolveActivity = new ActivityInfo(); 470 final ResolveInfo mResolveInfo = new ResolveInfo(); 471 ComponentName mResolveComponentName; 472 PackageParser.Package mPlatformPackage; 473 ComponentName mCustomResolverComponentName; 474 475 boolean mResolverReplaced = false; 476 477 // Set of pending broadcasts for aggregating enable/disable of components. 478 static class PendingPackageBroadcasts { 479 // for each user id, a map of <package name -> components within that package> 480 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 481 482 public PendingPackageBroadcasts() { 483 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 484 } 485 486 public ArrayList<String> get(int userId, String packageName) { 487 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 488 return packages.get(packageName); 489 } 490 491 public void put(int userId, String packageName, ArrayList<String> components) { 492 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 493 packages.put(packageName, components); 494 } 495 496 public void remove(int userId, String packageName) { 497 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 498 if (packages != null) { 499 packages.remove(packageName); 500 } 501 } 502 503 public void remove(int userId) { 504 mUidMap.remove(userId); 505 } 506 507 public int userIdCount() { 508 return mUidMap.size(); 509 } 510 511 public int userIdAt(int n) { 512 return mUidMap.keyAt(n); 513 } 514 515 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 516 return mUidMap.get(userId); 517 } 518 519 public int size() { 520 // total number of pending broadcast entries across all userIds 521 int num = 0; 522 for (int i = 0; i< mUidMap.size(); i++) { 523 num += mUidMap.valueAt(i).size(); 524 } 525 return num; 526 } 527 528 public void clear() { 529 mUidMap.clear(); 530 } 531 532 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 533 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 534 if (map == null) { 535 map = new HashMap<String, ArrayList<String>>(); 536 mUidMap.put(userId, map); 537 } 538 return map; 539 } 540 } 541 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 542 543 // Service Connection to remote media container service to copy 544 // package uri's from external media onto secure containers 545 // or internal storage. 546 private IMediaContainerService mContainerService = null; 547 548 static final int SEND_PENDING_BROADCAST = 1; 549 static final int MCS_BOUND = 3; 550 static final int END_COPY = 4; 551 static final int INIT_COPY = 5; 552 static final int MCS_UNBIND = 6; 553 static final int START_CLEANING_PACKAGE = 7; 554 static final int FIND_INSTALL_LOC = 8; 555 static final int POST_INSTALL = 9; 556 static final int MCS_RECONNECT = 10; 557 static final int MCS_GIVE_UP = 11; 558 static final int UPDATED_MEDIA_STATUS = 12; 559 static final int WRITE_SETTINGS = 13; 560 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 561 static final int PACKAGE_VERIFIED = 15; 562 static final int CHECK_PENDING_VERIFICATION = 16; 563 564 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 565 566 // Delay time in millisecs 567 static final int BROADCAST_DELAY = 10 * 1000; 568 569 static UserManagerService sUserManager; 570 571 // Stores a list of users whose package restrictions file needs to be updated 572 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 573 574 final private DefaultContainerConnection mDefContainerConn = 575 new DefaultContainerConnection(); 576 class DefaultContainerConnection implements ServiceConnection { 577 public void onServiceConnected(ComponentName name, IBinder service) { 578 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 579 IMediaContainerService imcs = 580 IMediaContainerService.Stub.asInterface(service); 581 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 582 } 583 584 public void onServiceDisconnected(ComponentName name) { 585 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 586 } 587 }; 588 589 // Recordkeeping of restore-after-install operations that are currently in flight 590 // between the Package Manager and the Backup Manager 591 class PostInstallData { 592 public InstallArgs args; 593 public PackageInstalledInfo res; 594 595 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 596 args = _a; 597 res = _r; 598 } 599 }; 600 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 601 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 602 603 private final String mRequiredVerifierPackage; 604 605 private final PackageUsage mPackageUsage = new PackageUsage(); 606 607 private class PackageUsage { 608 private static final int WRITE_INTERVAL 609 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 610 611 private final Object mFileLock = new Object(); 612 private final AtomicLong mLastWritten = new AtomicLong(0); 613 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 614 615 private boolean mIsHistoricalPackageUsageAvailable = true; 616 617 boolean isHistoricalPackageUsageAvailable() { 618 return mIsHistoricalPackageUsageAvailable; 619 } 620 621 void write(boolean force) { 622 if (force) { 623 writeInternal(); 624 return; 625 } 626 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 627 && !DEBUG_DEXOPT) { 628 return; 629 } 630 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 631 new Thread("PackageUsage_DiskWriter") { 632 @Override 633 public void run() { 634 try { 635 writeInternal(); 636 } finally { 637 mBackgroundWriteRunning.set(false); 638 } 639 } 640 }.start(); 641 } 642 } 643 644 private void writeInternal() { 645 synchronized (mPackages) { 646 synchronized (mFileLock) { 647 AtomicFile file = getFile(); 648 FileOutputStream f = null; 649 try { 650 f = file.startWrite(); 651 BufferedOutputStream out = new BufferedOutputStream(f); 652 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 653 StringBuilder sb = new StringBuilder(); 654 for (PackageParser.Package pkg : mPackages.values()) { 655 if (pkg.mLastPackageUsageTimeInMills == 0) { 656 continue; 657 } 658 sb.setLength(0); 659 sb.append(pkg.packageName); 660 sb.append(' '); 661 sb.append((long)pkg.mLastPackageUsageTimeInMills); 662 sb.append('\n'); 663 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 664 } 665 out.flush(); 666 file.finishWrite(f); 667 } catch (IOException e) { 668 if (f != null) { 669 file.failWrite(f); 670 } 671 Log.e(TAG, "Failed to write package usage times", e); 672 } 673 } 674 } 675 mLastWritten.set(SystemClock.elapsedRealtime()); 676 } 677 678 void readLP() { 679 synchronized (mFileLock) { 680 AtomicFile file = getFile(); 681 BufferedInputStream in = null; 682 try { 683 in = new BufferedInputStream(file.openRead()); 684 StringBuffer sb = new StringBuffer(); 685 while (true) { 686 String packageName = readToken(in, sb, ' '); 687 if (packageName == null) { 688 break; 689 } 690 String timeInMillisString = readToken(in, sb, '\n'); 691 if (timeInMillisString == null) { 692 throw new IOException("Failed to find last usage time for package " 693 + packageName); 694 } 695 PackageParser.Package pkg = mPackages.get(packageName); 696 if (pkg == null) { 697 continue; 698 } 699 long timeInMillis; 700 try { 701 timeInMillis = Long.parseLong(timeInMillisString.toString()); 702 } catch (NumberFormatException e) { 703 throw new IOException("Failed to parse " + timeInMillisString 704 + " as a long.", e); 705 } 706 pkg.mLastPackageUsageTimeInMills = timeInMillis; 707 } 708 } catch (FileNotFoundException expected) { 709 mIsHistoricalPackageUsageAvailable = false; 710 } catch (IOException e) { 711 Log.w(TAG, "Failed to read package usage times", e); 712 } finally { 713 IoUtils.closeQuietly(in); 714 } 715 } 716 mLastWritten.set(SystemClock.elapsedRealtime()); 717 } 718 719 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 720 throws IOException { 721 sb.setLength(0); 722 while (true) { 723 int ch = in.read(); 724 if (ch == -1) { 725 if (sb.length() == 0) { 726 return null; 727 } 728 throw new IOException("Unexpected EOF"); 729 } 730 if (ch == endOfToken) { 731 return sb.toString(); 732 } 733 sb.append((char)ch); 734 } 735 } 736 737 private AtomicFile getFile() { 738 File dataDir = Environment.getDataDirectory(); 739 File systemDir = new File(dataDir, "system"); 740 File fname = new File(systemDir, "package-usage.list"); 741 return new AtomicFile(fname); 742 } 743 } 744 745 class PackageHandler extends Handler { 746 private boolean mBound = false; 747 final ArrayList<HandlerParams> mPendingInstalls = 748 new ArrayList<HandlerParams>(); 749 750 private boolean connectToService() { 751 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 752 " DefaultContainerService"); 753 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 754 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 755 if (mContext.bindServiceAsUser(service, mDefContainerConn, 756 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 757 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 758 mBound = true; 759 return true; 760 } 761 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 762 return false; 763 } 764 765 private void disconnectService() { 766 mContainerService = null; 767 mBound = false; 768 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 769 mContext.unbindService(mDefContainerConn); 770 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 771 } 772 773 PackageHandler(Looper looper) { 774 super(looper); 775 } 776 777 public void handleMessage(Message msg) { 778 try { 779 doHandleMessage(msg); 780 } finally { 781 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 782 } 783 } 784 785 void doHandleMessage(Message msg) { 786 switch (msg.what) { 787 case INIT_COPY: { 788 HandlerParams params = (HandlerParams) msg.obj; 789 int idx = mPendingInstalls.size(); 790 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 791 // If a bind was already initiated we dont really 792 // need to do anything. The pending install 793 // will be processed later on. 794 if (!mBound) { 795 // If this is the only one pending we might 796 // have to bind to the service again. 797 if (!connectToService()) { 798 Slog.e(TAG, "Failed to bind to media container service"); 799 params.serviceError(); 800 return; 801 } else { 802 // Once we bind to the service, the first 803 // pending request will be processed. 804 mPendingInstalls.add(idx, params); 805 } 806 } else { 807 mPendingInstalls.add(idx, params); 808 // Already bound to the service. Just make 809 // sure we trigger off processing the first request. 810 if (idx == 0) { 811 mHandler.sendEmptyMessage(MCS_BOUND); 812 } 813 } 814 break; 815 } 816 case MCS_BOUND: { 817 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 818 if (msg.obj != null) { 819 mContainerService = (IMediaContainerService) msg.obj; 820 } 821 if (mContainerService == null) { 822 // Something seriously wrong. Bail out 823 Slog.e(TAG, "Cannot bind to media container service"); 824 for (HandlerParams params : mPendingInstalls) { 825 // Indicate service bind error 826 params.serviceError(); 827 } 828 mPendingInstalls.clear(); 829 } else if (mPendingInstalls.size() > 0) { 830 HandlerParams params = mPendingInstalls.get(0); 831 if (params != null) { 832 if (params.startCopy()) { 833 // We are done... look for more work or to 834 // go idle. 835 if (DEBUG_SD_INSTALL) Log.i(TAG, 836 "Checking for more work or unbind..."); 837 // Delete pending install 838 if (mPendingInstalls.size() > 0) { 839 mPendingInstalls.remove(0); 840 } 841 if (mPendingInstalls.size() == 0) { 842 if (mBound) { 843 if (DEBUG_SD_INSTALL) Log.i(TAG, 844 "Posting delayed MCS_UNBIND"); 845 removeMessages(MCS_UNBIND); 846 Message ubmsg = obtainMessage(MCS_UNBIND); 847 // Unbind after a little delay, to avoid 848 // continual thrashing. 849 sendMessageDelayed(ubmsg, 10000); 850 } 851 } else { 852 // There are more pending requests in queue. 853 // Just post MCS_BOUND message to trigger processing 854 // of next pending install. 855 if (DEBUG_SD_INSTALL) Log.i(TAG, 856 "Posting MCS_BOUND for next work"); 857 mHandler.sendEmptyMessage(MCS_BOUND); 858 } 859 } 860 } 861 } else { 862 // Should never happen ideally. 863 Slog.w(TAG, "Empty queue"); 864 } 865 break; 866 } 867 case MCS_RECONNECT: { 868 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 869 if (mPendingInstalls.size() > 0) { 870 if (mBound) { 871 disconnectService(); 872 } 873 if (!connectToService()) { 874 Slog.e(TAG, "Failed to bind to media container service"); 875 for (HandlerParams params : mPendingInstalls) { 876 // Indicate service bind error 877 params.serviceError(); 878 } 879 mPendingInstalls.clear(); 880 } 881 } 882 break; 883 } 884 case MCS_UNBIND: { 885 // If there is no actual work left, then time to unbind. 886 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 887 888 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 889 if (mBound) { 890 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 891 892 disconnectService(); 893 } 894 } else if (mPendingInstalls.size() > 0) { 895 // There are more pending requests in queue. 896 // Just post MCS_BOUND message to trigger processing 897 // of next pending install. 898 mHandler.sendEmptyMessage(MCS_BOUND); 899 } 900 901 break; 902 } 903 case MCS_GIVE_UP: { 904 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 905 mPendingInstalls.remove(0); 906 break; 907 } 908 case SEND_PENDING_BROADCAST: { 909 String packages[]; 910 ArrayList<String> components[]; 911 int size = 0; 912 int uids[]; 913 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 914 synchronized (mPackages) { 915 if (mPendingBroadcasts == null) { 916 return; 917 } 918 size = mPendingBroadcasts.size(); 919 if (size <= 0) { 920 // Nothing to be done. Just return 921 return; 922 } 923 packages = new String[size]; 924 components = new ArrayList[size]; 925 uids = new int[size]; 926 int i = 0; // filling out the above arrays 927 928 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 929 int packageUserId = mPendingBroadcasts.userIdAt(n); 930 Iterator<Map.Entry<String, ArrayList<String>>> it 931 = mPendingBroadcasts.packagesForUserId(packageUserId) 932 .entrySet().iterator(); 933 while (it.hasNext() && i < size) { 934 Map.Entry<String, ArrayList<String>> ent = it.next(); 935 packages[i] = ent.getKey(); 936 components[i] = ent.getValue(); 937 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 938 uids[i] = (ps != null) 939 ? UserHandle.getUid(packageUserId, ps.appId) 940 : -1; 941 i++; 942 } 943 } 944 size = i; 945 mPendingBroadcasts.clear(); 946 } 947 // Send broadcasts 948 for (int i = 0; i < size; i++) { 949 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 950 } 951 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 952 break; 953 } 954 case START_CLEANING_PACKAGE: { 955 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 956 final String packageName = (String)msg.obj; 957 final int userId = msg.arg1; 958 final boolean andCode = msg.arg2 != 0; 959 synchronized (mPackages) { 960 if (userId == UserHandle.USER_ALL) { 961 int[] users = sUserManager.getUserIds(); 962 for (int user : users) { 963 mSettings.addPackageToCleanLPw( 964 new PackageCleanItem(user, packageName, andCode)); 965 } 966 } else { 967 mSettings.addPackageToCleanLPw( 968 new PackageCleanItem(userId, packageName, andCode)); 969 } 970 } 971 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 972 startCleaningPackages(); 973 } break; 974 case POST_INSTALL: { 975 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 976 PostInstallData data = mRunningInstalls.get(msg.arg1); 977 mRunningInstalls.delete(msg.arg1); 978 boolean deleteOld = false; 979 980 if (data != null) { 981 InstallArgs args = data.args; 982 PackageInstalledInfo res = data.res; 983 984 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 985 res.removedInfo.sendBroadcast(false, true, false); 986 Bundle extras = new Bundle(1); 987 extras.putInt(Intent.EXTRA_UID, res.uid); 988 // Determine the set of users who are adding this 989 // package for the first time vs. those who are seeing 990 // an update. 991 int[] firstUsers; 992 int[] updateUsers = new int[0]; 993 if (res.origUsers == null || res.origUsers.length == 0) { 994 firstUsers = res.newUsers; 995 } else { 996 firstUsers = new int[0]; 997 for (int i=0; i<res.newUsers.length; i++) { 998 int user = res.newUsers[i]; 999 boolean isNew = true; 1000 for (int j=0; j<res.origUsers.length; j++) { 1001 if (res.origUsers[j] == user) { 1002 isNew = false; 1003 break; 1004 } 1005 } 1006 if (isNew) { 1007 int[] newFirst = new int[firstUsers.length+1]; 1008 System.arraycopy(firstUsers, 0, newFirst, 0, 1009 firstUsers.length); 1010 newFirst[firstUsers.length] = user; 1011 firstUsers = newFirst; 1012 } else { 1013 int[] newUpdate = new int[updateUsers.length+1]; 1014 System.arraycopy(updateUsers, 0, newUpdate, 0, 1015 updateUsers.length); 1016 newUpdate[updateUsers.length] = user; 1017 updateUsers = newUpdate; 1018 } 1019 } 1020 } 1021 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1022 res.pkg.applicationInfo.packageName, 1023 extras, null, null, firstUsers); 1024 final boolean update = res.removedInfo.removedPackage != null; 1025 if (update) { 1026 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1027 } 1028 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1029 res.pkg.applicationInfo.packageName, 1030 extras, null, null, updateUsers); 1031 if (update) { 1032 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1033 res.pkg.applicationInfo.packageName, 1034 extras, null, null, updateUsers); 1035 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1036 null, null, 1037 res.pkg.applicationInfo.packageName, null, updateUsers); 1038 1039 // treat asec-hosted packages like removable media on upgrade 1040 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1041 if (DEBUG_INSTALL) { 1042 Slog.i(TAG, "upgrading pkg " + res.pkg 1043 + " is ASEC-hosted -> AVAILABLE"); 1044 } 1045 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1046 ArrayList<String> pkgList = new ArrayList<String>(1); 1047 pkgList.add(res.pkg.applicationInfo.packageName); 1048 sendResourcesChangedBroadcast(true, true, 1049 pkgList,uidArray, null); 1050 } 1051 } 1052 if (res.removedInfo.args != null) { 1053 // Remove the replaced package's older resources safely now 1054 deleteOld = true; 1055 } 1056 1057 // Log current value of "unknown sources" setting 1058 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1059 getUnknownSourcesSettings()); 1060 } 1061 // Force a gc to clear up things 1062 Runtime.getRuntime().gc(); 1063 // We delete after a gc for applications on sdcard. 1064 if (deleteOld) { 1065 synchronized (mInstallLock) { 1066 res.removedInfo.args.doPostDeleteLI(true); 1067 } 1068 } 1069 if (args.observer != null) { 1070 try { 1071 Bundle extras = extrasForInstallResult(res); 1072 args.observer.onPackageInstalled(res.name, res.returnCode, 1073 res.returnMsg, extras); 1074 } catch (RemoteException e) { 1075 Slog.i(TAG, "Observer no longer exists."); 1076 } 1077 } 1078 } else { 1079 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1080 } 1081 } break; 1082 case UPDATED_MEDIA_STATUS: { 1083 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1084 boolean reportStatus = msg.arg1 == 1; 1085 boolean doGc = msg.arg2 == 1; 1086 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1087 if (doGc) { 1088 // Force a gc to clear up stale containers. 1089 Runtime.getRuntime().gc(); 1090 } 1091 if (msg.obj != null) { 1092 @SuppressWarnings("unchecked") 1093 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1094 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1095 // Unload containers 1096 unloadAllContainers(args); 1097 } 1098 if (reportStatus) { 1099 try { 1100 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1101 PackageHelper.getMountService().finishMediaUpdate(); 1102 } catch (RemoteException e) { 1103 Log.e(TAG, "MountService not running?"); 1104 } 1105 } 1106 } break; 1107 case WRITE_SETTINGS: { 1108 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1109 synchronized (mPackages) { 1110 removeMessages(WRITE_SETTINGS); 1111 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1112 mSettings.writeLPr(); 1113 mDirtyUsers.clear(); 1114 } 1115 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1116 } break; 1117 case WRITE_PACKAGE_RESTRICTIONS: { 1118 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1119 synchronized (mPackages) { 1120 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1121 for (int userId : mDirtyUsers) { 1122 mSettings.writePackageRestrictionsLPr(userId); 1123 } 1124 mDirtyUsers.clear(); 1125 } 1126 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1127 } break; 1128 case CHECK_PENDING_VERIFICATION: { 1129 final int verificationId = msg.arg1; 1130 final PackageVerificationState state = mPendingVerification.get(verificationId); 1131 1132 if ((state != null) && !state.timeoutExtended()) { 1133 final InstallArgs args = state.getInstallArgs(); 1134 final Uri originUri = Uri.fromFile(args.originFile); 1135 1136 Slog.i(TAG, "Verification timed out for " + originUri); 1137 mPendingVerification.remove(verificationId); 1138 1139 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1140 1141 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1142 Slog.i(TAG, "Continuing with installation of " + originUri); 1143 state.setVerifierResponse(Binder.getCallingUid(), 1144 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1145 broadcastPackageVerified(verificationId, originUri, 1146 PackageManager.VERIFICATION_ALLOW, 1147 state.getInstallArgs().getUser()); 1148 try { 1149 ret = args.copyApk(mContainerService, true); 1150 } catch (RemoteException e) { 1151 Slog.e(TAG, "Could not contact the ContainerService"); 1152 } 1153 } else { 1154 broadcastPackageVerified(verificationId, originUri, 1155 PackageManager.VERIFICATION_REJECT, 1156 state.getInstallArgs().getUser()); 1157 } 1158 1159 processPendingInstall(args, ret); 1160 mHandler.sendEmptyMessage(MCS_UNBIND); 1161 } 1162 break; 1163 } 1164 case PACKAGE_VERIFIED: { 1165 final int verificationId = msg.arg1; 1166 1167 final PackageVerificationState state = mPendingVerification.get(verificationId); 1168 if (state == null) { 1169 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1170 break; 1171 } 1172 1173 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1174 1175 state.setVerifierResponse(response.callerUid, response.code); 1176 1177 if (state.isVerificationComplete()) { 1178 mPendingVerification.remove(verificationId); 1179 1180 final InstallArgs args = state.getInstallArgs(); 1181 final Uri originUri = Uri.fromFile(args.originFile); 1182 1183 int ret; 1184 if (state.isInstallAllowed()) { 1185 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1186 broadcastPackageVerified(verificationId, originUri, 1187 response.code, state.getInstallArgs().getUser()); 1188 try { 1189 ret = args.copyApk(mContainerService, true); 1190 } catch (RemoteException e) { 1191 Slog.e(TAG, "Could not contact the ContainerService"); 1192 } 1193 } else { 1194 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1195 } 1196 1197 processPendingInstall(args, ret); 1198 1199 mHandler.sendEmptyMessage(MCS_UNBIND); 1200 } 1201 1202 break; 1203 } 1204 } 1205 } 1206 } 1207 1208 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1209 Bundle extras = null; 1210 switch (res.returnCode) { 1211 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1212 extras = new Bundle(); 1213 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1214 res.origPermission); 1215 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1216 res.origPackage); 1217 break; 1218 } 1219 } 1220 return extras; 1221 } 1222 1223 void scheduleWriteSettingsLocked() { 1224 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1225 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1226 } 1227 } 1228 1229 void scheduleWritePackageRestrictionsLocked(int userId) { 1230 if (!sUserManager.exists(userId)) return; 1231 mDirtyUsers.add(userId); 1232 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1233 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1234 } 1235 } 1236 1237 public static final PackageManagerService main(Context context, Installer installer, 1238 boolean factoryTest, boolean onlyCore) { 1239 PackageManagerService m = new PackageManagerService(context, installer, 1240 factoryTest, onlyCore); 1241 ServiceManager.addService("package", m); 1242 return m; 1243 } 1244 1245 static String[] splitString(String str, char sep) { 1246 int count = 1; 1247 int i = 0; 1248 while ((i=str.indexOf(sep, i)) >= 0) { 1249 count++; 1250 i++; 1251 } 1252 1253 String[] res = new String[count]; 1254 i=0; 1255 count = 0; 1256 int lastI=0; 1257 while ((i=str.indexOf(sep, i)) >= 0) { 1258 res[count] = str.substring(lastI, i); 1259 count++; 1260 i++; 1261 lastI = i; 1262 } 1263 res[count] = str.substring(lastI, str.length()); 1264 return res; 1265 } 1266 1267 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1268 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1269 Context.DISPLAY_SERVICE); 1270 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1271 } 1272 1273 public PackageManagerService(Context context, Installer installer, 1274 boolean factoryTest, boolean onlyCore) { 1275 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1276 SystemClock.uptimeMillis()); 1277 1278 if (mSdkVersion <= 0) { 1279 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1280 } 1281 1282 mContext = context; 1283 mFactoryTest = factoryTest; 1284 mOnlyCore = onlyCore; 1285 mMetrics = new DisplayMetrics(); 1286 mSettings = new Settings(context); 1287 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1288 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1289 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1290 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1291 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1292 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1293 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1294 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1295 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1296 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1297 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1298 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1299 1300 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1301 if (separateProcesses != null && separateProcesses.length() > 0) { 1302 if ("*".equals(separateProcesses)) { 1303 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1304 mSeparateProcesses = null; 1305 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1306 } else { 1307 mDefParseFlags = 0; 1308 mSeparateProcesses = separateProcesses.split(","); 1309 Slog.w(TAG, "Running with debug.separate_processes: " 1310 + separateProcesses); 1311 } 1312 } else { 1313 mDefParseFlags = 0; 1314 mSeparateProcesses = null; 1315 } 1316 1317 mInstaller = installer; 1318 1319 getDefaultDisplayMetrics(context, mMetrics); 1320 1321 SystemConfig systemConfig = SystemConfig.getInstance(); 1322 mGlobalGids = systemConfig.getGlobalGids(); 1323 mSystemPermissions = systemConfig.getSystemPermissions(); 1324 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1325 1326 synchronized (mInstallLock) { 1327 // writer 1328 synchronized (mPackages) { 1329 mHandlerThread = new ServiceThread(TAG, 1330 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1331 mHandlerThread.start(); 1332 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1333 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1334 1335 File dataDir = Environment.getDataDirectory(); 1336 mAppDataDir = new File(dataDir, "data"); 1337 mAppInstallDir = new File(dataDir, "app"); 1338 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1339 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1340 mUserAppDataDir = new File(dataDir, "user"); 1341 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1342 1343 sUserManager = new UserManagerService(context, this, 1344 mInstallLock, mPackages); 1345 1346 // Propagate permission configuration in to package manager. 1347 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1348 = systemConfig.getPermissions(); 1349 for (int i=0; i<permConfig.size(); i++) { 1350 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1351 BasePermission bp = mSettings.mPermissions.get(perm.name); 1352 if (bp == null) { 1353 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1354 mSettings.mPermissions.put(perm.name, bp); 1355 } 1356 if (perm.gids != null) { 1357 bp.gids = appendInts(bp.gids, perm.gids); 1358 } 1359 } 1360 1361 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1362 for (int i=0; i<libConfig.size(); i++) { 1363 mSharedLibraries.put(libConfig.keyAt(i), 1364 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1365 } 1366 1367 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1368 1369 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1370 mSdkVersion, mOnlyCore); 1371 1372 String customResolverActivity = Resources.getSystem().getString( 1373 R.string.config_customResolverActivity); 1374 if (TextUtils.isEmpty(customResolverActivity)) { 1375 customResolverActivity = null; 1376 } else { 1377 mCustomResolverComponentName = ComponentName.unflattenFromString( 1378 customResolverActivity); 1379 } 1380 1381 long startTime = SystemClock.uptimeMillis(); 1382 1383 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1384 startTime); 1385 1386 // Set flag to monitor and not change apk file paths when 1387 // scanning install directories. 1388 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1389 1390 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1391 1392 /** 1393 * Add everything in the in the boot class path to the 1394 * list of process files because dexopt will have been run 1395 * if necessary during zygote startup. 1396 */ 1397 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1398 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1399 1400 if (bootClassPath != null) { 1401 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1402 for (String element : bootClassPathElements) { 1403 alreadyDexOpted.add(element); 1404 } 1405 } else { 1406 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1407 } 1408 1409 if (systemServerClassPath != null) { 1410 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1411 for (String element : systemServerClassPathElements) { 1412 alreadyDexOpted.add(element); 1413 } 1414 } else { 1415 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1416 } 1417 1418 boolean didDexOptLibraryOrTool = false; 1419 1420 final List<String> allInstructionSets = getAllInstructionSets(); 1421 final String[] dexCodeInstructionSets = 1422 getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()])); 1423 1424 /** 1425 * Ensure all external libraries have had dexopt run on them. 1426 */ 1427 if (mSharedLibraries.size() > 0) { 1428 // NOTE: For now, we're compiling these system "shared libraries" 1429 // (and framework jars) into all available architectures. It's possible 1430 // to compile them only when we come across an app that uses them (there's 1431 // already logic for that in scanPackageLI) but that adds some complexity. 1432 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1433 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1434 final String lib = libEntry.path; 1435 if (lib == null) { 1436 continue; 1437 } 1438 1439 try { 1440 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1441 dexCodeInstructionSet, 1442 false); 1443 if (dexoptRequired != DexFile.UP_TO_DATE) { 1444 alreadyDexOpted.add(lib); 1445 1446 // The list of "shared libraries" we have at this point is 1447 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1448 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1449 } else { 1450 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1451 } 1452 didDexOptLibraryOrTool = true; 1453 } 1454 } catch (FileNotFoundException e) { 1455 Slog.w(TAG, "Library not found: " + lib); 1456 } catch (IOException e) { 1457 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1458 + e.getMessage()); 1459 } 1460 } 1461 } 1462 } 1463 1464 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1465 1466 // Gross hack for now: we know this file doesn't contain any 1467 // code, so don't dexopt it to avoid the resulting log spew. 1468 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1469 1470 // Gross hack for now: we know this file is only part of 1471 // the boot class path for art, so don't dexopt it to 1472 // avoid the resulting log spew. 1473 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1474 1475 /** 1476 * And there are a number of commands implemented in Java, which 1477 * we currently need to do the dexopt on so that they can be 1478 * run from a non-root shell. 1479 */ 1480 String[] frameworkFiles = frameworkDir.list(); 1481 if (frameworkFiles != null) { 1482 // TODO: We could compile these only for the most preferred ABI. We should 1483 // first double check that the dex files for these commands are not referenced 1484 // by other system apps. 1485 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1486 for (int i=0; i<frameworkFiles.length; i++) { 1487 File libPath = new File(frameworkDir, frameworkFiles[i]); 1488 String path = libPath.getPath(); 1489 // Skip the file if we already did it. 1490 if (alreadyDexOpted.contains(path)) { 1491 continue; 1492 } 1493 // Skip the file if it is not a type we want to dexopt. 1494 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1495 continue; 1496 } 1497 try { 1498 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1499 dexCodeInstructionSet, 1500 false); 1501 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1502 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1503 didDexOptLibraryOrTool = true; 1504 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1505 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1506 didDexOptLibraryOrTool = true; 1507 } 1508 } catch (FileNotFoundException e) { 1509 Slog.w(TAG, "Jar not found: " + path); 1510 } catch (IOException e) { 1511 Slog.w(TAG, "Exception reading jar: " + path, e); 1512 } 1513 } 1514 } 1515 } 1516 1517 if (didDexOptLibraryOrTool) { 1518 // If we dexopted a library or tool, then something on the system has 1519 // changed. Consider this significant, and wipe away all other 1520 // existing dexopt files to ensure we don't leave any dangling around. 1521 // 1522 // TODO: This should be revisited because it isn't as good an indicator 1523 // as it used to be. It used to include the boot classpath but at some point 1524 // DexFile.isDexOptNeeded started returning false for the boot 1525 // class path files in all cases. It is very possible in a 1526 // small maintenance release update that the library and tool 1527 // jars may be unchanged but APK could be removed resulting in 1528 // unused dalvik-cache files. 1529 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1530 mInstaller.pruneDexCache(dexCodeInstructionSet); 1531 } 1532 1533 // Additionally, delete all dex files from the root directory 1534 // since there shouldn't be any there anyway, unless we're upgrading 1535 // from an older OS version or a build that contained the "old" style 1536 // flat scheme. 1537 mInstaller.pruneDexCache("."); 1538 } 1539 1540 // Collect vendor overlay packages. 1541 // (Do this before scanning any apps.) 1542 // For security and version matching reason, only consider 1543 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1544 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1545 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1546 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1547 1548 // Find base frameworks (resource packages without code). 1549 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1550 | PackageParser.PARSE_IS_SYSTEM_DIR 1551 | PackageParser.PARSE_IS_PRIVILEGED, 1552 scanMode | SCAN_NO_DEX, 0); 1553 1554 // Collected privileged system packages. 1555 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1556 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1557 | PackageParser.PARSE_IS_SYSTEM_DIR 1558 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1559 1560 // Collect ordinary system packages. 1561 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1562 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1563 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1564 1565 // Collect all vendor packages. 1566 File vendorAppDir = new File("/vendor/app"); 1567 try { 1568 vendorAppDir = vendorAppDir.getCanonicalFile(); 1569 } catch (IOException e) { 1570 // failed to look up canonical path, continue with original one 1571 } 1572 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1573 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1574 1575 // Collect all OEM packages. 1576 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1577 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1578 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1579 1580 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1581 mInstaller.moveFiles(); 1582 1583 // Prune any system packages that no longer exist. 1584 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1585 if (!mOnlyCore) { 1586 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1587 while (psit.hasNext()) { 1588 PackageSetting ps = psit.next(); 1589 1590 /* 1591 * If this is not a system app, it can't be a 1592 * disable system app. 1593 */ 1594 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1595 continue; 1596 } 1597 1598 /* 1599 * If the package is scanned, it's not erased. 1600 */ 1601 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1602 if (scannedPkg != null) { 1603 /* 1604 * If the system app is both scanned and in the 1605 * disabled packages list, then it must have been 1606 * added via OTA. Remove it from the currently 1607 * scanned package so the previously user-installed 1608 * application can be scanned. 1609 */ 1610 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1611 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1612 + "; removing system app"); 1613 removePackageLI(ps, true); 1614 } 1615 1616 continue; 1617 } 1618 1619 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1620 psit.remove(); 1621 String msg = "System package " + ps.name 1622 + " no longer exists; wiping its data"; 1623 reportSettingsProblem(Log.WARN, msg); 1624 removeDataDirsLI(ps.name); 1625 } else { 1626 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1627 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1628 possiblyDeletedUpdatedSystemApps.add(ps.name); 1629 } 1630 } 1631 } 1632 } 1633 1634 //look for any incomplete package installations 1635 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1636 //clean up list 1637 for(int i = 0; i < deletePkgsList.size(); i++) { 1638 //clean up here 1639 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1640 } 1641 //delete tmp files 1642 deleteTempPackageFiles(); 1643 1644 // Remove any shared userIDs that have no associated packages 1645 mSettings.pruneSharedUsersLPw(); 1646 1647 if (!mOnlyCore) { 1648 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1649 SystemClock.uptimeMillis()); 1650 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1651 1652 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1653 scanMode, 0); 1654 1655 /** 1656 * Remove disable package settings for any updated system 1657 * apps that were removed via an OTA. If they're not a 1658 * previously-updated app, remove them completely. 1659 * Otherwise, just revoke their system-level permissions. 1660 */ 1661 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1662 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1663 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1664 1665 String msg; 1666 if (deletedPkg == null) { 1667 msg = "Updated system package " + deletedAppName 1668 + " no longer exists; wiping its data"; 1669 removeDataDirsLI(deletedAppName); 1670 } else { 1671 msg = "Updated system app + " + deletedAppName 1672 + " no longer present; removing system privileges for " 1673 + deletedAppName; 1674 1675 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1676 1677 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1678 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1679 } 1680 reportSettingsProblem(Log.WARN, msg); 1681 } 1682 } 1683 1684 // Now that we know all of the shared libraries, update all clients to have 1685 // the correct library paths. 1686 updateAllSharedLibrariesLPw(); 1687 1688 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1689 // NOTE: We ignore potential failures here during a system scan (like 1690 // the rest of the commands above) because there's precious little we 1691 // can do about it. A settings error is reported, though. 1692 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1693 false /* force dexopt */, false /* defer dexopt */); 1694 } 1695 1696 // Now that we know all the packages we are keeping, 1697 // read and update their last usage times. 1698 mPackageUsage.readLP(); 1699 1700 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1701 SystemClock.uptimeMillis()); 1702 Slog.i(TAG, "Time to scan packages: " 1703 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1704 + " seconds"); 1705 1706 // If the platform SDK has changed since the last time we booted, 1707 // we need to re-grant app permission to catch any new ones that 1708 // appear. This is really a hack, and means that apps can in some 1709 // cases get permissions that the user didn't initially explicitly 1710 // allow... it would be nice to have some better way to handle 1711 // this situation. 1712 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1713 != mSdkVersion; 1714 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1715 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1716 + "; regranting permissions for internal storage"); 1717 mSettings.mInternalSdkPlatform = mSdkVersion; 1718 1719 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1720 | (regrantPermissions 1721 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1722 : 0)); 1723 1724 // If this is the first boot, and it is a normal boot, then 1725 // we need to initialize the default preferred apps. 1726 if (!mRestoredSettings && !onlyCore) { 1727 mSettings.readDefaultPreferredAppsLPw(this, 0); 1728 } 1729 1730 // If this is first boot after an OTA, and a normal boot, then 1731 // we need to clear code cache directories. 1732 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1733 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1734 for (String pkgName : mSettings.mPackages.keySet()) { 1735 deleteCodeCacheDirsLI(pkgName); 1736 } 1737 mSettings.mFingerprint = Build.FINGERPRINT; 1738 } 1739 1740 // All the changes are done during package scanning. 1741 mSettings.updateInternalDatabaseVersion(); 1742 1743 // can downgrade to reader 1744 mSettings.writeLPr(); 1745 1746 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1747 SystemClock.uptimeMillis()); 1748 1749 1750 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1751 } // synchronized (mPackages) 1752 } // synchronized (mInstallLock) 1753 1754 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1755 1756 // Now after opening every single application zip, make sure they 1757 // are all flushed. Not really needed, but keeps things nice and 1758 // tidy. 1759 Runtime.getRuntime().gc(); 1760 } 1761 1762 @Override 1763 public boolean isFirstBoot() { 1764 return !mRestoredSettings; 1765 } 1766 1767 @Override 1768 public boolean isOnlyCoreApps() { 1769 return mOnlyCore; 1770 } 1771 1772 private String getRequiredVerifierLPr() { 1773 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1774 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1775 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1776 1777 String requiredVerifier = null; 1778 1779 final int N = receivers.size(); 1780 for (int i = 0; i < N; i++) { 1781 final ResolveInfo info = receivers.get(i); 1782 1783 if (info.activityInfo == null) { 1784 continue; 1785 } 1786 1787 final String packageName = info.activityInfo.packageName; 1788 1789 final PackageSetting ps = mSettings.mPackages.get(packageName); 1790 if (ps == null) { 1791 continue; 1792 } 1793 1794 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1795 if (!gp.grantedPermissions 1796 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1797 continue; 1798 } 1799 1800 if (requiredVerifier != null) { 1801 throw new RuntimeException("There can be only one required verifier"); 1802 } 1803 1804 requiredVerifier = packageName; 1805 } 1806 1807 return requiredVerifier; 1808 } 1809 1810 @Override 1811 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1812 throws RemoteException { 1813 try { 1814 return super.onTransact(code, data, reply, flags); 1815 } catch (RuntimeException e) { 1816 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1817 Slog.wtf(TAG, "Package Manager Crash", e); 1818 } 1819 throw e; 1820 } 1821 } 1822 1823 void cleanupInstallFailedPackage(PackageSetting ps) { 1824 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1825 removeDataDirsLI(ps.name); 1826 1827 // TODO: try cleaning up codePath directory contents first, since it 1828 // might be a cluster 1829 1830 if (ps.codePath != null) { 1831 if (!ps.codePath.delete()) { 1832 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1833 } 1834 } 1835 if (ps.resourcePath != null) { 1836 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1837 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1838 } 1839 } 1840 mSettings.removePackageLPw(ps.name); 1841 } 1842 1843 static int[] appendInts(int[] cur, int[] add) { 1844 if (add == null) return cur; 1845 if (cur == null) return add; 1846 final int N = add.length; 1847 for (int i=0; i<N; i++) { 1848 cur = appendInt(cur, add[i]); 1849 } 1850 return cur; 1851 } 1852 1853 static int[] removeInts(int[] cur, int[] rem) { 1854 if (rem == null) return cur; 1855 if (cur == null) return cur; 1856 final int N = rem.length; 1857 for (int i=0; i<N; i++) { 1858 cur = removeInt(cur, rem[i]); 1859 } 1860 return cur; 1861 } 1862 1863 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1864 if (!sUserManager.exists(userId)) return null; 1865 final PackageSetting ps = (PackageSetting) p.mExtras; 1866 if (ps == null) { 1867 return null; 1868 } 1869 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1870 final PackageUserState state = ps.readUserState(userId); 1871 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1872 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1873 state, userId); 1874 } 1875 1876 @Override 1877 public boolean isPackageAvailable(String packageName, int userId) { 1878 if (!sUserManager.exists(userId)) return false; 1879 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1880 synchronized (mPackages) { 1881 PackageParser.Package p = mPackages.get(packageName); 1882 if (p != null) { 1883 final PackageSetting ps = (PackageSetting) p.mExtras; 1884 if (ps != null) { 1885 final PackageUserState state = ps.readUserState(userId); 1886 if (state != null) { 1887 return PackageParser.isAvailable(state); 1888 } 1889 } 1890 } 1891 } 1892 return false; 1893 } 1894 1895 @Override 1896 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1897 if (!sUserManager.exists(userId)) return null; 1898 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1899 // reader 1900 synchronized (mPackages) { 1901 PackageParser.Package p = mPackages.get(packageName); 1902 if (DEBUG_PACKAGE_INFO) 1903 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1904 if (p != null) { 1905 return generatePackageInfo(p, flags, userId); 1906 } 1907 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1908 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1909 } 1910 } 1911 return null; 1912 } 1913 1914 @Override 1915 public String[] currentToCanonicalPackageNames(String[] names) { 1916 String[] out = new String[names.length]; 1917 // reader 1918 synchronized (mPackages) { 1919 for (int i=names.length-1; i>=0; i--) { 1920 PackageSetting ps = mSettings.mPackages.get(names[i]); 1921 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1922 } 1923 } 1924 return out; 1925 } 1926 1927 @Override 1928 public String[] canonicalToCurrentPackageNames(String[] names) { 1929 String[] out = new String[names.length]; 1930 // reader 1931 synchronized (mPackages) { 1932 for (int i=names.length-1; i>=0; i--) { 1933 String cur = mSettings.mRenamedPackages.get(names[i]); 1934 out[i] = cur != null ? cur : names[i]; 1935 } 1936 } 1937 return out; 1938 } 1939 1940 @Override 1941 public int getPackageUid(String packageName, int userId) { 1942 if (!sUserManager.exists(userId)) return -1; 1943 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1944 // reader 1945 synchronized (mPackages) { 1946 PackageParser.Package p = mPackages.get(packageName); 1947 if(p != null) { 1948 return UserHandle.getUid(userId, p.applicationInfo.uid); 1949 } 1950 PackageSetting ps = mSettings.mPackages.get(packageName); 1951 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1952 return -1; 1953 } 1954 p = ps.pkg; 1955 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1956 } 1957 } 1958 1959 @Override 1960 public int[] getPackageGids(String packageName) { 1961 // reader 1962 synchronized (mPackages) { 1963 PackageParser.Package p = mPackages.get(packageName); 1964 if (DEBUG_PACKAGE_INFO) 1965 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1966 if (p != null) { 1967 final PackageSetting ps = (PackageSetting)p.mExtras; 1968 return ps.getGids(); 1969 } 1970 } 1971 // stupid thing to indicate an error. 1972 return new int[0]; 1973 } 1974 1975 static final PermissionInfo generatePermissionInfo( 1976 BasePermission bp, int flags) { 1977 if (bp.perm != null) { 1978 return PackageParser.generatePermissionInfo(bp.perm, flags); 1979 } 1980 PermissionInfo pi = new PermissionInfo(); 1981 pi.name = bp.name; 1982 pi.packageName = bp.sourcePackage; 1983 pi.nonLocalizedLabel = bp.name; 1984 pi.protectionLevel = bp.protectionLevel; 1985 return pi; 1986 } 1987 1988 @Override 1989 public PermissionInfo getPermissionInfo(String name, int flags) { 1990 // reader 1991 synchronized (mPackages) { 1992 final BasePermission p = mSettings.mPermissions.get(name); 1993 if (p != null) { 1994 return generatePermissionInfo(p, flags); 1995 } 1996 return null; 1997 } 1998 } 1999 2000 @Override 2001 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2002 // reader 2003 synchronized (mPackages) { 2004 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2005 for (BasePermission p : mSettings.mPermissions.values()) { 2006 if (group == null) { 2007 if (p.perm == null || p.perm.info.group == null) { 2008 out.add(generatePermissionInfo(p, flags)); 2009 } 2010 } else { 2011 if (p.perm != null && group.equals(p.perm.info.group)) { 2012 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2013 } 2014 } 2015 } 2016 2017 if (out.size() > 0) { 2018 return out; 2019 } 2020 return mPermissionGroups.containsKey(group) ? out : null; 2021 } 2022 } 2023 2024 @Override 2025 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2026 // reader 2027 synchronized (mPackages) { 2028 return PackageParser.generatePermissionGroupInfo( 2029 mPermissionGroups.get(name), flags); 2030 } 2031 } 2032 2033 @Override 2034 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2035 // reader 2036 synchronized (mPackages) { 2037 final int N = mPermissionGroups.size(); 2038 ArrayList<PermissionGroupInfo> out 2039 = new ArrayList<PermissionGroupInfo>(N); 2040 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2041 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2042 } 2043 return out; 2044 } 2045 } 2046 2047 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2048 int userId) { 2049 if (!sUserManager.exists(userId)) return null; 2050 PackageSetting ps = mSettings.mPackages.get(packageName); 2051 if (ps != null) { 2052 if (ps.pkg == null) { 2053 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2054 flags, userId); 2055 if (pInfo != null) { 2056 return pInfo.applicationInfo; 2057 } 2058 return null; 2059 } 2060 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2061 ps.readUserState(userId), userId); 2062 } 2063 return null; 2064 } 2065 2066 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2067 int userId) { 2068 if (!sUserManager.exists(userId)) return null; 2069 PackageSetting ps = mSettings.mPackages.get(packageName); 2070 if (ps != null) { 2071 PackageParser.Package pkg = ps.pkg; 2072 if (pkg == null) { 2073 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2074 return null; 2075 } 2076 // Only data remains, so we aren't worried about code paths 2077 pkg = new PackageParser.Package(packageName); 2078 pkg.applicationInfo.packageName = packageName; 2079 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2080 pkg.applicationInfo.dataDir = 2081 getDataPathForPackage(packageName, 0).getPath(); 2082 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2083 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2084 } 2085 return generatePackageInfo(pkg, flags, userId); 2086 } 2087 return null; 2088 } 2089 2090 @Override 2091 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2092 if (!sUserManager.exists(userId)) return null; 2093 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2094 // writer 2095 synchronized (mPackages) { 2096 PackageParser.Package p = mPackages.get(packageName); 2097 if (DEBUG_PACKAGE_INFO) Log.v( 2098 TAG, "getApplicationInfo " + packageName 2099 + ": " + p); 2100 if (p != null) { 2101 PackageSetting ps = mSettings.mPackages.get(packageName); 2102 if (ps == null) return null; 2103 // Note: isEnabledLP() does not apply here - always return info 2104 return PackageParser.generateApplicationInfo( 2105 p, flags, ps.readUserState(userId), userId); 2106 } 2107 if ("android".equals(packageName)||"system".equals(packageName)) { 2108 return mAndroidApplication; 2109 } 2110 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2111 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2112 } 2113 } 2114 return null; 2115 } 2116 2117 2118 @Override 2119 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2120 mContext.enforceCallingOrSelfPermission( 2121 android.Manifest.permission.CLEAR_APP_CACHE, null); 2122 // Queue up an async operation since clearing cache may take a little while. 2123 mHandler.post(new Runnable() { 2124 public void run() { 2125 mHandler.removeCallbacks(this); 2126 int retCode = -1; 2127 synchronized (mInstallLock) { 2128 retCode = mInstaller.freeCache(freeStorageSize); 2129 if (retCode < 0) { 2130 Slog.w(TAG, "Couldn't clear application caches"); 2131 } 2132 } 2133 if (observer != null) { 2134 try { 2135 observer.onRemoveCompleted(null, (retCode >= 0)); 2136 } catch (RemoteException e) { 2137 Slog.w(TAG, "RemoveException when invoking call back"); 2138 } 2139 } 2140 } 2141 }); 2142 } 2143 2144 @Override 2145 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2146 mContext.enforceCallingOrSelfPermission( 2147 android.Manifest.permission.CLEAR_APP_CACHE, null); 2148 // Queue up an async operation since clearing cache may take a little while. 2149 mHandler.post(new Runnable() { 2150 public void run() { 2151 mHandler.removeCallbacks(this); 2152 int retCode = -1; 2153 synchronized (mInstallLock) { 2154 retCode = mInstaller.freeCache(freeStorageSize); 2155 if (retCode < 0) { 2156 Slog.w(TAG, "Couldn't clear application caches"); 2157 } 2158 } 2159 if(pi != null) { 2160 try { 2161 // Callback via pending intent 2162 int code = (retCode >= 0) ? 1 : 0; 2163 pi.sendIntent(null, code, null, 2164 null, null); 2165 } catch (SendIntentException e1) { 2166 Slog.i(TAG, "Failed to send pending intent"); 2167 } 2168 } 2169 } 2170 }); 2171 } 2172 2173 void freeStorage(long freeStorageSize) throws IOException { 2174 synchronized (mInstallLock) { 2175 if (mInstaller.freeCache(freeStorageSize) < 0) { 2176 throw new IOException("Failed to free enough space"); 2177 } 2178 } 2179 } 2180 2181 @Override 2182 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2183 if (!sUserManager.exists(userId)) return null; 2184 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2185 synchronized (mPackages) { 2186 PackageParser.Activity a = mActivities.mActivities.get(component); 2187 2188 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2189 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2190 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2191 if (ps == null) return null; 2192 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2193 userId); 2194 } 2195 if (mResolveComponentName.equals(component)) { 2196 return mResolveActivity; 2197 } 2198 } 2199 return null; 2200 } 2201 2202 @Override 2203 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2204 String resolvedType) { 2205 synchronized (mPackages) { 2206 PackageParser.Activity a = mActivities.mActivities.get(component); 2207 if (a == null) { 2208 return false; 2209 } 2210 for (int i=0; i<a.intents.size(); i++) { 2211 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2212 intent.getData(), intent.getCategories(), TAG) >= 0) { 2213 return true; 2214 } 2215 } 2216 return false; 2217 } 2218 } 2219 2220 @Override 2221 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2222 if (!sUserManager.exists(userId)) return null; 2223 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2224 synchronized (mPackages) { 2225 PackageParser.Activity a = mReceivers.mActivities.get(component); 2226 if (DEBUG_PACKAGE_INFO) Log.v( 2227 TAG, "getReceiverInfo " + component + ": " + a); 2228 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2229 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2230 if (ps == null) return null; 2231 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2232 userId); 2233 } 2234 } 2235 return null; 2236 } 2237 2238 @Override 2239 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2240 if (!sUserManager.exists(userId)) return null; 2241 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2242 synchronized (mPackages) { 2243 PackageParser.Service s = mServices.mServices.get(component); 2244 if (DEBUG_PACKAGE_INFO) Log.v( 2245 TAG, "getServiceInfo " + component + ": " + s); 2246 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2247 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2248 if (ps == null) return null; 2249 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2250 userId); 2251 } 2252 } 2253 return null; 2254 } 2255 2256 @Override 2257 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2258 if (!sUserManager.exists(userId)) return null; 2259 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2260 synchronized (mPackages) { 2261 PackageParser.Provider p = mProviders.mProviders.get(component); 2262 if (DEBUG_PACKAGE_INFO) Log.v( 2263 TAG, "getProviderInfo " + component + ": " + p); 2264 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2265 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2266 if (ps == null) return null; 2267 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2268 userId); 2269 } 2270 } 2271 return null; 2272 } 2273 2274 @Override 2275 public String[] getSystemSharedLibraryNames() { 2276 Set<String> libSet; 2277 synchronized (mPackages) { 2278 libSet = mSharedLibraries.keySet(); 2279 int size = libSet.size(); 2280 if (size > 0) { 2281 String[] libs = new String[size]; 2282 libSet.toArray(libs); 2283 return libs; 2284 } 2285 } 2286 return null; 2287 } 2288 2289 @Override 2290 public FeatureInfo[] getSystemAvailableFeatures() { 2291 Collection<FeatureInfo> featSet; 2292 synchronized (mPackages) { 2293 featSet = mAvailableFeatures.values(); 2294 int size = featSet.size(); 2295 if (size > 0) { 2296 FeatureInfo[] features = new FeatureInfo[size+1]; 2297 featSet.toArray(features); 2298 FeatureInfo fi = new FeatureInfo(); 2299 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2300 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2301 features[size] = fi; 2302 return features; 2303 } 2304 } 2305 return null; 2306 } 2307 2308 @Override 2309 public boolean hasSystemFeature(String name) { 2310 synchronized (mPackages) { 2311 return mAvailableFeatures.containsKey(name); 2312 } 2313 } 2314 2315 private void checkValidCaller(int uid, int userId) { 2316 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2317 return; 2318 2319 throw new SecurityException("Caller uid=" + uid 2320 + " is not privileged to communicate with user=" + userId); 2321 } 2322 2323 @Override 2324 public int checkPermission(String permName, String pkgName) { 2325 synchronized (mPackages) { 2326 PackageParser.Package p = mPackages.get(pkgName); 2327 if (p != null && p.mExtras != null) { 2328 PackageSetting ps = (PackageSetting)p.mExtras; 2329 if (ps.sharedUser != null) { 2330 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2331 return PackageManager.PERMISSION_GRANTED; 2332 } 2333 } else if (ps.grantedPermissions.contains(permName)) { 2334 return PackageManager.PERMISSION_GRANTED; 2335 } 2336 } 2337 } 2338 return PackageManager.PERMISSION_DENIED; 2339 } 2340 2341 @Override 2342 public int checkUidPermission(String permName, int uid) { 2343 synchronized (mPackages) { 2344 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2345 if (obj != null) { 2346 GrantedPermissions gp = (GrantedPermissions)obj; 2347 if (gp.grantedPermissions.contains(permName)) { 2348 return PackageManager.PERMISSION_GRANTED; 2349 } 2350 } else { 2351 HashSet<String> perms = mSystemPermissions.get(uid); 2352 if (perms != null && perms.contains(permName)) { 2353 return PackageManager.PERMISSION_GRANTED; 2354 } 2355 } 2356 } 2357 return PackageManager.PERMISSION_DENIED; 2358 } 2359 2360 /** 2361 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2362 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2363 * @param message the message to log on security exception 2364 */ 2365 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2366 String message) { 2367 if (userId < 0) { 2368 throw new IllegalArgumentException("Invalid userId " + userId); 2369 } 2370 if (userId == UserHandle.getUserId(callingUid)) return; 2371 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2372 if (requireFullPermission) { 2373 mContext.enforceCallingOrSelfPermission( 2374 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2375 } else { 2376 try { 2377 mContext.enforceCallingOrSelfPermission( 2378 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2379 } catch (SecurityException se) { 2380 mContext.enforceCallingOrSelfPermission( 2381 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2382 } 2383 } 2384 } 2385 } 2386 2387 private BasePermission findPermissionTreeLP(String permName) { 2388 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2389 if (permName.startsWith(bp.name) && 2390 permName.length() > bp.name.length() && 2391 permName.charAt(bp.name.length()) == '.') { 2392 return bp; 2393 } 2394 } 2395 return null; 2396 } 2397 2398 private BasePermission checkPermissionTreeLP(String permName) { 2399 if (permName != null) { 2400 BasePermission bp = findPermissionTreeLP(permName); 2401 if (bp != null) { 2402 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2403 return bp; 2404 } 2405 throw new SecurityException("Calling uid " 2406 + Binder.getCallingUid() 2407 + " is not allowed to add to permission tree " 2408 + bp.name + " owned by uid " + bp.uid); 2409 } 2410 } 2411 throw new SecurityException("No permission tree found for " + permName); 2412 } 2413 2414 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2415 if (s1 == null) { 2416 return s2 == null; 2417 } 2418 if (s2 == null) { 2419 return false; 2420 } 2421 if (s1.getClass() != s2.getClass()) { 2422 return false; 2423 } 2424 return s1.equals(s2); 2425 } 2426 2427 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2428 if (pi1.icon != pi2.icon) return false; 2429 if (pi1.logo != pi2.logo) return false; 2430 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2431 if (!compareStrings(pi1.name, pi2.name)) return false; 2432 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2433 // We'll take care of setting this one. 2434 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2435 // These are not currently stored in settings. 2436 //if (!compareStrings(pi1.group, pi2.group)) return false; 2437 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2438 //if (pi1.labelRes != pi2.labelRes) return false; 2439 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2440 return true; 2441 } 2442 2443 int permissionInfoFootprint(PermissionInfo info) { 2444 int size = info.name.length(); 2445 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2446 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2447 return size; 2448 } 2449 2450 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2451 int size = 0; 2452 for (BasePermission perm : mSettings.mPermissions.values()) { 2453 if (perm.uid == tree.uid) { 2454 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2455 } 2456 } 2457 return size; 2458 } 2459 2460 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2461 // We calculate the max size of permissions defined by this uid and throw 2462 // if that plus the size of 'info' would exceed our stated maximum. 2463 if (tree.uid != Process.SYSTEM_UID) { 2464 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2465 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2466 throw new SecurityException("Permission tree size cap exceeded"); 2467 } 2468 } 2469 } 2470 2471 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2472 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2473 throw new SecurityException("Label must be specified in permission"); 2474 } 2475 BasePermission tree = checkPermissionTreeLP(info.name); 2476 BasePermission bp = mSettings.mPermissions.get(info.name); 2477 boolean added = bp == null; 2478 boolean changed = true; 2479 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2480 if (added) { 2481 enforcePermissionCapLocked(info, tree); 2482 bp = new BasePermission(info.name, tree.sourcePackage, 2483 BasePermission.TYPE_DYNAMIC); 2484 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2485 throw new SecurityException( 2486 "Not allowed to modify non-dynamic permission " 2487 + info.name); 2488 } else { 2489 if (bp.protectionLevel == fixedLevel 2490 && bp.perm.owner.equals(tree.perm.owner) 2491 && bp.uid == tree.uid 2492 && comparePermissionInfos(bp.perm.info, info)) { 2493 changed = false; 2494 } 2495 } 2496 bp.protectionLevel = fixedLevel; 2497 info = new PermissionInfo(info); 2498 info.protectionLevel = fixedLevel; 2499 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2500 bp.perm.info.packageName = tree.perm.info.packageName; 2501 bp.uid = tree.uid; 2502 if (added) { 2503 mSettings.mPermissions.put(info.name, bp); 2504 } 2505 if (changed) { 2506 if (!async) { 2507 mSettings.writeLPr(); 2508 } else { 2509 scheduleWriteSettingsLocked(); 2510 } 2511 } 2512 return added; 2513 } 2514 2515 @Override 2516 public boolean addPermission(PermissionInfo info) { 2517 synchronized (mPackages) { 2518 return addPermissionLocked(info, false); 2519 } 2520 } 2521 2522 @Override 2523 public boolean addPermissionAsync(PermissionInfo info) { 2524 synchronized (mPackages) { 2525 return addPermissionLocked(info, true); 2526 } 2527 } 2528 2529 @Override 2530 public void removePermission(String name) { 2531 synchronized (mPackages) { 2532 checkPermissionTreeLP(name); 2533 BasePermission bp = mSettings.mPermissions.get(name); 2534 if (bp != null) { 2535 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2536 throw new SecurityException( 2537 "Not allowed to modify non-dynamic permission " 2538 + name); 2539 } 2540 mSettings.mPermissions.remove(name); 2541 mSettings.writeLPr(); 2542 } 2543 } 2544 } 2545 2546 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2547 int index = pkg.requestedPermissions.indexOf(bp.name); 2548 if (index == -1) { 2549 throw new SecurityException("Package " + pkg.packageName 2550 + " has not requested permission " + bp.name); 2551 } 2552 boolean isNormal = 2553 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2554 == PermissionInfo.PROTECTION_NORMAL); 2555 boolean isDangerous = 2556 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2557 == PermissionInfo.PROTECTION_DANGEROUS); 2558 boolean isDevelopment = 2559 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2560 2561 if (!isNormal && !isDangerous && !isDevelopment) { 2562 throw new SecurityException("Permission " + bp.name 2563 + " is not a changeable permission type"); 2564 } 2565 2566 if (isNormal || isDangerous) { 2567 if (pkg.requestedPermissionsRequired.get(index)) { 2568 throw new SecurityException("Can't change " + bp.name 2569 + ". It is required by the application"); 2570 } 2571 } 2572 } 2573 2574 @Override 2575 public void grantPermission(String packageName, String permissionName) { 2576 mContext.enforceCallingOrSelfPermission( 2577 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2578 synchronized (mPackages) { 2579 final PackageParser.Package pkg = mPackages.get(packageName); 2580 if (pkg == null) { 2581 throw new IllegalArgumentException("Unknown package: " + packageName); 2582 } 2583 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2584 if (bp == null) { 2585 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2586 } 2587 2588 checkGrantRevokePermissions(pkg, bp); 2589 2590 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2591 if (ps == null) { 2592 return; 2593 } 2594 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2595 if (gp.grantedPermissions.add(permissionName)) { 2596 if (ps.haveGids) { 2597 gp.gids = appendInts(gp.gids, bp.gids); 2598 } 2599 mSettings.writeLPr(); 2600 } 2601 } 2602 } 2603 2604 @Override 2605 public void revokePermission(String packageName, String permissionName) { 2606 int changedAppId = -1; 2607 2608 synchronized (mPackages) { 2609 final PackageParser.Package pkg = mPackages.get(packageName); 2610 if (pkg == null) { 2611 throw new IllegalArgumentException("Unknown package: " + packageName); 2612 } 2613 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2614 mContext.enforceCallingOrSelfPermission( 2615 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2616 } 2617 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2618 if (bp == null) { 2619 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2620 } 2621 2622 checkGrantRevokePermissions(pkg, bp); 2623 2624 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2625 if (ps == null) { 2626 return; 2627 } 2628 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2629 if (gp.grantedPermissions.remove(permissionName)) { 2630 gp.grantedPermissions.remove(permissionName); 2631 if (ps.haveGids) { 2632 gp.gids = removeInts(gp.gids, bp.gids); 2633 } 2634 mSettings.writeLPr(); 2635 changedAppId = ps.appId; 2636 } 2637 } 2638 2639 if (changedAppId >= 0) { 2640 // We changed the perm on someone, kill its processes. 2641 IActivityManager am = ActivityManagerNative.getDefault(); 2642 if (am != null) { 2643 final int callingUserId = UserHandle.getCallingUserId(); 2644 final long ident = Binder.clearCallingIdentity(); 2645 try { 2646 //XXX we should only revoke for the calling user's app permissions, 2647 // but for now we impact all users. 2648 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2649 // "revoke " + permissionName); 2650 int[] users = sUserManager.getUserIds(); 2651 for (int user : users) { 2652 am.killUid(UserHandle.getUid(user, changedAppId), 2653 "revoke " + permissionName); 2654 } 2655 } catch (RemoteException e) { 2656 } finally { 2657 Binder.restoreCallingIdentity(ident); 2658 } 2659 } 2660 } 2661 } 2662 2663 @Override 2664 public boolean isProtectedBroadcast(String actionName) { 2665 synchronized (mPackages) { 2666 return mProtectedBroadcasts.contains(actionName); 2667 } 2668 } 2669 2670 @Override 2671 public int checkSignatures(String pkg1, String pkg2) { 2672 synchronized (mPackages) { 2673 final PackageParser.Package p1 = mPackages.get(pkg1); 2674 final PackageParser.Package p2 = mPackages.get(pkg2); 2675 if (p1 == null || p1.mExtras == null 2676 || p2 == null || p2.mExtras == null) { 2677 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2678 } 2679 return compareSignatures(p1.mSignatures, p2.mSignatures); 2680 } 2681 } 2682 2683 @Override 2684 public int checkUidSignatures(int uid1, int uid2) { 2685 // Map to base uids. 2686 uid1 = UserHandle.getAppId(uid1); 2687 uid2 = UserHandle.getAppId(uid2); 2688 // reader 2689 synchronized (mPackages) { 2690 Signature[] s1; 2691 Signature[] s2; 2692 Object obj = mSettings.getUserIdLPr(uid1); 2693 if (obj != null) { 2694 if (obj instanceof SharedUserSetting) { 2695 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2696 } else if (obj instanceof PackageSetting) { 2697 s1 = ((PackageSetting)obj).signatures.mSignatures; 2698 } else { 2699 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2700 } 2701 } else { 2702 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2703 } 2704 obj = mSettings.getUserIdLPr(uid2); 2705 if (obj != null) { 2706 if (obj instanceof SharedUserSetting) { 2707 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2708 } else if (obj instanceof PackageSetting) { 2709 s2 = ((PackageSetting)obj).signatures.mSignatures; 2710 } else { 2711 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2712 } 2713 } else { 2714 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2715 } 2716 return compareSignatures(s1, s2); 2717 } 2718 } 2719 2720 /** 2721 * Compares two sets of signatures. Returns: 2722 * <br /> 2723 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2724 * <br /> 2725 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2726 * <br /> 2727 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2728 * <br /> 2729 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2730 * <br /> 2731 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2732 */ 2733 static int compareSignatures(Signature[] s1, Signature[] s2) { 2734 if (s1 == null) { 2735 return s2 == null 2736 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2737 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2738 } 2739 2740 if (s2 == null) { 2741 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2742 } 2743 2744 if (s1.length != s2.length) { 2745 return PackageManager.SIGNATURE_NO_MATCH; 2746 } 2747 2748 // Since both signature sets are of size 1, we can compare without HashSets. 2749 if (s1.length == 1) { 2750 return s1[0].equals(s2[0]) ? 2751 PackageManager.SIGNATURE_MATCH : 2752 PackageManager.SIGNATURE_NO_MATCH; 2753 } 2754 2755 HashSet<Signature> set1 = new HashSet<Signature>(); 2756 for (Signature sig : s1) { 2757 set1.add(sig); 2758 } 2759 HashSet<Signature> set2 = new HashSet<Signature>(); 2760 for (Signature sig : s2) { 2761 set2.add(sig); 2762 } 2763 // Make sure s2 contains all signatures in s1. 2764 if (set1.equals(set2)) { 2765 return PackageManager.SIGNATURE_MATCH; 2766 } 2767 return PackageManager.SIGNATURE_NO_MATCH; 2768 } 2769 2770 /** 2771 * If the database version for this type of package (internal storage or 2772 * external storage) is less than the version where package signatures 2773 * were updated, return true. 2774 */ 2775 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2776 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2777 DatabaseVersion.SIGNATURE_END_ENTITY)) 2778 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2779 DatabaseVersion.SIGNATURE_END_ENTITY)); 2780 } 2781 2782 /** 2783 * Used for backward compatibility to make sure any packages with 2784 * certificate chains get upgraded to the new style. {@code existingSigs} 2785 * will be in the old format (since they were stored on disk from before the 2786 * system upgrade) and {@code scannedSigs} will be in the newer format. 2787 */ 2788 private int compareSignaturesCompat(PackageSignatures existingSigs, 2789 PackageParser.Package scannedPkg) { 2790 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2791 return PackageManager.SIGNATURE_NO_MATCH; 2792 } 2793 2794 HashSet<Signature> existingSet = new HashSet<Signature>(); 2795 for (Signature sig : existingSigs.mSignatures) { 2796 existingSet.add(sig); 2797 } 2798 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2799 for (Signature sig : scannedPkg.mSignatures) { 2800 try { 2801 Signature[] chainSignatures = sig.getChainSignatures(); 2802 for (Signature chainSig : chainSignatures) { 2803 scannedCompatSet.add(chainSig); 2804 } 2805 } catch (CertificateEncodingException e) { 2806 scannedCompatSet.add(sig); 2807 } 2808 } 2809 /* 2810 * Make sure the expanded scanned set contains all signatures in the 2811 * existing one. 2812 */ 2813 if (scannedCompatSet.equals(existingSet)) { 2814 // Migrate the old signatures to the new scheme. 2815 existingSigs.assignSignatures(scannedPkg.mSignatures); 2816 // The new KeySets will be re-added later in the scanning process. 2817 synchronized (mPackages) { 2818 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2819 } 2820 return PackageManager.SIGNATURE_MATCH; 2821 } 2822 return PackageManager.SIGNATURE_NO_MATCH; 2823 } 2824 2825 @Override 2826 public String[] getPackagesForUid(int uid) { 2827 uid = UserHandle.getAppId(uid); 2828 // reader 2829 synchronized (mPackages) { 2830 Object obj = mSettings.getUserIdLPr(uid); 2831 if (obj instanceof SharedUserSetting) { 2832 final SharedUserSetting sus = (SharedUserSetting) obj; 2833 final int N = sus.packages.size(); 2834 final String[] res = new String[N]; 2835 final Iterator<PackageSetting> it = sus.packages.iterator(); 2836 int i = 0; 2837 while (it.hasNext()) { 2838 res[i++] = it.next().name; 2839 } 2840 return res; 2841 } else if (obj instanceof PackageSetting) { 2842 final PackageSetting ps = (PackageSetting) obj; 2843 return new String[] { ps.name }; 2844 } 2845 } 2846 return null; 2847 } 2848 2849 @Override 2850 public String getNameForUid(int uid) { 2851 // reader 2852 synchronized (mPackages) { 2853 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2854 if (obj instanceof SharedUserSetting) { 2855 final SharedUserSetting sus = (SharedUserSetting) obj; 2856 return sus.name + ":" + sus.userId; 2857 } else if (obj instanceof PackageSetting) { 2858 final PackageSetting ps = (PackageSetting) obj; 2859 return ps.name; 2860 } 2861 } 2862 return null; 2863 } 2864 2865 @Override 2866 public int getUidForSharedUser(String sharedUserName) { 2867 if(sharedUserName == null) { 2868 return -1; 2869 } 2870 // reader 2871 synchronized (mPackages) { 2872 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2873 if (suid == null) { 2874 return -1; 2875 } 2876 return suid.userId; 2877 } 2878 } 2879 2880 @Override 2881 public int getFlagsForUid(int uid) { 2882 synchronized (mPackages) { 2883 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2884 if (obj instanceof SharedUserSetting) { 2885 final SharedUserSetting sus = (SharedUserSetting) obj; 2886 return sus.pkgFlags; 2887 } else if (obj instanceof PackageSetting) { 2888 final PackageSetting ps = (PackageSetting) obj; 2889 return ps.pkgFlags; 2890 } 2891 } 2892 return 0; 2893 } 2894 2895 @Override 2896 public String[] getAppOpPermissionPackages(String permissionName) { 2897 synchronized (mPackages) { 2898 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 2899 if (pkgs == null) { 2900 return null; 2901 } 2902 return pkgs.toArray(new String[pkgs.size()]); 2903 } 2904 } 2905 2906 @Override 2907 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2908 int flags, int userId) { 2909 if (!sUserManager.exists(userId)) return null; 2910 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2911 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2912 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2913 } 2914 2915 @Override 2916 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2917 IntentFilter filter, int match, ComponentName activity) { 2918 final int userId = UserHandle.getCallingUserId(); 2919 if (DEBUG_PREFERRED) { 2920 Log.v(TAG, "setLastChosenActivity intent=" + intent 2921 + " resolvedType=" + resolvedType 2922 + " flags=" + flags 2923 + " filter=" + filter 2924 + " match=" + match 2925 + " activity=" + activity); 2926 filter.dump(new PrintStreamPrinter(System.out), " "); 2927 } 2928 intent.setComponent(null); 2929 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2930 // Find any earlier preferred or last chosen entries and nuke them 2931 findPreferredActivity(intent, resolvedType, 2932 flags, query, 0, false, true, false, userId); 2933 // Add the new activity as the last chosen for this filter 2934 addPreferredActivityInternal(filter, match, null, activity, false, userId, 2935 "Setting last chosen"); 2936 } 2937 2938 @Override 2939 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2940 final int userId = UserHandle.getCallingUserId(); 2941 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2942 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2943 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2944 false, false, false, userId); 2945 } 2946 2947 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2948 int flags, List<ResolveInfo> query, int userId) { 2949 if (query != null) { 2950 final int N = query.size(); 2951 if (N == 1) { 2952 return query.get(0); 2953 } else if (N > 1) { 2954 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2955 // If there is more than one activity with the same priority, 2956 // then let the user decide between them. 2957 ResolveInfo r0 = query.get(0); 2958 ResolveInfo r1 = query.get(1); 2959 if (DEBUG_INTENT_MATCHING || debug) { 2960 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2961 + r1.activityInfo.name + "=" + r1.priority); 2962 } 2963 // If the first activity has a higher priority, or a different 2964 // default, then it is always desireable to pick it. 2965 if (r0.priority != r1.priority 2966 || r0.preferredOrder != r1.preferredOrder 2967 || r0.isDefault != r1.isDefault) { 2968 return query.get(0); 2969 } 2970 // If we have saved a preference for a preferred activity for 2971 // this Intent, use that. 2972 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2973 flags, query, r0.priority, true, false, debug, userId); 2974 if (ri != null) { 2975 return ri; 2976 } 2977 if (userId != 0) { 2978 ri = new ResolveInfo(mResolveInfo); 2979 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2980 ri.activityInfo.applicationInfo = new ApplicationInfo( 2981 ri.activityInfo.applicationInfo); 2982 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2983 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2984 return ri; 2985 } 2986 return mResolveInfo; 2987 } 2988 } 2989 return null; 2990 } 2991 2992 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2993 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2994 final int N = query.size(); 2995 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2996 .get(userId); 2997 // Get the list of persistent preferred activities that handle the intent 2998 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2999 List<PersistentPreferredActivity> pprefs = ppir != null 3000 ? ppir.queryIntent(intent, resolvedType, 3001 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3002 : null; 3003 if (pprefs != null && pprefs.size() > 0) { 3004 final int M = pprefs.size(); 3005 for (int i=0; i<M; i++) { 3006 final PersistentPreferredActivity ppa = pprefs.get(i); 3007 if (DEBUG_PREFERRED || debug) { 3008 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3009 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3010 + "\n component=" + ppa.mComponent); 3011 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3012 } 3013 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3014 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3015 if (DEBUG_PREFERRED || debug) { 3016 Slog.v(TAG, "Found persistent preferred activity:"); 3017 if (ai != null) { 3018 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3019 } else { 3020 Slog.v(TAG, " null"); 3021 } 3022 } 3023 if (ai == null) { 3024 // This previously registered persistent preferred activity 3025 // component is no longer known. Ignore it and do NOT remove it. 3026 continue; 3027 } 3028 for (int j=0; j<N; j++) { 3029 final ResolveInfo ri = query.get(j); 3030 if (!ri.activityInfo.applicationInfo.packageName 3031 .equals(ai.applicationInfo.packageName)) { 3032 continue; 3033 } 3034 if (!ri.activityInfo.name.equals(ai.name)) { 3035 continue; 3036 } 3037 // Found a persistent preference that can handle the intent. 3038 if (DEBUG_PREFERRED || debug) { 3039 Slog.v(TAG, "Returning persistent preferred activity: " + 3040 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3041 } 3042 return ri; 3043 } 3044 } 3045 } 3046 return null; 3047 } 3048 3049 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3050 List<ResolveInfo> query, int priority, boolean always, 3051 boolean removeMatches, boolean debug, int userId) { 3052 if (!sUserManager.exists(userId)) return null; 3053 // writer 3054 synchronized (mPackages) { 3055 if (intent.getSelector() != null) { 3056 intent = intent.getSelector(); 3057 } 3058 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3059 3060 // Try to find a matching persistent preferred activity. 3061 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3062 debug, userId); 3063 3064 // If a persistent preferred activity matched, use it. 3065 if (pri != null) { 3066 return pri; 3067 } 3068 3069 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3070 // Get the list of preferred activities that handle the intent 3071 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3072 List<PreferredActivity> prefs = pir != null 3073 ? pir.queryIntent(intent, resolvedType, 3074 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3075 : null; 3076 if (prefs != null && prefs.size() > 0) { 3077 // First figure out how good the original match set is. 3078 // We will only allow preferred activities that came 3079 // from the same match quality. 3080 int match = 0; 3081 3082 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3083 3084 final int N = query.size(); 3085 for (int j=0; j<N; j++) { 3086 final ResolveInfo ri = query.get(j); 3087 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3088 + ": 0x" + Integer.toHexString(match)); 3089 if (ri.match > match) { 3090 match = ri.match; 3091 } 3092 } 3093 3094 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3095 + Integer.toHexString(match)); 3096 3097 match &= IntentFilter.MATCH_CATEGORY_MASK; 3098 final int M = prefs.size(); 3099 for (int i=0; i<M; i++) { 3100 final PreferredActivity pa = prefs.get(i); 3101 if (DEBUG_PREFERRED || debug) { 3102 Slog.v(TAG, "Checking PreferredActivity ds=" 3103 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3104 + "\n component=" + pa.mPref.mComponent); 3105 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3106 } 3107 if (pa.mPref.mMatch != match) { 3108 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3109 + Integer.toHexString(pa.mPref.mMatch)); 3110 continue; 3111 } 3112 // If it's not an "always" type preferred activity and that's what we're 3113 // looking for, skip it. 3114 if (always && !pa.mPref.mAlways) { 3115 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3116 continue; 3117 } 3118 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3119 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3120 if (DEBUG_PREFERRED || debug) { 3121 Slog.v(TAG, "Found preferred activity:"); 3122 if (ai != null) { 3123 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3124 } else { 3125 Slog.v(TAG, " null"); 3126 } 3127 } 3128 if (ai == null) { 3129 // This previously registered preferred activity 3130 // component is no longer known. Most likely an update 3131 // to the app was installed and in the new version this 3132 // component no longer exists. Clean it up by removing 3133 // it from the preferred activities list, and skip it. 3134 Slog.w(TAG, "Removing dangling preferred activity: " 3135 + pa.mPref.mComponent); 3136 pir.removeFilter(pa); 3137 continue; 3138 } 3139 for (int j=0; j<N; j++) { 3140 final ResolveInfo ri = query.get(j); 3141 if (!ri.activityInfo.applicationInfo.packageName 3142 .equals(ai.applicationInfo.packageName)) { 3143 continue; 3144 } 3145 if (!ri.activityInfo.name.equals(ai.name)) { 3146 continue; 3147 } 3148 3149 if (removeMatches) { 3150 pir.removeFilter(pa); 3151 if (DEBUG_PREFERRED) { 3152 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3153 } 3154 break; 3155 } 3156 3157 // Okay we found a previously set preferred or last chosen app. 3158 // If the result set is different from when this 3159 // was created, we need to clear it and re-ask the 3160 // user their preference, if we're looking for an "always" type entry. 3161 if (always && !pa.mPref.sameSet(query, priority)) { 3162 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3163 + intent + " type " + resolvedType); 3164 if (DEBUG_PREFERRED) { 3165 Slog.v(TAG, "Removing preferred activity since set changed " 3166 + pa.mPref.mComponent); 3167 } 3168 pir.removeFilter(pa); 3169 // Re-add the filter as a "last chosen" entry (!always) 3170 PreferredActivity lastChosen = new PreferredActivity( 3171 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3172 pir.addFilter(lastChosen); 3173 mSettings.writePackageRestrictionsLPr(userId); 3174 return null; 3175 } 3176 3177 // Yay! Either the set matched or we're looking for the last chosen 3178 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3179 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3180 mSettings.writePackageRestrictionsLPr(userId); 3181 return ri; 3182 } 3183 } 3184 } 3185 mSettings.writePackageRestrictionsLPr(userId); 3186 } 3187 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3188 return null; 3189 } 3190 3191 /* 3192 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3193 */ 3194 @Override 3195 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3196 int targetUserId) { 3197 mContext.enforceCallingOrSelfPermission( 3198 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3199 List<CrossProfileIntentFilter> matches = 3200 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3201 if (matches != null) { 3202 int size = matches.size(); 3203 for (int i = 0; i < size; i++) { 3204 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3205 } 3206 } 3207 3208 ArrayList<String> packageNames = null; 3209 SparseArray<ArrayList<String>> fromSource = 3210 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3211 if (fromSource != null) { 3212 packageNames = fromSource.get(targetUserId); 3213 } 3214 if (packageNames != null && packageNames.contains(intent.getPackage())) { 3215 return true; 3216 } 3217 // We need the package name, so we try to resolve with the loosest flags possible 3218 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3219 intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3220 int count = resolveInfos.size(); 3221 for (int i = 0; i < count; i++) { 3222 ResolveInfo resolveInfo = resolveInfos.get(i); 3223 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3224 return true; 3225 } 3226 } 3227 return false; 3228 } 3229 3230 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3231 String resolvedType, int userId) { 3232 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3233 if (resolver != null) { 3234 return resolver.queryIntent(intent, resolvedType, false, userId); 3235 } 3236 return null; 3237 } 3238 3239 @Override 3240 public List<ResolveInfo> queryIntentActivities(Intent intent, 3241 String resolvedType, int flags, int userId) { 3242 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3243 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3244 ComponentName comp = intent.getComponent(); 3245 if (comp == null) { 3246 if (intent.getSelector() != null) { 3247 intent = intent.getSelector(); 3248 comp = intent.getComponent(); 3249 } 3250 } 3251 3252 if (comp != null) { 3253 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3254 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3255 if (ai != null) { 3256 final ResolveInfo ri = new ResolveInfo(); 3257 ri.activityInfo = ai; 3258 list.add(ri); 3259 } 3260 return list; 3261 } 3262 3263 // reader 3264 synchronized (mPackages) { 3265 final String pkgName = intent.getPackage(); 3266 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3267 if (pkgName == null) { 3268 ResolveInfo resolveInfo = null; 3269 if (queryCrossProfile) { 3270 // Check if the intent needs to be forwarded to another user for this package 3271 ArrayList<ResolveInfo> crossProfileResult = 3272 queryIntentActivitiesCrossProfilePackage( 3273 intent, resolvedType, flags, userId); 3274 if (!crossProfileResult.isEmpty()) { 3275 // Skip the current profile 3276 return crossProfileResult; 3277 } 3278 List<CrossProfileIntentFilter> matchingFilters = 3279 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3280 // Check for results that need to skip the current profile. 3281 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3282 resolvedType, flags, userId); 3283 if (resolveInfo != null) { 3284 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3285 result.add(resolveInfo); 3286 return result; 3287 } 3288 // Check for cross profile results. 3289 resolveInfo = queryCrossProfileIntents( 3290 matchingFilters, intent, resolvedType, flags, userId); 3291 } 3292 // Check for results in the current profile. 3293 List<ResolveInfo> result = mActivities.queryIntent( 3294 intent, resolvedType, flags, userId); 3295 if (resolveInfo != null) { 3296 result.add(resolveInfo); 3297 } 3298 return result; 3299 } 3300 final PackageParser.Package pkg = mPackages.get(pkgName); 3301 if (pkg != null) { 3302 if (queryCrossProfile) { 3303 ArrayList<ResolveInfo> crossProfileResult = 3304 queryIntentActivitiesCrossProfilePackage( 3305 intent, resolvedType, flags, userId, pkg, pkgName); 3306 if (!crossProfileResult.isEmpty()) { 3307 // Skip the current profile 3308 return crossProfileResult; 3309 } 3310 } 3311 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3312 pkg.activities, userId); 3313 } 3314 return new ArrayList<ResolveInfo>(); 3315 } 3316 } 3317 3318 private ResolveInfo querySkipCurrentProfileIntents( 3319 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3320 int flags, int sourceUserId) { 3321 if (matchingFilters != null) { 3322 int size = matchingFilters.size(); 3323 for (int i = 0; i < size; i ++) { 3324 CrossProfileIntentFilter filter = matchingFilters.get(i); 3325 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3326 // Checking if there are activities in the target user that can handle the 3327 // intent. 3328 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3329 flags, sourceUserId); 3330 if (resolveInfo != null) { 3331 return resolveInfo; 3332 } 3333 } 3334 } 3335 } 3336 return null; 3337 } 3338 3339 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3340 Intent intent, String resolvedType, int flags, int userId) { 3341 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3342 SparseArray<ArrayList<String>> sourceForwardingInfo = 3343 mSettings.mCrossProfilePackageInfo.get(userId); 3344 if (sourceForwardingInfo != null) { 3345 int NI = sourceForwardingInfo.size(); 3346 for (int i = 0; i < NI; i++) { 3347 int targetUserId = sourceForwardingInfo.keyAt(i); 3348 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3349 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3350 intent, resolvedType, flags, targetUserId); 3351 int NJ = resolveInfos.size(); 3352 for (int j = 0; j < NJ; j++) { 3353 ResolveInfo resolveInfo = resolveInfos.get(j); 3354 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3355 matchingResolveInfos.add(createForwardingResolveInfo( 3356 resolveInfo.filter, userId, targetUserId)); 3357 } 3358 } 3359 } 3360 } 3361 return matchingResolveInfos; 3362 } 3363 3364 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3365 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3366 String packageName) { 3367 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3368 SparseArray<ArrayList<String>> sourceForwardingInfo = 3369 mSettings.mCrossProfilePackageInfo.get(userId); 3370 if (sourceForwardingInfo != null) { 3371 int NI = sourceForwardingInfo.size(); 3372 for (int i = 0; i < NI; i++) { 3373 int targetUserId = sourceForwardingInfo.keyAt(i); 3374 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3375 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3376 intent, resolvedType, flags, pkg.activities, targetUserId); 3377 int NJ = resolveInfos.size(); 3378 for (int j = 0; j < NJ; j++) { 3379 ResolveInfo resolveInfo = resolveInfos.get(j); 3380 matchingResolveInfos.add(createForwardingResolveInfo( 3381 resolveInfo.filter, userId, targetUserId)); 3382 } 3383 } 3384 } 3385 } 3386 return matchingResolveInfos; 3387 } 3388 3389 // Return matching ResolveInfo if any for skip current profile intent filters. 3390 private ResolveInfo queryCrossProfileIntents( 3391 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3392 int flags, int sourceUserId) { 3393 if (matchingFilters != null) { 3394 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3395 // match the same intent. For performance reasons, it is better not to 3396 // run queryIntent twice for the same userId 3397 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3398 int size = matchingFilters.size(); 3399 for (int i = 0; i < size; i++) { 3400 CrossProfileIntentFilter filter = matchingFilters.get(i); 3401 int targetUserId = filter.getTargetUserId(); 3402 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3403 && !alreadyTriedUserIds.get(targetUserId)) { 3404 // Checking if there are activities in the target user that can handle the 3405 // intent. 3406 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3407 flags, sourceUserId); 3408 if (resolveInfo != null) return resolveInfo; 3409 alreadyTriedUserIds.put(targetUserId, true); 3410 } 3411 } 3412 } 3413 return null; 3414 } 3415 3416 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3417 String resolvedType, int flags, int sourceUserId) { 3418 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3419 resolvedType, flags, filter.getTargetUserId()); 3420 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3421 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3422 } 3423 return null; 3424 } 3425 3426 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3427 int sourceUserId, int targetUserId) { 3428 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3429 String className; 3430 if (targetUserId == UserHandle.USER_OWNER) { 3431 className = FORWARD_INTENT_TO_USER_OWNER; 3432 } else { 3433 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3434 } 3435 ComponentName forwardingActivityComponentName = new ComponentName( 3436 mAndroidApplication.packageName, className); 3437 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3438 sourceUserId); 3439 if (targetUserId == UserHandle.USER_OWNER) { 3440 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3441 forwardingResolveInfo.noResourceId = true; 3442 } 3443 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3444 forwardingResolveInfo.priority = 0; 3445 forwardingResolveInfo.preferredOrder = 0; 3446 forwardingResolveInfo.match = 0; 3447 forwardingResolveInfo.isDefault = true; 3448 forwardingResolveInfo.filter = filter; 3449 forwardingResolveInfo.targetUserId = targetUserId; 3450 return forwardingResolveInfo; 3451 } 3452 3453 @Override 3454 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3455 Intent[] specifics, String[] specificTypes, Intent intent, 3456 String resolvedType, int flags, int userId) { 3457 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3458 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3459 "query intent activity options"); 3460 final String resultsAction = intent.getAction(); 3461 3462 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3463 | PackageManager.GET_RESOLVED_FILTER, userId); 3464 3465 if (DEBUG_INTENT_MATCHING) { 3466 Log.v(TAG, "Query " + intent + ": " + results); 3467 } 3468 3469 int specificsPos = 0; 3470 int N; 3471 3472 // todo: note that the algorithm used here is O(N^2). This 3473 // isn't a problem in our current environment, but if we start running 3474 // into situations where we have more than 5 or 10 matches then this 3475 // should probably be changed to something smarter... 3476 3477 // First we go through and resolve each of the specific items 3478 // that were supplied, taking care of removing any corresponding 3479 // duplicate items in the generic resolve list. 3480 if (specifics != null) { 3481 for (int i=0; i<specifics.length; i++) { 3482 final Intent sintent = specifics[i]; 3483 if (sintent == null) { 3484 continue; 3485 } 3486 3487 if (DEBUG_INTENT_MATCHING) { 3488 Log.v(TAG, "Specific #" + i + ": " + sintent); 3489 } 3490 3491 String action = sintent.getAction(); 3492 if (resultsAction != null && resultsAction.equals(action)) { 3493 // If this action was explicitly requested, then don't 3494 // remove things that have it. 3495 action = null; 3496 } 3497 3498 ResolveInfo ri = null; 3499 ActivityInfo ai = null; 3500 3501 ComponentName comp = sintent.getComponent(); 3502 if (comp == null) { 3503 ri = resolveIntent( 3504 sintent, 3505 specificTypes != null ? specificTypes[i] : null, 3506 flags, userId); 3507 if (ri == null) { 3508 continue; 3509 } 3510 if (ri == mResolveInfo) { 3511 // ACK! Must do something better with this. 3512 } 3513 ai = ri.activityInfo; 3514 comp = new ComponentName(ai.applicationInfo.packageName, 3515 ai.name); 3516 } else { 3517 ai = getActivityInfo(comp, flags, userId); 3518 if (ai == null) { 3519 continue; 3520 } 3521 } 3522 3523 // Look for any generic query activities that are duplicates 3524 // of this specific one, and remove them from the results. 3525 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3526 N = results.size(); 3527 int j; 3528 for (j=specificsPos; j<N; j++) { 3529 ResolveInfo sri = results.get(j); 3530 if ((sri.activityInfo.name.equals(comp.getClassName()) 3531 && sri.activityInfo.applicationInfo.packageName.equals( 3532 comp.getPackageName())) 3533 || (action != null && sri.filter.matchAction(action))) { 3534 results.remove(j); 3535 if (DEBUG_INTENT_MATCHING) Log.v( 3536 TAG, "Removing duplicate item from " + j 3537 + " due to specific " + specificsPos); 3538 if (ri == null) { 3539 ri = sri; 3540 } 3541 j--; 3542 N--; 3543 } 3544 } 3545 3546 // Add this specific item to its proper place. 3547 if (ri == null) { 3548 ri = new ResolveInfo(); 3549 ri.activityInfo = ai; 3550 } 3551 results.add(specificsPos, ri); 3552 ri.specificIndex = i; 3553 specificsPos++; 3554 } 3555 } 3556 3557 // Now we go through the remaining generic results and remove any 3558 // duplicate actions that are found here. 3559 N = results.size(); 3560 for (int i=specificsPos; i<N-1; i++) { 3561 final ResolveInfo rii = results.get(i); 3562 if (rii.filter == null) { 3563 continue; 3564 } 3565 3566 // Iterate over all of the actions of this result's intent 3567 // filter... typically this should be just one. 3568 final Iterator<String> it = rii.filter.actionsIterator(); 3569 if (it == null) { 3570 continue; 3571 } 3572 while (it.hasNext()) { 3573 final String action = it.next(); 3574 if (resultsAction != null && resultsAction.equals(action)) { 3575 // If this action was explicitly requested, then don't 3576 // remove things that have it. 3577 continue; 3578 } 3579 for (int j=i+1; j<N; j++) { 3580 final ResolveInfo rij = results.get(j); 3581 if (rij.filter != null && rij.filter.hasAction(action)) { 3582 results.remove(j); 3583 if (DEBUG_INTENT_MATCHING) Log.v( 3584 TAG, "Removing duplicate item from " + j 3585 + " due to action " + action + " at " + i); 3586 j--; 3587 N--; 3588 } 3589 } 3590 } 3591 3592 // If the caller didn't request filter information, drop it now 3593 // so we don't have to marshall/unmarshall it. 3594 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3595 rii.filter = null; 3596 } 3597 } 3598 3599 // Filter out the caller activity if so requested. 3600 if (caller != null) { 3601 N = results.size(); 3602 for (int i=0; i<N; i++) { 3603 ActivityInfo ainfo = results.get(i).activityInfo; 3604 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3605 && caller.getClassName().equals(ainfo.name)) { 3606 results.remove(i); 3607 break; 3608 } 3609 } 3610 } 3611 3612 // If the caller didn't request filter information, 3613 // drop them now so we don't have to 3614 // marshall/unmarshall it. 3615 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3616 N = results.size(); 3617 for (int i=0; i<N; i++) { 3618 results.get(i).filter = null; 3619 } 3620 } 3621 3622 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3623 return results; 3624 } 3625 3626 @Override 3627 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3628 int userId) { 3629 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3630 ComponentName comp = intent.getComponent(); 3631 if (comp == null) { 3632 if (intent.getSelector() != null) { 3633 intent = intent.getSelector(); 3634 comp = intent.getComponent(); 3635 } 3636 } 3637 if (comp != null) { 3638 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3639 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3640 if (ai != null) { 3641 ResolveInfo ri = new ResolveInfo(); 3642 ri.activityInfo = ai; 3643 list.add(ri); 3644 } 3645 return list; 3646 } 3647 3648 // reader 3649 synchronized (mPackages) { 3650 String pkgName = intent.getPackage(); 3651 if (pkgName == null) { 3652 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3653 } 3654 final PackageParser.Package pkg = mPackages.get(pkgName); 3655 if (pkg != null) { 3656 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3657 userId); 3658 } 3659 return null; 3660 } 3661 } 3662 3663 @Override 3664 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3665 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3666 if (!sUserManager.exists(userId)) return null; 3667 if (query != null) { 3668 if (query.size() >= 1) { 3669 // If there is more than one service with the same priority, 3670 // just arbitrarily pick the first one. 3671 return query.get(0); 3672 } 3673 } 3674 return null; 3675 } 3676 3677 @Override 3678 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3679 int userId) { 3680 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3681 ComponentName comp = intent.getComponent(); 3682 if (comp == null) { 3683 if (intent.getSelector() != null) { 3684 intent = intent.getSelector(); 3685 comp = intent.getComponent(); 3686 } 3687 } 3688 if (comp != null) { 3689 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3690 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3691 if (si != null) { 3692 final ResolveInfo ri = new ResolveInfo(); 3693 ri.serviceInfo = si; 3694 list.add(ri); 3695 } 3696 return list; 3697 } 3698 3699 // reader 3700 synchronized (mPackages) { 3701 String pkgName = intent.getPackage(); 3702 if (pkgName == null) { 3703 return mServices.queryIntent(intent, resolvedType, flags, userId); 3704 } 3705 final PackageParser.Package pkg = mPackages.get(pkgName); 3706 if (pkg != null) { 3707 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3708 userId); 3709 } 3710 return null; 3711 } 3712 } 3713 3714 @Override 3715 public List<ResolveInfo> queryIntentContentProviders( 3716 Intent intent, String resolvedType, int flags, int userId) { 3717 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3718 ComponentName comp = intent.getComponent(); 3719 if (comp == null) { 3720 if (intent.getSelector() != null) { 3721 intent = intent.getSelector(); 3722 comp = intent.getComponent(); 3723 } 3724 } 3725 if (comp != null) { 3726 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3727 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3728 if (pi != null) { 3729 final ResolveInfo ri = new ResolveInfo(); 3730 ri.providerInfo = pi; 3731 list.add(ri); 3732 } 3733 return list; 3734 } 3735 3736 // reader 3737 synchronized (mPackages) { 3738 String pkgName = intent.getPackage(); 3739 if (pkgName == null) { 3740 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3741 } 3742 final PackageParser.Package pkg = mPackages.get(pkgName); 3743 if (pkg != null) { 3744 return mProviders.queryIntentForPackage( 3745 intent, resolvedType, flags, pkg.providers, userId); 3746 } 3747 return null; 3748 } 3749 } 3750 3751 @Override 3752 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3753 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3754 3755 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3756 3757 // writer 3758 synchronized (mPackages) { 3759 ArrayList<PackageInfo> list; 3760 if (listUninstalled) { 3761 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3762 for (PackageSetting ps : mSettings.mPackages.values()) { 3763 PackageInfo pi; 3764 if (ps.pkg != null) { 3765 pi = generatePackageInfo(ps.pkg, flags, userId); 3766 } else { 3767 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3768 } 3769 if (pi != null) { 3770 list.add(pi); 3771 } 3772 } 3773 } else { 3774 list = new ArrayList<PackageInfo>(mPackages.size()); 3775 for (PackageParser.Package p : mPackages.values()) { 3776 PackageInfo pi = generatePackageInfo(p, flags, userId); 3777 if (pi != null) { 3778 list.add(pi); 3779 } 3780 } 3781 } 3782 3783 return new ParceledListSlice<PackageInfo>(list); 3784 } 3785 } 3786 3787 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3788 String[] permissions, boolean[] tmp, int flags, int userId) { 3789 int numMatch = 0; 3790 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3791 for (int i=0; i<permissions.length; i++) { 3792 if (gp.grantedPermissions.contains(permissions[i])) { 3793 tmp[i] = true; 3794 numMatch++; 3795 } else { 3796 tmp[i] = false; 3797 } 3798 } 3799 if (numMatch == 0) { 3800 return; 3801 } 3802 PackageInfo pi; 3803 if (ps.pkg != null) { 3804 pi = generatePackageInfo(ps.pkg, flags, userId); 3805 } else { 3806 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3807 } 3808 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3809 if (numMatch == permissions.length) { 3810 pi.requestedPermissions = permissions; 3811 } else { 3812 pi.requestedPermissions = new String[numMatch]; 3813 numMatch = 0; 3814 for (int i=0; i<permissions.length; i++) { 3815 if (tmp[i]) { 3816 pi.requestedPermissions[numMatch] = permissions[i]; 3817 numMatch++; 3818 } 3819 } 3820 } 3821 } 3822 list.add(pi); 3823 } 3824 3825 @Override 3826 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3827 String[] permissions, int flags, int userId) { 3828 if (!sUserManager.exists(userId)) return null; 3829 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3830 3831 // writer 3832 synchronized (mPackages) { 3833 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3834 boolean[] tmpBools = new boolean[permissions.length]; 3835 if (listUninstalled) { 3836 for (PackageSetting ps : mSettings.mPackages.values()) { 3837 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3838 } 3839 } else { 3840 for (PackageParser.Package pkg : mPackages.values()) { 3841 PackageSetting ps = (PackageSetting)pkg.mExtras; 3842 if (ps != null) { 3843 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3844 userId); 3845 } 3846 } 3847 } 3848 3849 return new ParceledListSlice<PackageInfo>(list); 3850 } 3851 } 3852 3853 @Override 3854 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3855 if (!sUserManager.exists(userId)) return null; 3856 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3857 3858 // writer 3859 synchronized (mPackages) { 3860 ArrayList<ApplicationInfo> list; 3861 if (listUninstalled) { 3862 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3863 for (PackageSetting ps : mSettings.mPackages.values()) { 3864 ApplicationInfo ai; 3865 if (ps.pkg != null) { 3866 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3867 ps.readUserState(userId), userId); 3868 } else { 3869 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3870 } 3871 if (ai != null) { 3872 list.add(ai); 3873 } 3874 } 3875 } else { 3876 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3877 for (PackageParser.Package p : mPackages.values()) { 3878 if (p.mExtras != null) { 3879 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3880 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3881 if (ai != null) { 3882 list.add(ai); 3883 } 3884 } 3885 } 3886 } 3887 3888 return new ParceledListSlice<ApplicationInfo>(list); 3889 } 3890 } 3891 3892 public List<ApplicationInfo> getPersistentApplications(int flags) { 3893 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3894 3895 // reader 3896 synchronized (mPackages) { 3897 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3898 final int userId = UserHandle.getCallingUserId(); 3899 while (i.hasNext()) { 3900 final PackageParser.Package p = i.next(); 3901 if (p.applicationInfo != null 3902 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3903 && (!mSafeMode || isSystemApp(p))) { 3904 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3905 if (ps != null) { 3906 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3907 ps.readUserState(userId), userId); 3908 if (ai != null) { 3909 finalList.add(ai); 3910 } 3911 } 3912 } 3913 } 3914 } 3915 3916 return finalList; 3917 } 3918 3919 @Override 3920 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3921 if (!sUserManager.exists(userId)) return null; 3922 // reader 3923 synchronized (mPackages) { 3924 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3925 PackageSetting ps = provider != null 3926 ? mSettings.mPackages.get(provider.owner.packageName) 3927 : null; 3928 return ps != null 3929 && mSettings.isEnabledLPr(provider.info, flags, userId) 3930 && (!mSafeMode || (provider.info.applicationInfo.flags 3931 &ApplicationInfo.FLAG_SYSTEM) != 0) 3932 ? PackageParser.generateProviderInfo(provider, flags, 3933 ps.readUserState(userId), userId) 3934 : null; 3935 } 3936 } 3937 3938 /** 3939 * @deprecated 3940 */ 3941 @Deprecated 3942 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3943 // reader 3944 synchronized (mPackages) { 3945 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3946 .entrySet().iterator(); 3947 final int userId = UserHandle.getCallingUserId(); 3948 while (i.hasNext()) { 3949 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3950 PackageParser.Provider p = entry.getValue(); 3951 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3952 3953 if (ps != null && p.syncable 3954 && (!mSafeMode || (p.info.applicationInfo.flags 3955 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3956 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3957 ps.readUserState(userId), userId); 3958 if (info != null) { 3959 outNames.add(entry.getKey()); 3960 outInfo.add(info); 3961 } 3962 } 3963 } 3964 } 3965 } 3966 3967 @Override 3968 public List<ProviderInfo> queryContentProviders(String processName, 3969 int uid, int flags) { 3970 ArrayList<ProviderInfo> finalList = null; 3971 // reader 3972 synchronized (mPackages) { 3973 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3974 final int userId = processName != null ? 3975 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3976 while (i.hasNext()) { 3977 final PackageParser.Provider p = i.next(); 3978 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3979 if (ps != null && p.info.authority != null 3980 && (processName == null 3981 || (p.info.processName.equals(processName) 3982 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3983 && mSettings.isEnabledLPr(p.info, flags, userId) 3984 && (!mSafeMode 3985 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3986 if (finalList == null) { 3987 finalList = new ArrayList<ProviderInfo>(3); 3988 } 3989 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3990 ps.readUserState(userId), userId); 3991 if (info != null) { 3992 finalList.add(info); 3993 } 3994 } 3995 } 3996 } 3997 3998 if (finalList != null) { 3999 Collections.sort(finalList, mProviderInitOrderSorter); 4000 } 4001 4002 return finalList; 4003 } 4004 4005 @Override 4006 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4007 int flags) { 4008 // reader 4009 synchronized (mPackages) { 4010 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4011 return PackageParser.generateInstrumentationInfo(i, flags); 4012 } 4013 } 4014 4015 @Override 4016 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4017 int flags) { 4018 ArrayList<InstrumentationInfo> finalList = 4019 new ArrayList<InstrumentationInfo>(); 4020 4021 // reader 4022 synchronized (mPackages) { 4023 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4024 while (i.hasNext()) { 4025 final PackageParser.Instrumentation p = i.next(); 4026 if (targetPackage == null 4027 || targetPackage.equals(p.info.targetPackage)) { 4028 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4029 flags); 4030 if (ii != null) { 4031 finalList.add(ii); 4032 } 4033 } 4034 } 4035 } 4036 4037 return finalList; 4038 } 4039 4040 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4041 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4042 if (overlays == null) { 4043 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4044 return; 4045 } 4046 for (PackageParser.Package opkg : overlays.values()) { 4047 // Not much to do if idmap fails: we already logged the error 4048 // and we certainly don't want to abort installation of pkg simply 4049 // because an overlay didn't fit properly. For these reasons, 4050 // ignore the return value of createIdmapForPackagePairLI. 4051 createIdmapForPackagePairLI(pkg, opkg); 4052 } 4053 } 4054 4055 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4056 PackageParser.Package opkg) { 4057 if (!opkg.mTrustedOverlay) { 4058 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4059 opkg.baseCodePath + ": overlay not trusted"); 4060 return false; 4061 } 4062 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4063 if (overlaySet == null) { 4064 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4065 opkg.baseCodePath + " but target package has no known overlays"); 4066 return false; 4067 } 4068 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4069 // TODO: generate idmap for split APKs 4070 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4071 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4072 + opkg.baseCodePath); 4073 return false; 4074 } 4075 PackageParser.Package[] overlayArray = 4076 overlaySet.values().toArray(new PackageParser.Package[0]); 4077 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4078 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4079 return p1.mOverlayPriority - p2.mOverlayPriority; 4080 } 4081 }; 4082 Arrays.sort(overlayArray, cmp); 4083 4084 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4085 int i = 0; 4086 for (PackageParser.Package p : overlayArray) { 4087 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4088 } 4089 return true; 4090 } 4091 4092 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4093 final File[] files = dir.listFiles(); 4094 if (ArrayUtils.isEmpty(files)) { 4095 Log.d(TAG, "No files in app dir " + dir); 4096 return; 4097 } 4098 4099 if (DEBUG_PACKAGE_SCANNING) { 4100 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4101 + " flags=0x" + Integer.toHexString(flags)); 4102 } 4103 4104 for (File file : files) { 4105 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4106 && !PackageInstallerService.isStageFile(file); 4107 if (!isPackage) { 4108 // Ignore entries which are not apk's 4109 continue; 4110 } 4111 try { 4112 scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null); 4113 } catch (PackageManagerException e) { 4114 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4115 4116 // Don't mess around with apps in system partition. 4117 if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4118 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4119 // Delete the apk 4120 Slog.w(TAG, "Cleaning up failed install of " + file); 4121 file.delete(); 4122 } 4123 } 4124 } 4125 } 4126 4127 private static File getSettingsProblemFile() { 4128 File dataDir = Environment.getDataDirectory(); 4129 File systemDir = new File(dataDir, "system"); 4130 File fname = new File(systemDir, "uiderrors.txt"); 4131 return fname; 4132 } 4133 4134 static void reportSettingsProblem(int priority, String msg) { 4135 try { 4136 File fname = getSettingsProblemFile(); 4137 FileOutputStream out = new FileOutputStream(fname, true); 4138 PrintWriter pw = new FastPrintWriter(out); 4139 SimpleDateFormat formatter = new SimpleDateFormat(); 4140 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4141 pw.println(dateString + ": " + msg); 4142 pw.close(); 4143 FileUtils.setPermissions( 4144 fname.toString(), 4145 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4146 -1, -1); 4147 } catch (java.io.IOException e) { 4148 } 4149 Slog.println(priority, TAG, msg); 4150 } 4151 4152 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4153 PackageParser.Package pkg, File srcFile, int parseFlags) 4154 throws PackageManagerException { 4155 if (ps != null 4156 && ps.codePath.equals(srcFile) 4157 && ps.timeStamp == srcFile.lastModified() 4158 && !isCompatSignatureUpdateNeeded(pkg)) { 4159 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4160 if (ps.signatures.mSignatures != null 4161 && ps.signatures.mSignatures.length != 0 4162 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4163 // Optimization: reuse the existing cached certificates 4164 // if the package appears to be unchanged. 4165 pkg.mSignatures = ps.signatures.mSignatures; 4166 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4167 synchronized (mPackages) { 4168 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4169 } 4170 return; 4171 } 4172 4173 Slog.w(TAG, "PackageSetting for " + ps.name 4174 + " is missing signatures. Collecting certs again to recover them."); 4175 } else { 4176 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4177 } 4178 4179 try { 4180 pp.collectCertificates(pkg, parseFlags); 4181 pp.collectManifestDigest(pkg); 4182 } catch (PackageParserException e) { 4183 throw new PackageManagerException(e.error, "Failed to collect certificates for " 4184 + pkg.packageName + ": " + e.getMessage()); 4185 } 4186 } 4187 4188 /* 4189 * Scan a package and return the newly parsed package. 4190 * Returns null in case of errors and the error code is stored in mLastScanError 4191 */ 4192 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode, 4193 long currentTime, UserHandle user) throws PackageManagerException { 4194 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4195 parseFlags |= mDefParseFlags; 4196 PackageParser pp = new PackageParser(); 4197 pp.setSeparateProcesses(mSeparateProcesses); 4198 pp.setOnlyCoreApps(mOnlyCore); 4199 pp.setDisplayMetrics(mMetrics); 4200 4201 if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) { 4202 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4203 } 4204 4205 final PackageParser.Package pkg; 4206 try { 4207 pkg = pp.parsePackage(scanFile, parseFlags); 4208 } catch (PackageParserException e) { 4209 throw new PackageManagerException(e.error, 4210 "Failed to scan " + scanFile + ": " + e.getMessage()); 4211 } 4212 4213 PackageSetting ps = null; 4214 PackageSetting updatedPkg; 4215 // reader 4216 synchronized (mPackages) { 4217 // Look to see if we already know about this package. 4218 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4219 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4220 // This package has been renamed to its original name. Let's 4221 // use that. 4222 ps = mSettings.peekPackageLPr(oldName); 4223 } 4224 // If there was no original package, see one for the real package name. 4225 if (ps == null) { 4226 ps = mSettings.peekPackageLPr(pkg.packageName); 4227 } 4228 // Check to see if this package could be hiding/updating a system 4229 // package. Must look for it either under the original or real 4230 // package name depending on our state. 4231 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4232 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4233 } 4234 boolean updatedPkgBetter = false; 4235 // First check if this is a system package that may involve an update 4236 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4237 if (ps != null && !ps.codePath.equals(scanFile)) { 4238 // The path has changed from what was last scanned... check the 4239 // version of the new path against what we have stored to determine 4240 // what to do. 4241 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4242 if (pkg.mVersionCode < ps.versionCode) { 4243 // The system package has been updated and the code path does not match 4244 // Ignore entry. Skip it. 4245 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4246 + " ignored: updated version " + ps.versionCode 4247 + " better than this " + pkg.mVersionCode); 4248 if (!updatedPkg.codePath.equals(scanFile)) { 4249 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4250 + ps.name + " changing from " + updatedPkg.codePathString 4251 + " to " + scanFile); 4252 updatedPkg.codePath = scanFile; 4253 updatedPkg.codePathString = scanFile.toString(); 4254 // This is the point at which we know that the system-disk APK 4255 // for this package has moved during a reboot (e.g. due to an OTA), 4256 // so we need to reevaluate it for privilege policy. 4257 if (locationIsPrivileged(scanFile)) { 4258 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4259 } 4260 } 4261 updatedPkg.pkg = pkg; 4262 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4263 } else { 4264 // The current app on the system partition is better than 4265 // what we have updated to on the data partition; switch 4266 // back to the system partition version. 4267 // At this point, its safely assumed that package installation for 4268 // apps in system partition will go through. If not there won't be a working 4269 // version of the app 4270 // writer 4271 synchronized (mPackages) { 4272 // Just remove the loaded entries from package lists. 4273 mPackages.remove(ps.name); 4274 } 4275 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4276 + "reverting from " + ps.codePathString 4277 + ": new version " + pkg.mVersionCode 4278 + " better than installed " + ps.versionCode); 4279 4280 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4281 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4282 getAppDexInstructionSets(ps), isMultiArch(ps)); 4283 synchronized (mInstallLock) { 4284 args.cleanUpResourcesLI(); 4285 } 4286 synchronized (mPackages) { 4287 mSettings.enableSystemPackageLPw(ps.name); 4288 } 4289 updatedPkgBetter = true; 4290 } 4291 } 4292 } 4293 4294 if (updatedPkg != null) { 4295 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4296 // initially 4297 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4298 4299 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4300 // flag set initially 4301 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4302 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4303 } 4304 } 4305 4306 // Verify certificates against what was last scanned 4307 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4308 4309 /* 4310 * A new system app appeared, but we already had a non-system one of the 4311 * same name installed earlier. 4312 */ 4313 boolean shouldHideSystemApp = false; 4314 if (updatedPkg == null && ps != null 4315 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4316 /* 4317 * Check to make sure the signatures match first. If they don't, 4318 * wipe the installed application and its data. 4319 */ 4320 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4321 != PackageManager.SIGNATURE_MATCH) { 4322 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4323 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4324 ps = null; 4325 } else { 4326 /* 4327 * If the newly-added system app is an older version than the 4328 * already installed version, hide it. It will be scanned later 4329 * and re-added like an update. 4330 */ 4331 if (pkg.mVersionCode < ps.versionCode) { 4332 shouldHideSystemApp = true; 4333 } else { 4334 /* 4335 * The newly found system app is a newer version that the 4336 * one previously installed. Simply remove the 4337 * already-installed application and replace it with our own 4338 * while keeping the application data. 4339 */ 4340 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4341 + ps.codePathString + ": new version " + pkg.mVersionCode 4342 + " better than installed " + ps.versionCode); 4343 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4344 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4345 getAppDexInstructionSets(ps), isMultiArch(ps)); 4346 synchronized (mInstallLock) { 4347 args.cleanUpResourcesLI(); 4348 } 4349 } 4350 } 4351 } 4352 4353 // The apk is forward locked (not public) if its code and resources 4354 // are kept in different files. (except for app in either system or 4355 // vendor path). 4356 // TODO grab this value from PackageSettings 4357 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4358 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4359 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4360 } 4361 } 4362 4363 // TODO: extend to support forward-locked splits 4364 String resourcePath = null; 4365 String baseResourcePath = null; 4366 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4367 if (ps != null && ps.resourcePathString != null) { 4368 resourcePath = ps.resourcePathString; 4369 baseResourcePath = ps.resourcePathString; 4370 } else { 4371 // Should not happen at all. Just log an error. 4372 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4373 } 4374 } else { 4375 resourcePath = pkg.codePath; 4376 baseResourcePath = pkg.baseCodePath; 4377 } 4378 4379 // Set application objects path explicitly. 4380 pkg.applicationInfo.setCodePath(pkg.codePath); 4381 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4382 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4383 pkg.applicationInfo.setResourcePath(resourcePath); 4384 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4385 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4386 4387 // Note that we invoke the following method only if we are about to unpack an application 4388 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4389 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4390 4391 /* 4392 * If the system app should be overridden by a previously installed 4393 * data, hide the system app now and let the /data/app scan pick it up 4394 * again. 4395 */ 4396 if (shouldHideSystemApp) { 4397 synchronized (mPackages) { 4398 /* 4399 * We have to grant systems permissions before we hide, because 4400 * grantPermissions will assume the package update is trying to 4401 * expand its permissions. 4402 */ 4403 grantPermissionsLPw(pkg, true); 4404 mSettings.disableSystemPackageLPw(pkg.packageName); 4405 } 4406 } 4407 4408 return scannedPkg; 4409 } 4410 4411 private static String fixProcessName(String defProcessName, 4412 String processName, int uid) { 4413 if (processName == null) { 4414 return defProcessName; 4415 } 4416 return processName; 4417 } 4418 4419 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4420 throws PackageManagerException { 4421 if (pkgSetting.signatures.mSignatures != null) { 4422 // Already existing package. Make sure signatures match 4423 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4424 == PackageManager.SIGNATURE_MATCH; 4425 if (!match) { 4426 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4427 == PackageManager.SIGNATURE_MATCH; 4428 } 4429 if (!match) { 4430 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4431 + pkg.packageName + " signatures do not match the " 4432 + "previously installed version; ignoring!"); 4433 } 4434 } 4435 4436 // Check for shared user signatures 4437 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4438 // Already existing package. Make sure signatures match 4439 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4440 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4441 if (!match) { 4442 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4443 == PackageManager.SIGNATURE_MATCH; 4444 } 4445 if (!match) { 4446 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4447 "Package " + pkg.packageName 4448 + " has no signatures that match those in shared user " 4449 + pkgSetting.sharedUser.name + "; ignoring!"); 4450 } 4451 } 4452 } 4453 4454 /** 4455 * Enforces that only the system UID or root's UID can call a method exposed 4456 * via Binder. 4457 * 4458 * @param message used as message if SecurityException is thrown 4459 * @throws SecurityException if the caller is not system or root 4460 */ 4461 private static final void enforceSystemOrRoot(String message) { 4462 final int uid = Binder.getCallingUid(); 4463 if (uid != Process.SYSTEM_UID && uid != 0) { 4464 throw new SecurityException(message); 4465 } 4466 } 4467 4468 @Override 4469 public void performBootDexOpt() { 4470 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4471 4472 final HashSet<PackageParser.Package> pkgs; 4473 synchronized (mPackages) { 4474 pkgs = mDeferredDexOpt; 4475 mDeferredDexOpt = null; 4476 } 4477 4478 if (pkgs != null) { 4479 // Filter out packages that aren't recently used. 4480 // 4481 // The exception is first boot of a non-eng device, which 4482 // should do a full dexopt. 4483 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4484 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4485 // TODO: add a property to control this? 4486 long dexOptLRUThresholdInMinutes; 4487 if (eng) { 4488 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4489 } else { 4490 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4491 } 4492 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4493 4494 int total = pkgs.size(); 4495 int skipped = 0; 4496 long now = System.currentTimeMillis(); 4497 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4498 PackageParser.Package pkg = i.next(); 4499 long then = pkg.mLastPackageUsageTimeInMills; 4500 if (then + dexOptLRUThresholdInMills < now) { 4501 if (DEBUG_DEXOPT) { 4502 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4503 ((then == 0) ? "never" : new Date(then))); 4504 } 4505 i.remove(); 4506 skipped++; 4507 } 4508 } 4509 if (DEBUG_DEXOPT) { 4510 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4511 } 4512 } 4513 4514 int i = 0; 4515 for (PackageParser.Package pkg : pkgs) { 4516 i++; 4517 if (DEBUG_DEXOPT) { 4518 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4519 + ": " + pkg.packageName); 4520 } 4521 if (!isFirstBoot()) { 4522 try { 4523 ActivityManagerNative.getDefault().showBootMessage( 4524 mContext.getResources().getString( 4525 R.string.android_upgrading_apk, 4526 i, pkgs.size()), true); 4527 } catch (RemoteException e) { 4528 } 4529 } 4530 PackageParser.Package p = pkg; 4531 synchronized (mInstallLock) { 4532 performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */, 4533 true /* include dependencies */); 4534 } 4535 } 4536 } 4537 } 4538 4539 @Override 4540 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4541 return performDexOpt(packageName, instructionSet, true); 4542 } 4543 4544 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4545 if (info.primaryCpuAbi == null) { 4546 return getPreferredInstructionSet(); 4547 } 4548 4549 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4550 } 4551 4552 public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) { 4553 PackageParser.Package p; 4554 final String targetInstructionSet; 4555 synchronized (mPackages) { 4556 p = mPackages.get(packageName); 4557 if (p == null) { 4558 return false; 4559 } 4560 if (updateUsage) { 4561 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4562 } 4563 mPackageUsage.write(false); 4564 4565 targetInstructionSet = instructionSet != null ? instructionSet : 4566 getPrimaryInstructionSet(p.applicationInfo); 4567 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4568 return false; 4569 } 4570 } 4571 4572 synchronized (mInstallLock) { 4573 final String[] instructionSets = new String[] { targetInstructionSet }; 4574 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4575 true /* include dependencies */) == DEX_OPT_PERFORMED; 4576 } 4577 } 4578 4579 public HashSet<String> getPackagesThatNeedDexOpt() { 4580 HashSet<String> pkgs = null; 4581 synchronized (mPackages) { 4582 for (PackageParser.Package p : mPackages.values()) { 4583 if (DEBUG_DEXOPT) { 4584 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4585 } 4586 if (!p.mDexOptPerformed.isEmpty()) { 4587 continue; 4588 } 4589 if (pkgs == null) { 4590 pkgs = new HashSet<String>(); 4591 } 4592 pkgs.add(p.packageName); 4593 } 4594 } 4595 return pkgs; 4596 } 4597 4598 public void shutdown() { 4599 mPackageUsage.write(true); 4600 } 4601 4602 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4603 boolean forceDex, boolean defer, HashSet<String> done) { 4604 for (int i=0; i<libs.size(); i++) { 4605 PackageParser.Package libPkg; 4606 String libName; 4607 synchronized (mPackages) { 4608 libName = libs.get(i); 4609 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4610 if (lib != null && lib.apk != null) { 4611 libPkg = mPackages.get(lib.apk); 4612 } else { 4613 libPkg = null; 4614 } 4615 } 4616 if (libPkg != null && !done.contains(libName)) { 4617 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4618 } 4619 } 4620 } 4621 4622 static final int DEX_OPT_SKIPPED = 0; 4623 static final int DEX_OPT_PERFORMED = 1; 4624 static final int DEX_OPT_DEFERRED = 2; 4625 static final int DEX_OPT_FAILED = -1; 4626 4627 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4628 boolean forceDex, boolean defer, HashSet<String> done) { 4629 final String[] instructionSets = targetInstructionSets != null ? 4630 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4631 4632 if (done != null) { 4633 done.add(pkg.packageName); 4634 if (pkg.usesLibraries != null) { 4635 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4636 } 4637 if (pkg.usesOptionalLibraries != null) { 4638 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4639 } 4640 } 4641 4642 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4643 return DEX_OPT_SKIPPED; 4644 } 4645 4646 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4647 boolean performedDexOpt = false; 4648 // There are three basic cases here: 4649 // 1.) we need to dexopt, either because we are forced or it is needed 4650 // 2.) we are defering a needed dexopt 4651 // 3.) we are skipping an unneeded dexopt 4652 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4653 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4654 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4655 continue; 4656 } 4657 4658 for (String path : paths) { 4659 try { 4660 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4661 // patckage or the one we find does not match the image checksum (i.e. it was 4662 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4663 // odex file and it matches the checksum of the image but not its base address, 4664 // meaning we need to move it. 4665 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4666 pkg.packageName, dexCodeInstructionSet, defer); 4667 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4668 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4669 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet); 4670 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4671 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4672 pkg.packageName, dexCodeInstructionSet); 4673 4674 if (ret < 0) { 4675 // Don't bother running dexopt again if we failed, it will probably 4676 // just result in an error again. Also, don't bother dexopting for other 4677 // paths & ISAs. 4678 return DEX_OPT_FAILED; 4679 } 4680 4681 performedDexOpt = true; 4682 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4683 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4684 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4685 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4686 pkg.packageName, dexCodeInstructionSet); 4687 4688 if (ret < 0) { 4689 // Don't bother running patchoat again if we failed, it will probably 4690 // just result in an error again. Also, don't bother dexopting for other 4691 // paths & ISAs. 4692 return DEX_OPT_FAILED; 4693 } 4694 4695 performedDexOpt = true; 4696 } 4697 4698 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4699 // paths and instruction sets. We'll deal with them all together when we process 4700 // our list of deferred dexopts. 4701 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4702 if (mDeferredDexOpt == null) { 4703 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4704 } 4705 mDeferredDexOpt.add(pkg); 4706 return DEX_OPT_DEFERRED; 4707 } 4708 } catch (FileNotFoundException e) { 4709 Slog.w(TAG, "Apk not found for dexopt: " + path); 4710 return DEX_OPT_FAILED; 4711 } catch (IOException e) { 4712 Slog.w(TAG, "IOException reading apk: " + path, e); 4713 return DEX_OPT_FAILED; 4714 } catch (StaleDexCacheError e) { 4715 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4716 return DEX_OPT_FAILED; 4717 } catch (Exception e) { 4718 Slog.w(TAG, "Exception when doing dexopt : ", e); 4719 return DEX_OPT_FAILED; 4720 } 4721 } 4722 4723 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4724 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4725 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4726 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4727 // it. 4728 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4729 } 4730 4731 // If we've gotten here, we're sure that no error occurred and that we haven't 4732 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4733 // we've skipped all of them because they are up to date. In both cases this 4734 // package doesn't need dexopt any longer. 4735 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4736 } 4737 4738 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4739 if (info.primaryCpuAbi != null) { 4740 if (info.secondaryCpuAbi != null) { 4741 return new String[] { 4742 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4743 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4744 } else { 4745 return new String[] { 4746 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4747 } 4748 } 4749 4750 return new String[] { getPreferredInstructionSet() }; 4751 } 4752 4753 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4754 if (ps.primaryCpuAbiString != null) { 4755 if (ps.secondaryCpuAbiString != null) { 4756 return new String[] { 4757 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4758 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4759 } else { 4760 return new String[] { 4761 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4762 } 4763 } 4764 4765 return new String[] { getPreferredInstructionSet() }; 4766 } 4767 4768 private static String getPreferredInstructionSet() { 4769 if (sPreferredInstructionSet == null) { 4770 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4771 } 4772 4773 return sPreferredInstructionSet; 4774 } 4775 4776 private static List<String> getAllInstructionSets() { 4777 final String[] allAbis = Build.SUPPORTED_ABIS; 4778 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4779 4780 for (String abi : allAbis) { 4781 final String instructionSet = VMRuntime.getInstructionSet(abi); 4782 if (!allInstructionSets.contains(instructionSet)) { 4783 allInstructionSets.add(instructionSet); 4784 } 4785 } 4786 4787 return allInstructionSets; 4788 } 4789 4790 /** 4791 * Returns the instruction set that should be used to compile dex code. In the presence of 4792 * a native bridge this might be different than the one shared libraries use. 4793 */ 4794 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4795 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4796 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4797 } 4798 4799 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4800 HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length); 4801 for (String instructionSet : instructionSets) { 4802 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4803 } 4804 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4805 } 4806 4807 @Override 4808 public void forceDexOpt(String packageName) { 4809 enforceSystemOrRoot("forceDexOpt"); 4810 4811 PackageParser.Package pkg; 4812 synchronized (mPackages) { 4813 pkg = mPackages.get(packageName); 4814 if (pkg == null) { 4815 throw new IllegalArgumentException("Missing package: " + packageName); 4816 } 4817 } 4818 4819 synchronized (mInstallLock) { 4820 final String[] instructionSets = new String[] { 4821 getPrimaryInstructionSet(pkg.applicationInfo) }; 4822 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4823 if (res != DEX_OPT_PERFORMED) { 4824 throw new IllegalStateException("Failed to dexopt: " + res); 4825 } 4826 } 4827 } 4828 4829 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4830 boolean forceDex, boolean defer, boolean inclDependencies) { 4831 HashSet<String> done; 4832 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4833 done = new HashSet<String>(); 4834 done.add(pkg.packageName); 4835 } else { 4836 done = null; 4837 } 4838 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4839 } 4840 4841 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4842 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4843 Slog.w(TAG, "Unable to update from " + oldPkg.name 4844 + " to " + newPkg.packageName 4845 + ": old package not in system partition"); 4846 return false; 4847 } else if (mPackages.get(oldPkg.name) != null) { 4848 Slog.w(TAG, "Unable to update from " + oldPkg.name 4849 + " to " + newPkg.packageName 4850 + ": old package still exists"); 4851 return false; 4852 } 4853 return true; 4854 } 4855 4856 File getDataPathForUser(int userId) { 4857 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4858 } 4859 4860 private File getDataPathForPackage(String packageName, int userId) { 4861 /* 4862 * Until we fully support multiple users, return the directory we 4863 * previously would have. The PackageManagerTests will need to be 4864 * revised when this is changed back.. 4865 */ 4866 if (userId == 0) { 4867 return new File(mAppDataDir, packageName); 4868 } else { 4869 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4870 + File.separator + packageName); 4871 } 4872 } 4873 4874 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4875 int[] users = sUserManager.getUserIds(); 4876 int res = mInstaller.install(packageName, uid, uid, seinfo); 4877 if (res < 0) { 4878 return res; 4879 } 4880 for (int user : users) { 4881 if (user != 0) { 4882 res = mInstaller.createUserData(packageName, 4883 UserHandle.getUid(user, uid), user, seinfo); 4884 if (res < 0) { 4885 return res; 4886 } 4887 } 4888 } 4889 return res; 4890 } 4891 4892 private int removeDataDirsLI(String packageName) { 4893 int[] users = sUserManager.getUserIds(); 4894 int res = 0; 4895 for (int user : users) { 4896 int resInner = mInstaller.remove(packageName, user); 4897 if (resInner < 0) { 4898 res = resInner; 4899 } 4900 } 4901 4902 return res; 4903 } 4904 4905 private int deleteCodeCacheDirsLI(String packageName) { 4906 int[] users = sUserManager.getUserIds(); 4907 int res = 0; 4908 for (int user : users) { 4909 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4910 if (resInner < 0) { 4911 res = resInner; 4912 } 4913 } 4914 return res; 4915 } 4916 4917 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4918 PackageParser.Package changingLib) { 4919 if (file.path != null) { 4920 usesLibraryFiles.add(file.path); 4921 return; 4922 } 4923 PackageParser.Package p = mPackages.get(file.apk); 4924 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4925 // If we are doing this while in the middle of updating a library apk, 4926 // then we need to make sure to use that new apk for determining the 4927 // dependencies here. (We haven't yet finished committing the new apk 4928 // to the package manager state.) 4929 if (p == null || p.packageName.equals(changingLib.packageName)) { 4930 p = changingLib; 4931 } 4932 } 4933 if (p != null) { 4934 usesLibraryFiles.addAll(p.getAllCodePaths()); 4935 } 4936 } 4937 4938 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4939 PackageParser.Package changingLib) throws PackageManagerException { 4940 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4941 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4942 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4943 for (int i=0; i<N; i++) { 4944 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4945 if (file == null) { 4946 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4947 "Package " + pkg.packageName + " requires unavailable shared library " 4948 + pkg.usesLibraries.get(i) + "; failing!"); 4949 } 4950 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4951 } 4952 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4953 for (int i=0; i<N; i++) { 4954 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4955 if (file == null) { 4956 Slog.w(TAG, "Package " + pkg.packageName 4957 + " desires unavailable shared library " 4958 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4959 } else { 4960 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4961 } 4962 } 4963 N = usesLibraryFiles.size(); 4964 if (N > 0) { 4965 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4966 } else { 4967 pkg.usesLibraryFiles = null; 4968 } 4969 } 4970 } 4971 4972 private static boolean hasString(List<String> list, List<String> which) { 4973 if (list == null) { 4974 return false; 4975 } 4976 for (int i=list.size()-1; i>=0; i--) { 4977 for (int j=which.size()-1; j>=0; j--) { 4978 if (which.get(j).equals(list.get(i))) { 4979 return true; 4980 } 4981 } 4982 } 4983 return false; 4984 } 4985 4986 private void updateAllSharedLibrariesLPw() { 4987 for (PackageParser.Package pkg : mPackages.values()) { 4988 try { 4989 updateSharedLibrariesLPw(pkg, null); 4990 } catch (PackageManagerException e) { 4991 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4992 } 4993 } 4994 } 4995 4996 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4997 PackageParser.Package changingPkg) { 4998 ArrayList<PackageParser.Package> res = null; 4999 for (PackageParser.Package pkg : mPackages.values()) { 5000 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5001 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5002 if (res == null) { 5003 res = new ArrayList<PackageParser.Package>(); 5004 } 5005 res.add(pkg); 5006 try { 5007 updateSharedLibrariesLPw(pkg, changingPkg); 5008 } catch (PackageManagerException e) { 5009 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5010 } 5011 } 5012 } 5013 return res; 5014 } 5015 5016 /** 5017 * Derive the value of the {@code cpuAbiOverride} based on the provided 5018 * value and an optional stored value from the package settings. 5019 */ 5020 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5021 String cpuAbiOverride = null; 5022 5023 if (CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5024 cpuAbiOverride = null; 5025 } else if (abiOverride != null) { 5026 cpuAbiOverride = abiOverride; 5027 } else if (settings != null) { 5028 cpuAbiOverride = settings.cpuAbiOverrideString; 5029 } 5030 5031 return cpuAbiOverride; 5032 } 5033 5034 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5035 int scanMode, long currentTime, UserHandle user) 5036 throws PackageManagerException { 5037 final File scanFile = new File(pkg.codePath); 5038 if (pkg.applicationInfo.getCodePath() == null || 5039 pkg.applicationInfo.getResourcePath() == null) { 5040 // Bail out. The resource and code paths haven't been set. 5041 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5042 "Code and resource paths haven't been set correctly"); 5043 } 5044 5045 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5046 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5047 } 5048 5049 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5050 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5051 } 5052 5053 if (mCustomResolverComponentName != null && 5054 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5055 setUpCustomResolverActivity(pkg); 5056 } 5057 5058 if (pkg.packageName.equals("android")) { 5059 synchronized (mPackages) { 5060 if (mAndroidApplication != null) { 5061 Slog.w(TAG, "*************************************************"); 5062 Slog.w(TAG, "Core android package being redefined. Skipping."); 5063 Slog.w(TAG, " file=" + scanFile); 5064 Slog.w(TAG, "*************************************************"); 5065 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5066 "Core android package being redefined. Skipping."); 5067 } 5068 5069 // Set up information for our fall-back user intent resolution activity. 5070 mPlatformPackage = pkg; 5071 pkg.mVersionCode = mSdkVersion; 5072 mAndroidApplication = pkg.applicationInfo; 5073 5074 if (!mResolverReplaced) { 5075 mResolveActivity.applicationInfo = mAndroidApplication; 5076 mResolveActivity.name = ResolverActivity.class.getName(); 5077 mResolveActivity.packageName = mAndroidApplication.packageName; 5078 mResolveActivity.processName = "system:ui"; 5079 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5080 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5081 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5082 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5083 mResolveActivity.exported = true; 5084 mResolveActivity.enabled = true; 5085 mResolveInfo.activityInfo = mResolveActivity; 5086 mResolveInfo.priority = 0; 5087 mResolveInfo.preferredOrder = 0; 5088 mResolveInfo.match = 0; 5089 mResolveComponentName = new ComponentName( 5090 mAndroidApplication.packageName, mResolveActivity.name); 5091 } 5092 } 5093 } 5094 5095 if (DEBUG_PACKAGE_SCANNING) { 5096 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5097 Log.d(TAG, "Scanning package " + pkg.packageName); 5098 } 5099 5100 if (mPackages.containsKey(pkg.packageName) 5101 || mSharedLibraries.containsKey(pkg.packageName)) { 5102 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5103 "Application package " + pkg.packageName 5104 + " already installed. Skipping duplicate."); 5105 } 5106 5107 // Initialize package source and resource directories 5108 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5109 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5110 5111 SharedUserSetting suid = null; 5112 PackageSetting pkgSetting = null; 5113 5114 if (!isSystemApp(pkg)) { 5115 // Only system apps can use these features. 5116 pkg.mOriginalPackages = null; 5117 pkg.mRealPackage = null; 5118 pkg.mAdoptPermissions = null; 5119 } 5120 5121 // writer 5122 synchronized (mPackages) { 5123 if (pkg.mSharedUserId != null) { 5124 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5125 if (suid == null) { 5126 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5127 "Creating application package " + pkg.packageName 5128 + " for shared user failed"); 5129 } 5130 if (DEBUG_PACKAGE_SCANNING) { 5131 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5132 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5133 + "): packages=" + suid.packages); 5134 } 5135 } 5136 5137 // Check if we are renaming from an original package name. 5138 PackageSetting origPackage = null; 5139 String realName = null; 5140 if (pkg.mOriginalPackages != null) { 5141 // This package may need to be renamed to a previously 5142 // installed name. Let's check on that... 5143 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5144 if (pkg.mOriginalPackages.contains(renamed)) { 5145 // This package had originally been installed as the 5146 // original name, and we have already taken care of 5147 // transitioning to the new one. Just update the new 5148 // one to continue using the old name. 5149 realName = pkg.mRealPackage; 5150 if (!pkg.packageName.equals(renamed)) { 5151 // Callers into this function may have already taken 5152 // care of renaming the package; only do it here if 5153 // it is not already done. 5154 pkg.setPackageName(renamed); 5155 } 5156 5157 } else { 5158 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5159 if ((origPackage = mSettings.peekPackageLPr( 5160 pkg.mOriginalPackages.get(i))) != null) { 5161 // We do have the package already installed under its 5162 // original name... should we use it? 5163 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5164 // New package is not compatible with original. 5165 origPackage = null; 5166 continue; 5167 } else if (origPackage.sharedUser != null) { 5168 // Make sure uid is compatible between packages. 5169 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5170 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5171 + " to " + pkg.packageName + ": old uid " 5172 + origPackage.sharedUser.name 5173 + " differs from " + pkg.mSharedUserId); 5174 origPackage = null; 5175 continue; 5176 } 5177 } else { 5178 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5179 + pkg.packageName + " to old name " + origPackage.name); 5180 } 5181 break; 5182 } 5183 } 5184 } 5185 } 5186 5187 if (mTransferedPackages.contains(pkg.packageName)) { 5188 Slog.w(TAG, "Package " + pkg.packageName 5189 + " was transferred to another, but its .apk remains"); 5190 } 5191 5192 // Just create the setting, don't add it yet. For already existing packages 5193 // the PkgSetting exists already and doesn't have to be created. 5194 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5195 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5196 pkg.applicationInfo.primaryCpuAbi, 5197 pkg.applicationInfo.secondaryCpuAbi, 5198 pkg.applicationInfo.flags, user, false); 5199 if (pkgSetting == null) { 5200 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5201 "Creating application package " + pkg.packageName + " failed"); 5202 } 5203 5204 if (pkgSetting.origPackage != null) { 5205 // If we are first transitioning from an original package, 5206 // fix up the new package's name now. We need to do this after 5207 // looking up the package under its new name, so getPackageLP 5208 // can take care of fiddling things correctly. 5209 pkg.setPackageName(origPackage.name); 5210 5211 // File a report about this. 5212 String msg = "New package " + pkgSetting.realName 5213 + " renamed to replace old package " + pkgSetting.name; 5214 reportSettingsProblem(Log.WARN, msg); 5215 5216 // Make a note of it. 5217 mTransferedPackages.add(origPackage.name); 5218 5219 // No longer need to retain this. 5220 pkgSetting.origPackage = null; 5221 } 5222 5223 if (realName != null) { 5224 // Make a note of it. 5225 mTransferedPackages.add(pkg.packageName); 5226 } 5227 5228 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5229 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5230 } 5231 5232 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5233 // Check all shared libraries and map to their actual file path. 5234 // We only do this here for apps not on a system dir, because those 5235 // are the only ones that can fail an install due to this. We 5236 // will take care of the system apps by updating all of their 5237 // library paths after the scan is done. 5238 updateSharedLibrariesLPw(pkg, null); 5239 } 5240 5241 if (mFoundPolicyFile) { 5242 SELinuxMMAC.assignSeinfoValue(pkg); 5243 } 5244 5245 pkg.applicationInfo.uid = pkgSetting.appId; 5246 pkg.mExtras = pkgSetting; 5247 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5248 try { 5249 verifySignaturesLP(pkgSetting, pkg); 5250 } catch (PackageManagerException e) { 5251 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5252 throw e; 5253 } 5254 // The signature has changed, but this package is in the system 5255 // image... let's recover! 5256 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5257 // However... if this package is part of a shared user, but it 5258 // doesn't match the signature of the shared user, let's fail. 5259 // What this means is that you can't change the signatures 5260 // associated with an overall shared user, which doesn't seem all 5261 // that unreasonable. 5262 if (pkgSetting.sharedUser != null) { 5263 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5264 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5265 throw new PackageManagerException( 5266 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5267 "Signature mismatch for shared user : " 5268 + pkgSetting.sharedUser); 5269 } 5270 } 5271 // File a report about this. 5272 String msg = "System package " + pkg.packageName 5273 + " signature changed; retaining data."; 5274 reportSettingsProblem(Log.WARN, msg); 5275 } 5276 } else { 5277 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5278 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5279 + pkg.packageName + " upgrade keys do not match the " 5280 + "previously installed version"); 5281 } else { 5282 // signatures may have changed as result of upgrade 5283 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5284 } 5285 } 5286 // Verify that this new package doesn't have any content providers 5287 // that conflict with existing packages. Only do this if the 5288 // package isn't already installed, since we don't want to break 5289 // things that are installed. 5290 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5291 final int N = pkg.providers.size(); 5292 int i; 5293 for (i=0; i<N; i++) { 5294 PackageParser.Provider p = pkg.providers.get(i); 5295 if (p.info.authority != null) { 5296 String names[] = p.info.authority.split(";"); 5297 for (int j = 0; j < names.length; j++) { 5298 if (mProvidersByAuthority.containsKey(names[j])) { 5299 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5300 final String otherPackageName = 5301 ((other != null && other.getComponentName() != null) ? 5302 other.getComponentName().getPackageName() : "?"); 5303 throw new PackageManagerException( 5304 INSTALL_FAILED_CONFLICTING_PROVIDER, 5305 "Can't install because provider name " + names[j] 5306 + " (in package " + pkg.applicationInfo.packageName 5307 + ") is already used by " + otherPackageName); 5308 } 5309 } 5310 } 5311 } 5312 } 5313 5314 if (pkg.mAdoptPermissions != null) { 5315 // This package wants to adopt ownership of permissions from 5316 // another package. 5317 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5318 final String origName = pkg.mAdoptPermissions.get(i); 5319 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5320 if (orig != null) { 5321 if (verifyPackageUpdateLPr(orig, pkg)) { 5322 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5323 + pkg.packageName); 5324 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5325 } 5326 } 5327 } 5328 } 5329 } 5330 5331 final String pkgName = pkg.packageName; 5332 5333 final long scanFileTime = scanFile.lastModified(); 5334 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5335 pkg.applicationInfo.processName = fixProcessName( 5336 pkg.applicationInfo.packageName, 5337 pkg.applicationInfo.processName, 5338 pkg.applicationInfo.uid); 5339 5340 File dataPath; 5341 if (mPlatformPackage == pkg) { 5342 // The system package is special. 5343 dataPath = new File (Environment.getDataDirectory(), "system"); 5344 pkg.applicationInfo.dataDir = dataPath.getPath(); 5345 5346 } else { 5347 // This is a normal package, need to make its data directory. 5348 dataPath = getDataPathForPackage(pkg.packageName, 0); 5349 5350 boolean uidError = false; 5351 5352 if (dataPath.exists()) { 5353 int currentUid = 0; 5354 try { 5355 StructStat stat = Os.stat(dataPath.getPath()); 5356 currentUid = stat.st_uid; 5357 } catch (ErrnoException e) { 5358 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5359 } 5360 5361 // If we have mismatched owners for the data path, we have a problem. 5362 if (currentUid != pkg.applicationInfo.uid) { 5363 boolean recovered = false; 5364 if (currentUid == 0) { 5365 // The directory somehow became owned by root. Wow. 5366 // This is probably because the system was stopped while 5367 // installd was in the middle of messing with its libs 5368 // directory. Ask installd to fix that. 5369 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5370 pkg.applicationInfo.uid); 5371 if (ret >= 0) { 5372 recovered = true; 5373 String msg = "Package " + pkg.packageName 5374 + " unexpectedly changed to uid 0; recovered to " + 5375 + pkg.applicationInfo.uid; 5376 reportSettingsProblem(Log.WARN, msg); 5377 } 5378 } 5379 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5380 || (scanMode&SCAN_BOOTING) != 0)) { 5381 // If this is a system app, we can at least delete its 5382 // current data so the application will still work. 5383 int ret = removeDataDirsLI(pkgName); 5384 if (ret >= 0) { 5385 // TODO: Kill the processes first 5386 // Old data gone! 5387 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5388 ? "System package " : "Third party package "; 5389 String msg = prefix + pkg.packageName 5390 + " has changed from uid: " 5391 + currentUid + " to " 5392 + pkg.applicationInfo.uid + "; old data erased"; 5393 reportSettingsProblem(Log.WARN, msg); 5394 recovered = true; 5395 5396 // And now re-install the app. 5397 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5398 pkg.applicationInfo.seinfo); 5399 if (ret == -1) { 5400 // Ack should not happen! 5401 msg = prefix + pkg.packageName 5402 + " could not have data directory re-created after delete."; 5403 reportSettingsProblem(Log.WARN, msg); 5404 throw new PackageManagerException( 5405 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5406 } 5407 } 5408 if (!recovered) { 5409 mHasSystemUidErrors = true; 5410 } 5411 } else if (!recovered) { 5412 // If we allow this install to proceed, we will be broken. 5413 // Abort, abort! 5414 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5415 "scanPackageLI"); 5416 } 5417 if (!recovered) { 5418 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5419 + pkg.applicationInfo.uid + "/fs_" 5420 + currentUid; 5421 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5422 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5423 String msg = "Package " + pkg.packageName 5424 + " has mismatched uid: " 5425 + currentUid + " on disk, " 5426 + pkg.applicationInfo.uid + " in settings"; 5427 // writer 5428 synchronized (mPackages) { 5429 mSettings.mReadMessages.append(msg); 5430 mSettings.mReadMessages.append('\n'); 5431 uidError = true; 5432 if (!pkgSetting.uidError) { 5433 reportSettingsProblem(Log.ERROR, msg); 5434 } 5435 } 5436 } 5437 } 5438 pkg.applicationInfo.dataDir = dataPath.getPath(); 5439 if (mShouldRestoreconData) { 5440 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5441 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5442 pkg.applicationInfo.uid); 5443 } 5444 } else { 5445 if (DEBUG_PACKAGE_SCANNING) { 5446 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5447 Log.v(TAG, "Want this data dir: " + dataPath); 5448 } 5449 //invoke installer to do the actual installation 5450 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5451 pkg.applicationInfo.seinfo); 5452 if (ret < 0) { 5453 // Error from installer 5454 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5455 "Unable to create data dirs [errorCode=" + ret + "]"); 5456 } 5457 5458 if (dataPath.exists()) { 5459 pkg.applicationInfo.dataDir = dataPath.getPath(); 5460 } else { 5461 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5462 pkg.applicationInfo.dataDir = null; 5463 } 5464 } 5465 5466 pkgSetting.uidError = uidError; 5467 } 5468 5469 final String path = scanFile.getPath(); 5470 final String codePath = pkg.applicationInfo.getCodePath(); 5471 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5472 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5473 setBundledAppAbisAndRoots(pkg, pkgSetting); 5474 5475 // If we haven't found any native libraries for the app, check if it has 5476 // renderscript code. We'll need to force the app to 32 bit if it has 5477 // renderscript bitcode. 5478 if (pkg.applicationInfo.primaryCpuAbi == null 5479 && pkg.applicationInfo.secondaryCpuAbi == null 5480 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5481 NativeLibraryHelper.Handle handle = null; 5482 try { 5483 handle = NativeLibraryHelper.Handle.create(scanFile); 5484 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5485 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5486 } 5487 } catch (IOException ioe) { 5488 Slog.w(TAG, "Error scanning system app : " + ioe); 5489 } finally { 5490 IoUtils.closeQuietly(handle); 5491 } 5492 } 5493 5494 setNativeLibraryPaths(pkg); 5495 } else { 5496 // TODO: We can probably be smarter about this stuff. For installed apps, 5497 // we can calculate this information at install time once and for all. For 5498 // system apps, we can probably assume that this information doesn't change 5499 // after the first boot scan. As things stand, we do lots of unnecessary work. 5500 5501 // Give ourselves some initial paths; we'll come back for another 5502 // pass once we've determined ABI below. 5503 setNativeLibraryPaths(pkg); 5504 5505 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5506 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5507 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5508 5509 NativeLibraryHelper.Handle handle = null; 5510 try { 5511 handle = NativeLibraryHelper.Handle.create(scanFile); 5512 // TODO(multiArch): This can be null for apps that didn't go through the 5513 // usual installation process. We can calculate it again, like we 5514 // do during install time. 5515 // 5516 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5517 // unnecessary. 5518 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5519 5520 // Null out the abis so that they can be recalculated. 5521 pkg.applicationInfo.primaryCpuAbi = null; 5522 pkg.applicationInfo.secondaryCpuAbi = null; 5523 if (isMultiArch(pkg.applicationInfo)) { 5524 // Warn if we've set an abiOverride for multi-lib packages.. 5525 // By definition, we need to copy both 32 and 64 bit libraries for 5526 // such packages. 5527 if (pkg.cpuAbiOverride != null && !CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5528 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5529 } 5530 5531 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5532 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5533 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5534 if (isAsec) { 5535 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5536 } else { 5537 abi32 = copyNativeLibrariesForInternalApp(handle, 5538 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs); 5539 } 5540 } 5541 5542 maybeThrowExceptionForMultiArchCopy( 5543 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5544 5545 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5546 if (isAsec) { 5547 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5548 } else { 5549 abi64 = copyNativeLibrariesForInternalApp(handle, 5550 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs); 5551 } 5552 } 5553 5554 maybeThrowExceptionForMultiArchCopy( 5555 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5556 5557 if (abi64 >= 0) { 5558 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5559 } 5560 5561 if (abi32 >= 0) { 5562 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5563 if (abi64 >= 0) { 5564 pkg.applicationInfo.secondaryCpuAbi = abi; 5565 } else { 5566 pkg.applicationInfo.primaryCpuAbi = abi; 5567 } 5568 } 5569 } else { 5570 String[] abiList = (cpuAbiOverride != null) ? 5571 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5572 5573 // Enable gross and lame hacks for apps that are built with old 5574 // SDK tools. We must scan their APKs for renderscript bitcode and 5575 // not launch them if it's present. Don't bother checking on devices 5576 // that don't have 64 bit support. 5577 boolean needsRenderScriptOverride = false; 5578 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5579 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5580 abiList = Build.SUPPORTED_32_BIT_ABIS; 5581 needsRenderScriptOverride = true; 5582 } 5583 5584 final int copyRet; 5585 if (isAsec) { 5586 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5587 } else { 5588 copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryRoot, abiList, 5589 useIsaSpecificSubdirs); 5590 } 5591 5592 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5593 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5594 "Error unpackaging native libs for app, errorCode=" + copyRet); 5595 } 5596 5597 if (copyRet >= 0) { 5598 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5599 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5600 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5601 } else if (needsRenderScriptOverride) { 5602 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5603 } 5604 } 5605 } catch (IOException ioe) { 5606 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5607 } finally { 5608 IoUtils.closeQuietly(handle); 5609 } 5610 5611 // Now that we've calculated the ABIs and determined if it's an internal app, 5612 // we will go ahead and populate the nativeLibraryPath. 5613 setNativeLibraryPaths(pkg); 5614 5615 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5616 final int[] userIds = sUserManager.getUserIds(); 5617 synchronized (mInstallLock) { 5618 // Create a native library symlink only if we have native libraries 5619 // and if the native libraries are 32 bit libraries. We do not provide 5620 // this symlink for 64 bit libraries. 5621 if (pkg.applicationInfo.primaryCpuAbi != null && 5622 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5623 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5624 for (int userId : userIds) { 5625 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5626 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5627 "Failed linking native library dir (user=" + userId + ")"); 5628 } 5629 } 5630 } 5631 } 5632 } 5633 5634 // This is a special case for the "system" package, where the ABI is 5635 // dictated by the zygote configuration (and init.rc). We should keep track 5636 // of this ABI so that we can deal with "normal" applications that run under 5637 // the same UID correctly. 5638 if (mPlatformPackage == pkg) { 5639 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5640 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5641 } 5642 5643 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5644 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5645 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5646 // Copy the derived override back to the parsed package, so that we can 5647 // update the package settings accordingly. 5648 pkg.cpuAbiOverride = cpuAbiOverride; 5649 5650 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5651 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5652 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5653 5654 // Push the derived path down into PackageSettings so we know what to 5655 // clean up at uninstall time. 5656 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5657 5658 if (DEBUG_ABI_SELECTION) { 5659 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5660 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5661 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5662 } 5663 5664 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5665 // We don't do this here during boot because we can do it all 5666 // at once after scanning all existing packages. 5667 // 5668 // We also do this *before* we perform dexopt on this package, so that 5669 // we can avoid redundant dexopts, and also to make sure we've got the 5670 // code and package path correct. 5671 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5672 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0); 5673 } 5674 5675 if ((scanMode&SCAN_NO_DEX) == 0) { 5676 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5677 == DEX_OPT_FAILED) { 5678 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5679 removeDataDirsLI(pkg.packageName); 5680 } 5681 5682 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5683 } 5684 } 5685 5686 if (mFactoryTest && pkg.requestedPermissions.contains( 5687 android.Manifest.permission.FACTORY_TEST)) { 5688 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5689 } 5690 5691 ArrayList<PackageParser.Package> clientLibPkgs = null; 5692 5693 // writer 5694 synchronized (mPackages) { 5695 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5696 // Only system apps can add new shared libraries. 5697 if (pkg.libraryNames != null) { 5698 for (int i=0; i<pkg.libraryNames.size(); i++) { 5699 String name = pkg.libraryNames.get(i); 5700 boolean allowed = false; 5701 if (isUpdatedSystemApp(pkg)) { 5702 // New library entries can only be added through the 5703 // system image. This is important to get rid of a lot 5704 // of nasty edge cases: for example if we allowed a non- 5705 // system update of the app to add a library, then uninstalling 5706 // the update would make the library go away, and assumptions 5707 // we made such as through app install filtering would now 5708 // have allowed apps on the device which aren't compatible 5709 // with it. Better to just have the restriction here, be 5710 // conservative, and create many fewer cases that can negatively 5711 // impact the user experience. 5712 final PackageSetting sysPs = mSettings 5713 .getDisabledSystemPkgLPr(pkg.packageName); 5714 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5715 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5716 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5717 allowed = true; 5718 allowed = true; 5719 break; 5720 } 5721 } 5722 } 5723 } else { 5724 allowed = true; 5725 } 5726 if (allowed) { 5727 if (!mSharedLibraries.containsKey(name)) { 5728 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5729 } else if (!name.equals(pkg.packageName)) { 5730 Slog.w(TAG, "Package " + pkg.packageName + " library " 5731 + name + " already exists; skipping"); 5732 } 5733 } else { 5734 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5735 + name + " that is not declared on system image; skipping"); 5736 } 5737 } 5738 if ((scanMode&SCAN_BOOTING) == 0) { 5739 // If we are not booting, we need to update any applications 5740 // that are clients of our shared library. If we are booting, 5741 // this will all be done once the scan is complete. 5742 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5743 } 5744 } 5745 } 5746 } 5747 5748 // We also need to dexopt any apps that are dependent on this library. Note that 5749 // if these fail, we should abort the install since installing the library will 5750 // result in some apps being broken. 5751 if (clientLibPkgs != null) { 5752 if ((scanMode&SCAN_NO_DEX) == 0) { 5753 for (int i=0; i<clientLibPkgs.size(); i++) { 5754 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5755 if (performDexOptLI(clientPkg, null /* instruction sets */, 5756 forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5757 == DEX_OPT_FAILED) { 5758 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5759 removeDataDirsLI(pkg.packageName); 5760 } 5761 5762 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5763 "scanPackageLI failed to dexopt clientLibPkgs"); 5764 } 5765 } 5766 } 5767 } 5768 5769 // Request the ActivityManager to kill the process(only for existing packages) 5770 // so that we do not end up in a confused state while the user is still using the older 5771 // version of the application while the new one gets installed. 5772 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5773 // If the package lives in an asec, tell everyone that the container is going 5774 // away so they can clean up any references to its resources (which would prevent 5775 // vold from being able to unmount the asec) 5776 if (isForwardLocked(pkg) || isExternal(pkg)) { 5777 if (DEBUG_INSTALL) { 5778 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5779 } 5780 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5781 final ArrayList<String> pkgList = new ArrayList<String>(1); 5782 pkgList.add(pkg.applicationInfo.packageName); 5783 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5784 } 5785 5786 // Post the request that it be killed now that the going-away broadcast is en route 5787 killApplication(pkg.applicationInfo.packageName, 5788 pkg.applicationInfo.uid, "update pkg"); 5789 } 5790 5791 // Also need to kill any apps that are dependent on the library. 5792 if (clientLibPkgs != null) { 5793 for (int i=0; i<clientLibPkgs.size(); i++) { 5794 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5795 killApplication(clientPkg.applicationInfo.packageName, 5796 clientPkg.applicationInfo.uid, "update lib"); 5797 } 5798 } 5799 5800 // writer 5801 synchronized (mPackages) { 5802 // We don't expect installation to fail beyond this point, 5803 if ((scanMode&SCAN_MONITOR) != 0) { 5804 mAppDirs.put(pkg.codePath, pkg); 5805 } 5806 // Add the new setting to mSettings 5807 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5808 // Add the new setting to mPackages 5809 mPackages.put(pkg.applicationInfo.packageName, pkg); 5810 // Make sure we don't accidentally delete its data. 5811 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5812 while (iter.hasNext()) { 5813 PackageCleanItem item = iter.next(); 5814 if (pkgName.equals(item.packageName)) { 5815 iter.remove(); 5816 } 5817 } 5818 5819 // Take care of first install / last update times. 5820 if (currentTime != 0) { 5821 if (pkgSetting.firstInstallTime == 0) { 5822 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5823 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5824 pkgSetting.lastUpdateTime = currentTime; 5825 } 5826 } else if (pkgSetting.firstInstallTime == 0) { 5827 // We need *something*. Take time time stamp of the file. 5828 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5829 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5830 if (scanFileTime != pkgSetting.timeStamp) { 5831 // A package on the system image has changed; consider this 5832 // to be an update. 5833 pkgSetting.lastUpdateTime = scanFileTime; 5834 } 5835 } 5836 5837 // Add the package's KeySets to the global KeySetManagerService 5838 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5839 try { 5840 // Old KeySetData no longer valid. 5841 ksms.removeAppKeySetDataLPw(pkg.packageName); 5842 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5843 if (pkg.mKeySetMapping != null) { 5844 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5845 pkg.mKeySetMapping.entrySet()) { 5846 if (entry.getValue() != null) { 5847 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5848 entry.getValue(), entry.getKey()); 5849 } 5850 } 5851 if (pkg.mUpgradeKeySets != null) { 5852 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5853 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5854 } 5855 } 5856 } 5857 } catch (NullPointerException e) { 5858 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5859 } catch (IllegalArgumentException e) { 5860 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5861 } 5862 5863 int N = pkg.providers.size(); 5864 StringBuilder r = null; 5865 int i; 5866 for (i=0; i<N; i++) { 5867 PackageParser.Provider p = pkg.providers.get(i); 5868 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5869 p.info.processName, pkg.applicationInfo.uid); 5870 mProviders.addProvider(p); 5871 p.syncable = p.info.isSyncable; 5872 if (p.info.authority != null) { 5873 String names[] = p.info.authority.split(";"); 5874 p.info.authority = null; 5875 for (int j = 0; j < names.length; j++) { 5876 if (j == 1 && p.syncable) { 5877 // We only want the first authority for a provider to possibly be 5878 // syncable, so if we already added this provider using a different 5879 // authority clear the syncable flag. We copy the provider before 5880 // changing it because the mProviders object contains a reference 5881 // to a provider that we don't want to change. 5882 // Only do this for the second authority since the resulting provider 5883 // object can be the same for all future authorities for this provider. 5884 p = new PackageParser.Provider(p); 5885 p.syncable = false; 5886 } 5887 if (!mProvidersByAuthority.containsKey(names[j])) { 5888 mProvidersByAuthority.put(names[j], p); 5889 if (p.info.authority == null) { 5890 p.info.authority = names[j]; 5891 } else { 5892 p.info.authority = p.info.authority + ";" + names[j]; 5893 } 5894 if (DEBUG_PACKAGE_SCANNING) { 5895 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5896 Log.d(TAG, "Registered content provider: " + names[j] 5897 + ", className = " + p.info.name + ", isSyncable = " 5898 + p.info.isSyncable); 5899 } 5900 } else { 5901 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5902 Slog.w(TAG, "Skipping provider name " + names[j] + 5903 " (in package " + pkg.applicationInfo.packageName + 5904 "): name already used by " 5905 + ((other != null && other.getComponentName() != null) 5906 ? other.getComponentName().getPackageName() : "?")); 5907 } 5908 } 5909 } 5910 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5911 if (r == null) { 5912 r = new StringBuilder(256); 5913 } else { 5914 r.append(' '); 5915 } 5916 r.append(p.info.name); 5917 } 5918 } 5919 if (r != null) { 5920 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5921 } 5922 5923 N = pkg.services.size(); 5924 r = null; 5925 for (i=0; i<N; i++) { 5926 PackageParser.Service s = pkg.services.get(i); 5927 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5928 s.info.processName, pkg.applicationInfo.uid); 5929 mServices.addService(s); 5930 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5931 if (r == null) { 5932 r = new StringBuilder(256); 5933 } else { 5934 r.append(' '); 5935 } 5936 r.append(s.info.name); 5937 } 5938 } 5939 if (r != null) { 5940 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5941 } 5942 5943 N = pkg.receivers.size(); 5944 r = null; 5945 for (i=0; i<N; i++) { 5946 PackageParser.Activity a = pkg.receivers.get(i); 5947 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5948 a.info.processName, pkg.applicationInfo.uid); 5949 mReceivers.addActivity(a, "receiver"); 5950 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5951 if (r == null) { 5952 r = new StringBuilder(256); 5953 } else { 5954 r.append(' '); 5955 } 5956 r.append(a.info.name); 5957 } 5958 } 5959 if (r != null) { 5960 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5961 } 5962 5963 N = pkg.activities.size(); 5964 r = null; 5965 for (i=0; i<N; i++) { 5966 PackageParser.Activity a = pkg.activities.get(i); 5967 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5968 a.info.processName, pkg.applicationInfo.uid); 5969 mActivities.addActivity(a, "activity"); 5970 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5971 if (r == null) { 5972 r = new StringBuilder(256); 5973 } else { 5974 r.append(' '); 5975 } 5976 r.append(a.info.name); 5977 } 5978 } 5979 if (r != null) { 5980 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5981 } 5982 5983 N = pkg.permissionGroups.size(); 5984 r = null; 5985 for (i=0; i<N; i++) { 5986 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5987 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5988 if (cur == null) { 5989 mPermissionGroups.put(pg.info.name, pg); 5990 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5991 if (r == null) { 5992 r = new StringBuilder(256); 5993 } else { 5994 r.append(' '); 5995 } 5996 r.append(pg.info.name); 5997 } 5998 } else { 5999 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6000 + pg.info.packageName + " ignored: original from " 6001 + cur.info.packageName); 6002 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6003 if (r == null) { 6004 r = new StringBuilder(256); 6005 } else { 6006 r.append(' '); 6007 } 6008 r.append("DUP:"); 6009 r.append(pg.info.name); 6010 } 6011 } 6012 } 6013 if (r != null) { 6014 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6015 } 6016 6017 N = pkg.permissions.size(); 6018 r = null; 6019 for (i=0; i<N; i++) { 6020 PackageParser.Permission p = pkg.permissions.get(i); 6021 HashMap<String, BasePermission> permissionMap = 6022 p.tree ? mSettings.mPermissionTrees 6023 : mSettings.mPermissions; 6024 p.group = mPermissionGroups.get(p.info.group); 6025 if (p.info.group == null || p.group != null) { 6026 BasePermission bp = permissionMap.get(p.info.name); 6027 if (bp == null) { 6028 bp = new BasePermission(p.info.name, p.info.packageName, 6029 BasePermission.TYPE_NORMAL); 6030 permissionMap.put(p.info.name, bp); 6031 } 6032 if (bp.perm == null) { 6033 if (bp.sourcePackage != null 6034 && !bp.sourcePackage.equals(p.info.packageName)) { 6035 // If this is a permission that was formerly defined by a non-system 6036 // app, but is now defined by a system app (following an upgrade), 6037 // discard the previous declaration and consider the system's to be 6038 // canonical. 6039 if (isSystemApp(p.owner)) { 6040 String msg = "New decl " + p.owner + " of permission " 6041 + p.info.name + " is system"; 6042 reportSettingsProblem(Log.WARN, msg); 6043 bp.sourcePackage = null; 6044 } 6045 } 6046 if (bp.sourcePackage == null 6047 || bp.sourcePackage.equals(p.info.packageName)) { 6048 BasePermission tree = findPermissionTreeLP(p.info.name); 6049 if (tree == null 6050 || tree.sourcePackage.equals(p.info.packageName)) { 6051 bp.packageSetting = pkgSetting; 6052 bp.perm = p; 6053 bp.uid = pkg.applicationInfo.uid; 6054 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6055 if (r == null) { 6056 r = new StringBuilder(256); 6057 } else { 6058 r.append(' '); 6059 } 6060 r.append(p.info.name); 6061 } 6062 } else { 6063 Slog.w(TAG, "Permission " + p.info.name + " from package " 6064 + p.info.packageName + " ignored: base tree " 6065 + tree.name + " is from package " 6066 + tree.sourcePackage); 6067 } 6068 } else { 6069 Slog.w(TAG, "Permission " + p.info.name + " from package " 6070 + p.info.packageName + " ignored: original from " 6071 + bp.sourcePackage); 6072 } 6073 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6074 if (r == null) { 6075 r = new StringBuilder(256); 6076 } else { 6077 r.append(' '); 6078 } 6079 r.append("DUP:"); 6080 r.append(p.info.name); 6081 } 6082 if (bp.perm == p) { 6083 bp.protectionLevel = p.info.protectionLevel; 6084 } 6085 } else { 6086 Slog.w(TAG, "Permission " + p.info.name + " from package " 6087 + p.info.packageName + " ignored: no group " 6088 + p.group); 6089 } 6090 } 6091 if (r != null) { 6092 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6093 } 6094 6095 N = pkg.instrumentation.size(); 6096 r = null; 6097 for (i=0; i<N; i++) { 6098 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6099 a.info.packageName = pkg.applicationInfo.packageName; 6100 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6101 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6102 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6103 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6104 a.info.dataDir = pkg.applicationInfo.dataDir; 6105 6106 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6107 // need other information about the application, like the ABI and what not ? 6108 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6109 mInstrumentation.put(a.getComponentName(), a); 6110 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6111 if (r == null) { 6112 r = new StringBuilder(256); 6113 } else { 6114 r.append(' '); 6115 } 6116 r.append(a.info.name); 6117 } 6118 } 6119 if (r != null) { 6120 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6121 } 6122 6123 if (pkg.protectedBroadcasts != null) { 6124 N = pkg.protectedBroadcasts.size(); 6125 for (i=0; i<N; i++) { 6126 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6127 } 6128 } 6129 6130 pkgSetting.setTimeStamp(scanFileTime); 6131 6132 // Create idmap files for pairs of (packages, overlay packages). 6133 // Note: "android", ie framework-res.apk, is handled by native layers. 6134 if (pkg.mOverlayTarget != null) { 6135 // This is an overlay package. 6136 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6137 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6138 mOverlays.put(pkg.mOverlayTarget, 6139 new HashMap<String, PackageParser.Package>()); 6140 } 6141 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6142 map.put(pkg.packageName, pkg); 6143 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6144 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6145 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6146 "scanPackageLI failed to createIdmap"); 6147 } 6148 } 6149 } else if (mOverlays.containsKey(pkg.packageName) && 6150 !pkg.packageName.equals("android")) { 6151 // This is a regular package, with one or more known overlay packages. 6152 createIdmapsForPackageLI(pkg); 6153 } 6154 } 6155 6156 return pkg; 6157 } 6158 6159 /** 6160 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6161 * i.e, so that all packages can be run inside a single process if required. 6162 * 6163 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6164 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6165 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6166 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6167 * updating a package that belongs to a shared user. 6168 * 6169 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6170 * adds unnecessary complexity. 6171 */ 6172 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6173 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6174 String requiredInstructionSet = null; 6175 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6176 requiredInstructionSet = VMRuntime.getInstructionSet( 6177 scannedPackage.applicationInfo.primaryCpuAbi); 6178 } 6179 6180 PackageSetting requirer = null; 6181 for (PackageSetting ps : packagesForUser) { 6182 // If packagesForUser contains scannedPackage, we skip it. This will happen 6183 // when scannedPackage is an update of an existing package. Without this check, 6184 // we will never be able to change the ABI of any package belonging to a shared 6185 // user, even if it's compatible with other packages. 6186 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6187 if (ps.primaryCpuAbiString == null) { 6188 continue; 6189 } 6190 6191 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6192 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6193 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6194 // this but there's not much we can do. 6195 String errorMessage = "Instruction set mismatch, " 6196 + ((requirer == null) ? "[caller]" : requirer) 6197 + " requires " + requiredInstructionSet + " whereas " + ps 6198 + " requires " + instructionSet; 6199 Slog.w(TAG, errorMessage); 6200 } 6201 6202 if (requiredInstructionSet == null) { 6203 requiredInstructionSet = instructionSet; 6204 requirer = ps; 6205 } 6206 } 6207 } 6208 6209 if (requiredInstructionSet != null) { 6210 String adjustedAbi; 6211 if (requirer != null) { 6212 // requirer != null implies that either scannedPackage was null or that scannedPackage 6213 // did not require an ABI, in which case we have to adjust scannedPackage to match 6214 // the ABI of the set (which is the same as requirer's ABI) 6215 adjustedAbi = requirer.primaryCpuAbiString; 6216 if (scannedPackage != null) { 6217 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6218 } 6219 } else { 6220 // requirer == null implies that we're updating all ABIs in the set to 6221 // match scannedPackage. 6222 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6223 } 6224 6225 for (PackageSetting ps : packagesForUser) { 6226 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6227 if (ps.primaryCpuAbiString != null) { 6228 continue; 6229 } 6230 6231 ps.primaryCpuAbiString = adjustedAbi; 6232 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6233 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6234 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6235 6236 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6237 deferDexOpt, true) == DEX_OPT_FAILED) { 6238 ps.primaryCpuAbiString = null; 6239 ps.pkg.applicationInfo.primaryCpuAbi = null; 6240 return; 6241 } else { 6242 mInstaller.rmdex(ps.codePathString, 6243 getDexCodeInstructionSet(getPreferredInstructionSet())); 6244 } 6245 } 6246 } 6247 } 6248 } 6249 } 6250 6251 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6252 synchronized (mPackages) { 6253 mResolverReplaced = true; 6254 // Set up information for custom user intent resolution activity. 6255 mResolveActivity.applicationInfo = pkg.applicationInfo; 6256 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6257 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6258 mResolveActivity.processName = null; 6259 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6260 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6261 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6262 mResolveActivity.theme = 0; 6263 mResolveActivity.exported = true; 6264 mResolveActivity.enabled = true; 6265 mResolveInfo.activityInfo = mResolveActivity; 6266 mResolveInfo.priority = 0; 6267 mResolveInfo.preferredOrder = 0; 6268 mResolveInfo.match = 0; 6269 mResolveComponentName = mCustomResolverComponentName; 6270 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6271 mResolveComponentName); 6272 } 6273 } 6274 6275 private static String calculateBundledApkRoot(final String codePathString) { 6276 final File codePath = new File(codePathString); 6277 final File codeRoot; 6278 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6279 codeRoot = Environment.getRootDirectory(); 6280 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6281 codeRoot = Environment.getOemDirectory(); 6282 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6283 codeRoot = Environment.getVendorDirectory(); 6284 } else { 6285 // Unrecognized code path; take its top real segment as the apk root: 6286 // e.g. /something/app/blah.apk => /something 6287 try { 6288 File f = codePath.getCanonicalFile(); 6289 File parent = f.getParentFile(); // non-null because codePath is a file 6290 File tmp; 6291 while ((tmp = parent.getParentFile()) != null) { 6292 f = parent; 6293 parent = tmp; 6294 } 6295 codeRoot = f; 6296 Slog.w(TAG, "Unrecognized code path " 6297 + codePath + " - using " + codeRoot); 6298 } catch (IOException e) { 6299 // Can't canonicalize the code path -- shenanigans? 6300 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6301 return Environment.getRootDirectory().getPath(); 6302 } 6303 } 6304 return codeRoot.getPath(); 6305 } 6306 6307 /** 6308 * Derive and set the location of native libraries for the given package, 6309 * which varies depending on where and how the package was installed. 6310 */ 6311 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6312 final ApplicationInfo info = pkg.applicationInfo; 6313 final String codePath = pkg.codePath; 6314 final File codeFile = new File(codePath); 6315 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6316 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6317 6318 info.nativeLibraryRootDir = null; 6319 info.nativeLibraryRootRequiresIsa = false; 6320 info.nativeLibraryDir = null; 6321 info.secondaryNativeLibraryDir = null; 6322 6323 if (isApkFile(codeFile)) { 6324 // Monolithic install 6325 if (bundledApp) { 6326 // If "/system/lib64/apkname" exists, assume that is the per-package 6327 // native library directory to use; otherwise use "/system/lib/apkname". 6328 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6329 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6330 getPrimaryInstructionSet(info)); 6331 6332 // This is a bundled system app so choose the path based on the ABI. 6333 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6334 // is just the default path. 6335 final String apkName = deriveCodePathName(codePath); 6336 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6337 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6338 apkName).getAbsolutePath(); 6339 6340 if (info.secondaryCpuAbi != null) { 6341 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6342 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6343 secondaryLibDir, apkName).getAbsolutePath(); 6344 } 6345 } else if (asecApp) { 6346 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6347 .getAbsolutePath(); 6348 } else { 6349 final String apkName = deriveCodePathName(codePath); 6350 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6351 .getAbsolutePath(); 6352 } 6353 6354 info.nativeLibraryRootRequiresIsa = false; 6355 info.nativeLibraryDir = info.nativeLibraryRootDir; 6356 } else { 6357 // Cluster install 6358 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6359 info.nativeLibraryRootRequiresIsa = true; 6360 6361 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6362 getPrimaryInstructionSet(info)).getAbsolutePath(); 6363 6364 if (info.secondaryCpuAbi != null) { 6365 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6366 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6367 } 6368 } 6369 } 6370 6371 /** 6372 * Calculate the abis and roots for a bundled app. These can uniquely 6373 * be determined from the contents of the system partition, i.e whether 6374 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6375 * of this information, and instead assume that the system was built 6376 * sensibly. 6377 */ 6378 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6379 PackageSetting pkgSetting) { 6380 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6381 6382 // If "/system/lib64/apkname" exists, assume that is the per-package 6383 // native library directory to use; otherwise use "/system/lib/apkname". 6384 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6385 setBundledAppAbi(pkg, apkRoot, apkName); 6386 // pkgSetting might be null during rescan following uninstall of updates 6387 // to a bundled app, so accommodate that possibility. The settings in 6388 // that case will be established later from the parsed package. 6389 // 6390 // If the settings aren't null, sync them up with what we've just derived. 6391 // note that apkRoot isn't stored in the package settings. 6392 if (pkgSetting != null) { 6393 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6394 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6395 } 6396 } 6397 6398 /** 6399 * Deduces the ABI of a bundled app and sets the relevant fields on the 6400 * parsed pkg object. 6401 * 6402 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6403 * under which system libraries are installed. 6404 * @param apkName the name of the installed package. 6405 */ 6406 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6407 final File codeFile = new File(pkg.codePath); 6408 6409 final boolean has64BitLibs; 6410 final boolean has32BitLibs; 6411 if (isApkFile(codeFile)) { 6412 // Monolithic install 6413 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6414 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6415 } else { 6416 // Cluster install 6417 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6418 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6419 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6420 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6421 has64BitLibs = (new File(rootDir, isa)).exists(); 6422 } else { 6423 has64BitLibs = false; 6424 } 6425 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6426 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6427 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6428 has32BitLibs = (new File(rootDir, isa)).exists(); 6429 } else { 6430 has32BitLibs = false; 6431 } 6432 } 6433 6434 if (has64BitLibs && !has32BitLibs) { 6435 // The package has 64 bit libs, but not 32 bit libs. Its primary 6436 // ABI should be 64 bit. We can safely assume here that the bundled 6437 // native libraries correspond to the most preferred ABI in the list. 6438 6439 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6440 pkg.applicationInfo.secondaryCpuAbi = null; 6441 } else if (has32BitLibs && !has64BitLibs) { 6442 // The package has 32 bit libs but not 64 bit libs. Its primary 6443 // ABI should be 32 bit. 6444 6445 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6446 pkg.applicationInfo.secondaryCpuAbi = null; 6447 } else if (has32BitLibs && has64BitLibs) { 6448 // The application has both 64 and 32 bit bundled libraries. We check 6449 // here that the app declares multiArch support, and warn if it doesn't. 6450 // 6451 // We will be lenient here and record both ABIs. The primary will be the 6452 // ABI that's higher on the list, i.e, a device that's configured to prefer 6453 // 64 bit apps will see a 64 bit primary ABI, 6454 6455 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6456 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6457 } 6458 6459 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6460 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6461 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6462 } else { 6463 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6464 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6465 } 6466 } else { 6467 pkg.applicationInfo.primaryCpuAbi = null; 6468 pkg.applicationInfo.secondaryCpuAbi = null; 6469 } 6470 } 6471 6472 private static void createNativeLibrarySubdir(File path) throws IOException { 6473 if (!path.isDirectory()) { 6474 path.delete(); 6475 6476 if (!path.mkdir()) { 6477 throw new IOException("Cannot create " + path.getPath()); 6478 } 6479 6480 try { 6481 Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6482 } catch (ErrnoException e) { 6483 throw new IOException("Cannot chmod native library directory " 6484 + path.getPath(), e); 6485 } 6486 } else if (!SELinux.restorecon(path)) { 6487 throw new IOException("Cannot set SELinux context for " + path.getPath()); 6488 } 6489 } 6490 6491 private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle, 6492 final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException { 6493 createNativeLibrarySubdir(nativeLibraryRoot); 6494 6495 /* 6496 * If this is an internal application or our nativeLibraryPath points to 6497 * the app-lib directory, unpack the libraries if necessary. 6498 */ 6499 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6500 if (abi >= 0) { 6501 /* 6502 * If we have a matching instruction set, construct a subdir under the native 6503 * library root that corresponds to this instruction set. 6504 */ 6505 final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]); 6506 final File subDir; 6507 if (useIsaSubdir) { 6508 final File isaSubdir = new File(nativeLibraryRoot, instructionSet); 6509 createNativeLibrarySubdir(isaSubdir); 6510 subDir = isaSubdir; 6511 } else { 6512 subDir = nativeLibraryRoot; 6513 } 6514 6515 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, subDir, abiList[abi]); 6516 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6517 return copyRet; 6518 } 6519 } 6520 6521 return abi; 6522 } 6523 6524 private void killApplication(String pkgName, int appId, String reason) { 6525 // Request the ActivityManager to kill the process(only for existing packages) 6526 // so that we do not end up in a confused state while the user is still using the older 6527 // version of the application while the new one gets installed. 6528 IActivityManager am = ActivityManagerNative.getDefault(); 6529 if (am != null) { 6530 try { 6531 am.killApplicationWithAppId(pkgName, appId, reason); 6532 } catch (RemoteException e) { 6533 } 6534 } 6535 } 6536 6537 void removePackageLI(PackageSetting ps, boolean chatty) { 6538 if (DEBUG_INSTALL) { 6539 if (chatty) 6540 Log.d(TAG, "Removing package " + ps.name); 6541 } 6542 6543 // writer 6544 synchronized (mPackages) { 6545 mPackages.remove(ps.name); 6546 if (ps.codePathString != null) { 6547 mAppDirs.remove(ps.codePathString); 6548 } 6549 6550 final PackageParser.Package pkg = ps.pkg; 6551 if (pkg != null) { 6552 cleanPackageDataStructuresLILPw(pkg, chatty); 6553 } 6554 } 6555 } 6556 6557 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6558 if (DEBUG_INSTALL) { 6559 if (chatty) 6560 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6561 } 6562 6563 // writer 6564 synchronized (mPackages) { 6565 mPackages.remove(pkg.applicationInfo.packageName); 6566 if (pkg.codePath != null) { 6567 mAppDirs.remove(pkg.codePath); 6568 } 6569 cleanPackageDataStructuresLILPw(pkg, chatty); 6570 } 6571 } 6572 6573 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6574 int N = pkg.providers.size(); 6575 StringBuilder r = null; 6576 int i; 6577 for (i=0; i<N; i++) { 6578 PackageParser.Provider p = pkg.providers.get(i); 6579 mProviders.removeProvider(p); 6580 if (p.info.authority == null) { 6581 6582 /* There was another ContentProvider with this authority when 6583 * this app was installed so this authority is null, 6584 * Ignore it as we don't have to unregister the provider. 6585 */ 6586 continue; 6587 } 6588 String names[] = p.info.authority.split(";"); 6589 for (int j = 0; j < names.length; j++) { 6590 if (mProvidersByAuthority.get(names[j]) == p) { 6591 mProvidersByAuthority.remove(names[j]); 6592 if (DEBUG_REMOVE) { 6593 if (chatty) 6594 Log.d(TAG, "Unregistered content provider: " + names[j] 6595 + ", className = " + p.info.name + ", isSyncable = " 6596 + p.info.isSyncable); 6597 } 6598 } 6599 } 6600 if (DEBUG_REMOVE && chatty) { 6601 if (r == null) { 6602 r = new StringBuilder(256); 6603 } else { 6604 r.append(' '); 6605 } 6606 r.append(p.info.name); 6607 } 6608 } 6609 if (r != null) { 6610 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6611 } 6612 6613 N = pkg.services.size(); 6614 r = null; 6615 for (i=0; i<N; i++) { 6616 PackageParser.Service s = pkg.services.get(i); 6617 mServices.removeService(s); 6618 if (chatty) { 6619 if (r == null) { 6620 r = new StringBuilder(256); 6621 } else { 6622 r.append(' '); 6623 } 6624 r.append(s.info.name); 6625 } 6626 } 6627 if (r != null) { 6628 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6629 } 6630 6631 N = pkg.receivers.size(); 6632 r = null; 6633 for (i=0; i<N; i++) { 6634 PackageParser.Activity a = pkg.receivers.get(i); 6635 mReceivers.removeActivity(a, "receiver"); 6636 if (DEBUG_REMOVE && chatty) { 6637 if (r == null) { 6638 r = new StringBuilder(256); 6639 } else { 6640 r.append(' '); 6641 } 6642 r.append(a.info.name); 6643 } 6644 } 6645 if (r != null) { 6646 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6647 } 6648 6649 N = pkg.activities.size(); 6650 r = null; 6651 for (i=0; i<N; i++) { 6652 PackageParser.Activity a = pkg.activities.get(i); 6653 mActivities.removeActivity(a, "activity"); 6654 if (DEBUG_REMOVE && chatty) { 6655 if (r == null) { 6656 r = new StringBuilder(256); 6657 } else { 6658 r.append(' '); 6659 } 6660 r.append(a.info.name); 6661 } 6662 } 6663 if (r != null) { 6664 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6665 } 6666 6667 N = pkg.permissions.size(); 6668 r = null; 6669 for (i=0; i<N; i++) { 6670 PackageParser.Permission p = pkg.permissions.get(i); 6671 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6672 if (bp == null) { 6673 bp = mSettings.mPermissionTrees.get(p.info.name); 6674 } 6675 if (bp != null && bp.perm == p) { 6676 bp.perm = null; 6677 if (DEBUG_REMOVE && chatty) { 6678 if (r == null) { 6679 r = new StringBuilder(256); 6680 } else { 6681 r.append(' '); 6682 } 6683 r.append(p.info.name); 6684 } 6685 } 6686 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6687 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6688 if (appOpPerms != null) { 6689 appOpPerms.remove(pkg.packageName); 6690 } 6691 } 6692 } 6693 if (r != null) { 6694 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6695 } 6696 6697 N = pkg.requestedPermissions.size(); 6698 r = null; 6699 for (i=0; i<N; i++) { 6700 String perm = pkg.requestedPermissions.get(i); 6701 BasePermission bp = mSettings.mPermissions.get(perm); 6702 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6703 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6704 if (appOpPerms != null) { 6705 appOpPerms.remove(pkg.packageName); 6706 if (appOpPerms.isEmpty()) { 6707 mAppOpPermissionPackages.remove(perm); 6708 } 6709 } 6710 } 6711 } 6712 if (r != null) { 6713 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6714 } 6715 6716 N = pkg.instrumentation.size(); 6717 r = null; 6718 for (i=0; i<N; i++) { 6719 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6720 mInstrumentation.remove(a.getComponentName()); 6721 if (DEBUG_REMOVE && chatty) { 6722 if (r == null) { 6723 r = new StringBuilder(256); 6724 } else { 6725 r.append(' '); 6726 } 6727 r.append(a.info.name); 6728 } 6729 } 6730 if (r != null) { 6731 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6732 } 6733 6734 r = null; 6735 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6736 // Only system apps can hold shared libraries. 6737 if (pkg.libraryNames != null) { 6738 for (i=0; i<pkg.libraryNames.size(); i++) { 6739 String name = pkg.libraryNames.get(i); 6740 SharedLibraryEntry cur = mSharedLibraries.get(name); 6741 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6742 mSharedLibraries.remove(name); 6743 if (DEBUG_REMOVE && chatty) { 6744 if (r == null) { 6745 r = new StringBuilder(256); 6746 } else { 6747 r.append(' '); 6748 } 6749 r.append(name); 6750 } 6751 } 6752 } 6753 } 6754 } 6755 if (r != null) { 6756 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6757 } 6758 } 6759 6760 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6761 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6762 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6763 return true; 6764 } 6765 } 6766 return false; 6767 } 6768 6769 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6770 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6771 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6772 6773 private void updatePermissionsLPw(String changingPkg, 6774 PackageParser.Package pkgInfo, int flags) { 6775 // Make sure there are no dangling permission trees. 6776 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6777 while (it.hasNext()) { 6778 final BasePermission bp = it.next(); 6779 if (bp.packageSetting == null) { 6780 // We may not yet have parsed the package, so just see if 6781 // we still know about its settings. 6782 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6783 } 6784 if (bp.packageSetting == null) { 6785 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6786 + " from package " + bp.sourcePackage); 6787 it.remove(); 6788 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6789 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6790 Slog.i(TAG, "Removing old permission tree: " + bp.name 6791 + " from package " + bp.sourcePackage); 6792 flags |= UPDATE_PERMISSIONS_ALL; 6793 it.remove(); 6794 } 6795 } 6796 } 6797 6798 // Make sure all dynamic permissions have been assigned to a package, 6799 // and make sure there are no dangling permissions. 6800 it = mSettings.mPermissions.values().iterator(); 6801 while (it.hasNext()) { 6802 final BasePermission bp = it.next(); 6803 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6804 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6805 + bp.name + " pkg=" + bp.sourcePackage 6806 + " info=" + bp.pendingInfo); 6807 if (bp.packageSetting == null && bp.pendingInfo != null) { 6808 final BasePermission tree = findPermissionTreeLP(bp.name); 6809 if (tree != null && tree.perm != null) { 6810 bp.packageSetting = tree.packageSetting; 6811 bp.perm = new PackageParser.Permission(tree.perm.owner, 6812 new PermissionInfo(bp.pendingInfo)); 6813 bp.perm.info.packageName = tree.perm.info.packageName; 6814 bp.perm.info.name = bp.name; 6815 bp.uid = tree.uid; 6816 } 6817 } 6818 } 6819 if (bp.packageSetting == null) { 6820 // We may not yet have parsed the package, so just see if 6821 // we still know about its settings. 6822 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6823 } 6824 if (bp.packageSetting == null) { 6825 Slog.w(TAG, "Removing dangling permission: " + bp.name 6826 + " from package " + bp.sourcePackage); 6827 it.remove(); 6828 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6829 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6830 Slog.i(TAG, "Removing old permission: " + bp.name 6831 + " from package " + bp.sourcePackage); 6832 flags |= UPDATE_PERMISSIONS_ALL; 6833 it.remove(); 6834 } 6835 } 6836 } 6837 6838 // Now update the permissions for all packages, in particular 6839 // replace the granted permissions of the system packages. 6840 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6841 for (PackageParser.Package pkg : mPackages.values()) { 6842 if (pkg != pkgInfo) { 6843 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6844 } 6845 } 6846 } 6847 6848 if (pkgInfo != null) { 6849 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6850 } 6851 } 6852 6853 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6854 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6855 if (ps == null) { 6856 return; 6857 } 6858 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6859 HashSet<String> origPermissions = gp.grantedPermissions; 6860 boolean changedPermission = false; 6861 6862 if (replace) { 6863 ps.permissionsFixed = false; 6864 if (gp == ps) { 6865 origPermissions = new HashSet<String>(gp.grantedPermissions); 6866 gp.grantedPermissions.clear(); 6867 gp.gids = mGlobalGids; 6868 } 6869 } 6870 6871 if (gp.gids == null) { 6872 gp.gids = mGlobalGids; 6873 } 6874 6875 final int N = pkg.requestedPermissions.size(); 6876 for (int i=0; i<N; i++) { 6877 final String name = pkg.requestedPermissions.get(i); 6878 final boolean required = pkg.requestedPermissionsRequired.get(i); 6879 final BasePermission bp = mSettings.mPermissions.get(name); 6880 if (DEBUG_INSTALL) { 6881 if (gp != ps) { 6882 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6883 } 6884 } 6885 6886 if (bp == null || bp.packageSetting == null) { 6887 Slog.w(TAG, "Unknown permission " + name 6888 + " in package " + pkg.packageName); 6889 continue; 6890 } 6891 6892 final String perm = bp.name; 6893 boolean allowed; 6894 boolean allowedSig = false; 6895 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6896 // Keep track of app op permissions. 6897 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6898 if (pkgs == null) { 6899 pkgs = new ArraySet<>(); 6900 mAppOpPermissionPackages.put(bp.name, pkgs); 6901 } 6902 pkgs.add(pkg.packageName); 6903 } 6904 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6905 if (level == PermissionInfo.PROTECTION_NORMAL 6906 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6907 // We grant a normal or dangerous permission if any of the following 6908 // are true: 6909 // 1) The permission is required 6910 // 2) The permission is optional, but was granted in the past 6911 // 3) The permission is optional, but was requested by an 6912 // app in /system (not /data) 6913 // 6914 // Otherwise, reject the permission. 6915 allowed = (required || origPermissions.contains(perm) 6916 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6917 } else if (bp.packageSetting == null) { 6918 // This permission is invalid; skip it. 6919 allowed = false; 6920 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6921 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6922 if (allowed) { 6923 allowedSig = true; 6924 } 6925 } else { 6926 allowed = false; 6927 } 6928 if (DEBUG_INSTALL) { 6929 if (gp != ps) { 6930 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6931 } 6932 } 6933 if (allowed) { 6934 if (!isSystemApp(ps) && ps.permissionsFixed) { 6935 // If this is an existing, non-system package, then 6936 // we can't add any new permissions to it. 6937 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6938 // Except... if this is a permission that was added 6939 // to the platform (note: need to only do this when 6940 // updating the platform). 6941 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6942 } 6943 } 6944 if (allowed) { 6945 if (!gp.grantedPermissions.contains(perm)) { 6946 changedPermission = true; 6947 gp.grantedPermissions.add(perm); 6948 gp.gids = appendInts(gp.gids, bp.gids); 6949 } else if (!ps.haveGids) { 6950 gp.gids = appendInts(gp.gids, bp.gids); 6951 } 6952 } else { 6953 Slog.w(TAG, "Not granting permission " + perm 6954 + " to package " + pkg.packageName 6955 + " because it was previously installed without"); 6956 } 6957 } else { 6958 if (gp.grantedPermissions.remove(perm)) { 6959 changedPermission = true; 6960 gp.gids = removeInts(gp.gids, bp.gids); 6961 Slog.i(TAG, "Un-granting permission " + perm 6962 + " from package " + pkg.packageName 6963 + " (protectionLevel=" + bp.protectionLevel 6964 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6965 + ")"); 6966 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6967 // Don't print warning for app op permissions, since it is fine for them 6968 // not to be granted, there is a UI for the user to decide. 6969 Slog.w(TAG, "Not granting permission " + perm 6970 + " to package " + pkg.packageName 6971 + " (protectionLevel=" + bp.protectionLevel 6972 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6973 + ")"); 6974 } 6975 } 6976 } 6977 6978 if ((changedPermission || replace) && !ps.permissionsFixed && 6979 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6980 // This is the first that we have heard about this package, so the 6981 // permissions we have now selected are fixed until explicitly 6982 // changed. 6983 ps.permissionsFixed = true; 6984 } 6985 ps.haveGids = true; 6986 } 6987 6988 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6989 boolean allowed = false; 6990 final int NP = PackageParser.NEW_PERMISSIONS.length; 6991 for (int ip=0; ip<NP; ip++) { 6992 final PackageParser.NewPermissionInfo npi 6993 = PackageParser.NEW_PERMISSIONS[ip]; 6994 if (npi.name.equals(perm) 6995 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6996 allowed = true; 6997 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6998 + pkg.packageName); 6999 break; 7000 } 7001 } 7002 return allowed; 7003 } 7004 7005 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7006 BasePermission bp, HashSet<String> origPermissions) { 7007 boolean allowed; 7008 allowed = (compareSignatures( 7009 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7010 == PackageManager.SIGNATURE_MATCH) 7011 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7012 == PackageManager.SIGNATURE_MATCH); 7013 if (!allowed && (bp.protectionLevel 7014 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7015 if (isSystemApp(pkg)) { 7016 // For updated system applications, a system permission 7017 // is granted only if it had been defined by the original application. 7018 if (isUpdatedSystemApp(pkg)) { 7019 final PackageSetting sysPs = mSettings 7020 .getDisabledSystemPkgLPr(pkg.packageName); 7021 final GrantedPermissions origGp = sysPs.sharedUser != null 7022 ? sysPs.sharedUser : sysPs; 7023 7024 if (origGp.grantedPermissions.contains(perm)) { 7025 // If the original was granted this permission, we take 7026 // that grant decision as read and propagate it to the 7027 // update. 7028 allowed = true; 7029 } else { 7030 // The system apk may have been updated with an older 7031 // version of the one on the data partition, but which 7032 // granted a new system permission that it didn't have 7033 // before. In this case we do want to allow the app to 7034 // now get the new permission if the ancestral apk is 7035 // privileged to get it. 7036 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7037 for (int j=0; 7038 j<sysPs.pkg.requestedPermissions.size(); j++) { 7039 if (perm.equals( 7040 sysPs.pkg.requestedPermissions.get(j))) { 7041 allowed = true; 7042 break; 7043 } 7044 } 7045 } 7046 } 7047 } else { 7048 allowed = isPrivilegedApp(pkg); 7049 } 7050 } 7051 } 7052 if (!allowed && (bp.protectionLevel 7053 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7054 // For development permissions, a development permission 7055 // is granted only if it was already granted. 7056 allowed = origPermissions.contains(perm); 7057 } 7058 return allowed; 7059 } 7060 7061 final class ActivityIntentResolver 7062 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7063 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7064 boolean defaultOnly, int userId) { 7065 if (!sUserManager.exists(userId)) return null; 7066 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7067 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7068 } 7069 7070 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7071 int userId) { 7072 if (!sUserManager.exists(userId)) return null; 7073 mFlags = flags; 7074 return super.queryIntent(intent, resolvedType, 7075 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7076 } 7077 7078 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7079 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7080 if (!sUserManager.exists(userId)) return null; 7081 if (packageActivities == null) { 7082 return null; 7083 } 7084 mFlags = flags; 7085 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7086 final int N = packageActivities.size(); 7087 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7088 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7089 7090 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7091 for (int i = 0; i < N; ++i) { 7092 intentFilters = packageActivities.get(i).intents; 7093 if (intentFilters != null && intentFilters.size() > 0) { 7094 PackageParser.ActivityIntentInfo[] array = 7095 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7096 intentFilters.toArray(array); 7097 listCut.add(array); 7098 } 7099 } 7100 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7101 } 7102 7103 public final void addActivity(PackageParser.Activity a, String type) { 7104 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7105 mActivities.put(a.getComponentName(), a); 7106 if (DEBUG_SHOW_INFO) 7107 Log.v( 7108 TAG, " " + type + " " + 7109 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7110 if (DEBUG_SHOW_INFO) 7111 Log.v(TAG, " Class=" + a.info.name); 7112 final int NI = a.intents.size(); 7113 for (int j=0; j<NI; j++) { 7114 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7115 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7116 intent.setPriority(0); 7117 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7118 + a.className + " with priority > 0, forcing to 0"); 7119 } 7120 if (DEBUG_SHOW_INFO) { 7121 Log.v(TAG, " IntentFilter:"); 7122 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7123 } 7124 if (!intent.debugCheck()) { 7125 Log.w(TAG, "==> For Activity " + a.info.name); 7126 } 7127 addFilter(intent); 7128 } 7129 } 7130 7131 public final void removeActivity(PackageParser.Activity a, String type) { 7132 mActivities.remove(a.getComponentName()); 7133 if (DEBUG_SHOW_INFO) { 7134 Log.v(TAG, " " + type + " " 7135 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7136 : a.info.name) + ":"); 7137 Log.v(TAG, " Class=" + a.info.name); 7138 } 7139 final int NI = a.intents.size(); 7140 for (int j=0; j<NI; j++) { 7141 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7142 if (DEBUG_SHOW_INFO) { 7143 Log.v(TAG, " IntentFilter:"); 7144 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7145 } 7146 removeFilter(intent); 7147 } 7148 } 7149 7150 @Override 7151 protected boolean allowFilterResult( 7152 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7153 ActivityInfo filterAi = filter.activity.info; 7154 for (int i=dest.size()-1; i>=0; i--) { 7155 ActivityInfo destAi = dest.get(i).activityInfo; 7156 if (destAi.name == filterAi.name 7157 && destAi.packageName == filterAi.packageName) { 7158 return false; 7159 } 7160 } 7161 return true; 7162 } 7163 7164 @Override 7165 protected ActivityIntentInfo[] newArray(int size) { 7166 return new ActivityIntentInfo[size]; 7167 } 7168 7169 @Override 7170 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7171 if (!sUserManager.exists(userId)) return true; 7172 PackageParser.Package p = filter.activity.owner; 7173 if (p != null) { 7174 PackageSetting ps = (PackageSetting)p.mExtras; 7175 if (ps != null) { 7176 // System apps are never considered stopped for purposes of 7177 // filtering, because there may be no way for the user to 7178 // actually re-launch them. 7179 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7180 && ps.getStopped(userId); 7181 } 7182 } 7183 return false; 7184 } 7185 7186 @Override 7187 protected boolean isPackageForFilter(String packageName, 7188 PackageParser.ActivityIntentInfo info) { 7189 return packageName.equals(info.activity.owner.packageName); 7190 } 7191 7192 @Override 7193 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7194 int match, int userId) { 7195 if (!sUserManager.exists(userId)) return null; 7196 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7197 return null; 7198 } 7199 final PackageParser.Activity activity = info.activity; 7200 if (mSafeMode && (activity.info.applicationInfo.flags 7201 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7202 return null; 7203 } 7204 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7205 if (ps == null) { 7206 return null; 7207 } 7208 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7209 ps.readUserState(userId), userId); 7210 if (ai == null) { 7211 return null; 7212 } 7213 final ResolveInfo res = new ResolveInfo(); 7214 res.activityInfo = ai; 7215 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7216 res.filter = info; 7217 } 7218 res.priority = info.getPriority(); 7219 res.preferredOrder = activity.owner.mPreferredOrder; 7220 //System.out.println("Result: " + res.activityInfo.className + 7221 // " = " + res.priority); 7222 res.match = match; 7223 res.isDefault = info.hasDefault; 7224 res.labelRes = info.labelRes; 7225 res.nonLocalizedLabel = info.nonLocalizedLabel; 7226 if (userNeedsBadging(userId)) { 7227 res.noResourceId = true; 7228 } else { 7229 res.icon = info.icon; 7230 } 7231 res.system = isSystemApp(res.activityInfo.applicationInfo); 7232 return res; 7233 } 7234 7235 @Override 7236 protected void sortResults(List<ResolveInfo> results) { 7237 Collections.sort(results, mResolvePrioritySorter); 7238 } 7239 7240 @Override 7241 protected void dumpFilter(PrintWriter out, String prefix, 7242 PackageParser.ActivityIntentInfo filter) { 7243 out.print(prefix); out.print( 7244 Integer.toHexString(System.identityHashCode(filter.activity))); 7245 out.print(' '); 7246 filter.activity.printComponentShortName(out); 7247 out.print(" filter "); 7248 out.println(Integer.toHexString(System.identityHashCode(filter))); 7249 } 7250 7251// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7252// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7253// final List<ResolveInfo> retList = Lists.newArrayList(); 7254// while (i.hasNext()) { 7255// final ResolveInfo resolveInfo = i.next(); 7256// if (isEnabledLP(resolveInfo.activityInfo)) { 7257// retList.add(resolveInfo); 7258// } 7259// } 7260// return retList; 7261// } 7262 7263 // Keys are String (activity class name), values are Activity. 7264 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7265 = new HashMap<ComponentName, PackageParser.Activity>(); 7266 private int mFlags; 7267 } 7268 7269 private final class ServiceIntentResolver 7270 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7271 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7272 boolean defaultOnly, int userId) { 7273 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7274 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7275 } 7276 7277 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7278 int userId) { 7279 if (!sUserManager.exists(userId)) return null; 7280 mFlags = flags; 7281 return super.queryIntent(intent, resolvedType, 7282 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7283 } 7284 7285 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7286 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7287 if (!sUserManager.exists(userId)) return null; 7288 if (packageServices == null) { 7289 return null; 7290 } 7291 mFlags = flags; 7292 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7293 final int N = packageServices.size(); 7294 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7295 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7296 7297 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7298 for (int i = 0; i < N; ++i) { 7299 intentFilters = packageServices.get(i).intents; 7300 if (intentFilters != null && intentFilters.size() > 0) { 7301 PackageParser.ServiceIntentInfo[] array = 7302 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7303 intentFilters.toArray(array); 7304 listCut.add(array); 7305 } 7306 } 7307 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7308 } 7309 7310 public final void addService(PackageParser.Service s) { 7311 mServices.put(s.getComponentName(), s); 7312 if (DEBUG_SHOW_INFO) { 7313 Log.v(TAG, " " 7314 + (s.info.nonLocalizedLabel != null 7315 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7316 Log.v(TAG, " Class=" + s.info.name); 7317 } 7318 final int NI = s.intents.size(); 7319 int j; 7320 for (j=0; j<NI; j++) { 7321 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7322 if (DEBUG_SHOW_INFO) { 7323 Log.v(TAG, " IntentFilter:"); 7324 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7325 } 7326 if (!intent.debugCheck()) { 7327 Log.w(TAG, "==> For Service " + s.info.name); 7328 } 7329 addFilter(intent); 7330 } 7331 } 7332 7333 public final void removeService(PackageParser.Service s) { 7334 mServices.remove(s.getComponentName()); 7335 if (DEBUG_SHOW_INFO) { 7336 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7337 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7338 Log.v(TAG, " Class=" + s.info.name); 7339 } 7340 final int NI = s.intents.size(); 7341 int j; 7342 for (j=0; j<NI; j++) { 7343 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7344 if (DEBUG_SHOW_INFO) { 7345 Log.v(TAG, " IntentFilter:"); 7346 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7347 } 7348 removeFilter(intent); 7349 } 7350 } 7351 7352 @Override 7353 protected boolean allowFilterResult( 7354 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7355 ServiceInfo filterSi = filter.service.info; 7356 for (int i=dest.size()-1; i>=0; i--) { 7357 ServiceInfo destAi = dest.get(i).serviceInfo; 7358 if (destAi.name == filterSi.name 7359 && destAi.packageName == filterSi.packageName) { 7360 return false; 7361 } 7362 } 7363 return true; 7364 } 7365 7366 @Override 7367 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7368 return new PackageParser.ServiceIntentInfo[size]; 7369 } 7370 7371 @Override 7372 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7373 if (!sUserManager.exists(userId)) return true; 7374 PackageParser.Package p = filter.service.owner; 7375 if (p != null) { 7376 PackageSetting ps = (PackageSetting)p.mExtras; 7377 if (ps != null) { 7378 // System apps are never considered stopped for purposes of 7379 // filtering, because there may be no way for the user to 7380 // actually re-launch them. 7381 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7382 && ps.getStopped(userId); 7383 } 7384 } 7385 return false; 7386 } 7387 7388 @Override 7389 protected boolean isPackageForFilter(String packageName, 7390 PackageParser.ServiceIntentInfo info) { 7391 return packageName.equals(info.service.owner.packageName); 7392 } 7393 7394 @Override 7395 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7396 int match, int userId) { 7397 if (!sUserManager.exists(userId)) return null; 7398 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7399 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7400 return null; 7401 } 7402 final PackageParser.Service service = info.service; 7403 if (mSafeMode && (service.info.applicationInfo.flags 7404 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7405 return null; 7406 } 7407 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7408 if (ps == null) { 7409 return null; 7410 } 7411 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7412 ps.readUserState(userId), userId); 7413 if (si == null) { 7414 return null; 7415 } 7416 final ResolveInfo res = new ResolveInfo(); 7417 res.serviceInfo = si; 7418 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7419 res.filter = filter; 7420 } 7421 res.priority = info.getPriority(); 7422 res.preferredOrder = service.owner.mPreferredOrder; 7423 //System.out.println("Result: " + res.activityInfo.className + 7424 // " = " + res.priority); 7425 res.match = match; 7426 res.isDefault = info.hasDefault; 7427 res.labelRes = info.labelRes; 7428 res.nonLocalizedLabel = info.nonLocalizedLabel; 7429 res.icon = info.icon; 7430 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7431 return res; 7432 } 7433 7434 @Override 7435 protected void sortResults(List<ResolveInfo> results) { 7436 Collections.sort(results, mResolvePrioritySorter); 7437 } 7438 7439 @Override 7440 protected void dumpFilter(PrintWriter out, String prefix, 7441 PackageParser.ServiceIntentInfo filter) { 7442 out.print(prefix); out.print( 7443 Integer.toHexString(System.identityHashCode(filter.service))); 7444 out.print(' '); 7445 filter.service.printComponentShortName(out); 7446 out.print(" filter "); 7447 out.println(Integer.toHexString(System.identityHashCode(filter))); 7448 } 7449 7450// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7451// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7452// final List<ResolveInfo> retList = Lists.newArrayList(); 7453// while (i.hasNext()) { 7454// final ResolveInfo resolveInfo = (ResolveInfo) i; 7455// if (isEnabledLP(resolveInfo.serviceInfo)) { 7456// retList.add(resolveInfo); 7457// } 7458// } 7459// return retList; 7460// } 7461 7462 // Keys are String (activity class name), values are Activity. 7463 private final HashMap<ComponentName, PackageParser.Service> mServices 7464 = new HashMap<ComponentName, PackageParser.Service>(); 7465 private int mFlags; 7466 }; 7467 7468 private final class ProviderIntentResolver 7469 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7470 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7471 boolean defaultOnly, int userId) { 7472 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7473 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7474 } 7475 7476 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7477 int userId) { 7478 if (!sUserManager.exists(userId)) 7479 return null; 7480 mFlags = flags; 7481 return super.queryIntent(intent, resolvedType, 7482 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7483 } 7484 7485 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7486 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7487 if (!sUserManager.exists(userId)) 7488 return null; 7489 if (packageProviders == null) { 7490 return null; 7491 } 7492 mFlags = flags; 7493 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7494 final int N = packageProviders.size(); 7495 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7496 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7497 7498 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7499 for (int i = 0; i < N; ++i) { 7500 intentFilters = packageProviders.get(i).intents; 7501 if (intentFilters != null && intentFilters.size() > 0) { 7502 PackageParser.ProviderIntentInfo[] array = 7503 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7504 intentFilters.toArray(array); 7505 listCut.add(array); 7506 } 7507 } 7508 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7509 } 7510 7511 public final void addProvider(PackageParser.Provider p) { 7512 if (mProviders.containsKey(p.getComponentName())) { 7513 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7514 return; 7515 } 7516 7517 mProviders.put(p.getComponentName(), p); 7518 if (DEBUG_SHOW_INFO) { 7519 Log.v(TAG, " " 7520 + (p.info.nonLocalizedLabel != null 7521 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7522 Log.v(TAG, " Class=" + p.info.name); 7523 } 7524 final int NI = p.intents.size(); 7525 int j; 7526 for (j = 0; j < NI; j++) { 7527 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7528 if (DEBUG_SHOW_INFO) { 7529 Log.v(TAG, " IntentFilter:"); 7530 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7531 } 7532 if (!intent.debugCheck()) { 7533 Log.w(TAG, "==> For Provider " + p.info.name); 7534 } 7535 addFilter(intent); 7536 } 7537 } 7538 7539 public final void removeProvider(PackageParser.Provider p) { 7540 mProviders.remove(p.getComponentName()); 7541 if (DEBUG_SHOW_INFO) { 7542 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7543 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7544 Log.v(TAG, " Class=" + p.info.name); 7545 } 7546 final int NI = p.intents.size(); 7547 int j; 7548 for (j = 0; j < NI; j++) { 7549 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7550 if (DEBUG_SHOW_INFO) { 7551 Log.v(TAG, " IntentFilter:"); 7552 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7553 } 7554 removeFilter(intent); 7555 } 7556 } 7557 7558 @Override 7559 protected boolean allowFilterResult( 7560 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7561 ProviderInfo filterPi = filter.provider.info; 7562 for (int i = dest.size() - 1; i >= 0; i--) { 7563 ProviderInfo destPi = dest.get(i).providerInfo; 7564 if (destPi.name == filterPi.name 7565 && destPi.packageName == filterPi.packageName) { 7566 return false; 7567 } 7568 } 7569 return true; 7570 } 7571 7572 @Override 7573 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7574 return new PackageParser.ProviderIntentInfo[size]; 7575 } 7576 7577 @Override 7578 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7579 if (!sUserManager.exists(userId)) 7580 return true; 7581 PackageParser.Package p = filter.provider.owner; 7582 if (p != null) { 7583 PackageSetting ps = (PackageSetting) p.mExtras; 7584 if (ps != null) { 7585 // System apps are never considered stopped for purposes of 7586 // filtering, because there may be no way for the user to 7587 // actually re-launch them. 7588 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7589 && ps.getStopped(userId); 7590 } 7591 } 7592 return false; 7593 } 7594 7595 @Override 7596 protected boolean isPackageForFilter(String packageName, 7597 PackageParser.ProviderIntentInfo info) { 7598 return packageName.equals(info.provider.owner.packageName); 7599 } 7600 7601 @Override 7602 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7603 int match, int userId) { 7604 if (!sUserManager.exists(userId)) 7605 return null; 7606 final PackageParser.ProviderIntentInfo info = filter; 7607 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7608 return null; 7609 } 7610 final PackageParser.Provider provider = info.provider; 7611 if (mSafeMode && (provider.info.applicationInfo.flags 7612 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7613 return null; 7614 } 7615 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7616 if (ps == null) { 7617 return null; 7618 } 7619 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7620 ps.readUserState(userId), userId); 7621 if (pi == null) { 7622 return null; 7623 } 7624 final ResolveInfo res = new ResolveInfo(); 7625 res.providerInfo = pi; 7626 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7627 res.filter = filter; 7628 } 7629 res.priority = info.getPriority(); 7630 res.preferredOrder = provider.owner.mPreferredOrder; 7631 res.match = match; 7632 res.isDefault = info.hasDefault; 7633 res.labelRes = info.labelRes; 7634 res.nonLocalizedLabel = info.nonLocalizedLabel; 7635 res.icon = info.icon; 7636 res.system = isSystemApp(res.providerInfo.applicationInfo); 7637 return res; 7638 } 7639 7640 @Override 7641 protected void sortResults(List<ResolveInfo> results) { 7642 Collections.sort(results, mResolvePrioritySorter); 7643 } 7644 7645 @Override 7646 protected void dumpFilter(PrintWriter out, String prefix, 7647 PackageParser.ProviderIntentInfo filter) { 7648 out.print(prefix); 7649 out.print( 7650 Integer.toHexString(System.identityHashCode(filter.provider))); 7651 out.print(' '); 7652 filter.provider.printComponentShortName(out); 7653 out.print(" filter "); 7654 out.println(Integer.toHexString(System.identityHashCode(filter))); 7655 } 7656 7657 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7658 = new HashMap<ComponentName, PackageParser.Provider>(); 7659 private int mFlags; 7660 }; 7661 7662 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7663 new Comparator<ResolveInfo>() { 7664 public int compare(ResolveInfo r1, ResolveInfo r2) { 7665 int v1 = r1.priority; 7666 int v2 = r2.priority; 7667 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7668 if (v1 != v2) { 7669 return (v1 > v2) ? -1 : 1; 7670 } 7671 v1 = r1.preferredOrder; 7672 v2 = r2.preferredOrder; 7673 if (v1 != v2) { 7674 return (v1 > v2) ? -1 : 1; 7675 } 7676 if (r1.isDefault != r2.isDefault) { 7677 return r1.isDefault ? -1 : 1; 7678 } 7679 v1 = r1.match; 7680 v2 = r2.match; 7681 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7682 if (v1 != v2) { 7683 return (v1 > v2) ? -1 : 1; 7684 } 7685 if (r1.system != r2.system) { 7686 return r1.system ? -1 : 1; 7687 } 7688 return 0; 7689 } 7690 }; 7691 7692 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7693 new Comparator<ProviderInfo>() { 7694 public int compare(ProviderInfo p1, ProviderInfo p2) { 7695 final int v1 = p1.initOrder; 7696 final int v2 = p2.initOrder; 7697 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7698 } 7699 }; 7700 7701 static final void sendPackageBroadcast(String action, String pkg, 7702 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7703 int[] userIds) { 7704 IActivityManager am = ActivityManagerNative.getDefault(); 7705 if (am != null) { 7706 try { 7707 if (userIds == null) { 7708 userIds = am.getRunningUserIds(); 7709 } 7710 for (int id : userIds) { 7711 final Intent intent = new Intent(action, 7712 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7713 if (extras != null) { 7714 intent.putExtras(extras); 7715 } 7716 if (targetPkg != null) { 7717 intent.setPackage(targetPkg); 7718 } 7719 // Modify the UID when posting to other users 7720 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7721 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7722 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7723 intent.putExtra(Intent.EXTRA_UID, uid); 7724 } 7725 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7726 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7727 if (DEBUG_BROADCASTS) { 7728 RuntimeException here = new RuntimeException("here"); 7729 here.fillInStackTrace(); 7730 Slog.d(TAG, "Sending to user " + id + ": " 7731 + intent.toShortString(false, true, false, false) 7732 + " " + intent.getExtras(), here); 7733 } 7734 am.broadcastIntent(null, intent, null, finishedReceiver, 7735 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7736 finishedReceiver != null, false, id); 7737 } 7738 } catch (RemoteException ex) { 7739 } 7740 } 7741 } 7742 7743 /** 7744 * Check if the external storage media is available. This is true if there 7745 * is a mounted external storage medium or if the external storage is 7746 * emulated. 7747 */ 7748 private boolean isExternalMediaAvailable() { 7749 return mMediaMounted || Environment.isExternalStorageEmulated(); 7750 } 7751 7752 @Override 7753 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7754 // writer 7755 synchronized (mPackages) { 7756 if (!isExternalMediaAvailable()) { 7757 // If the external storage is no longer mounted at this point, 7758 // the caller may not have been able to delete all of this 7759 // packages files and can not delete any more. Bail. 7760 return null; 7761 } 7762 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7763 if (lastPackage != null) { 7764 pkgs.remove(lastPackage); 7765 } 7766 if (pkgs.size() > 0) { 7767 return pkgs.get(0); 7768 } 7769 } 7770 return null; 7771 } 7772 7773 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7774 if (false) { 7775 RuntimeException here = new RuntimeException("here"); 7776 here.fillInStackTrace(); 7777 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7778 + " andCode=" + andCode, here); 7779 } 7780 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7781 userId, andCode ? 1 : 0, packageName)); 7782 } 7783 7784 void startCleaningPackages() { 7785 // reader 7786 synchronized (mPackages) { 7787 if (!isExternalMediaAvailable()) { 7788 return; 7789 } 7790 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7791 return; 7792 } 7793 } 7794 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7795 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7796 IActivityManager am = ActivityManagerNative.getDefault(); 7797 if (am != null) { 7798 try { 7799 am.startService(null, intent, null, UserHandle.USER_OWNER); 7800 } catch (RemoteException e) { 7801 } 7802 } 7803 } 7804 7805 @Override 7806 public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags, 7807 String installerPackageName, VerificationParams verificationParams, 7808 String packageAbiOverride) { 7809 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7810 null); 7811 7812 final File originFile = new File(originPath); 7813 final int uid = Binder.getCallingUid(); 7814 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7815 try { 7816 if (observer != null) { 7817 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7818 } 7819 } catch (RemoteException re) { 7820 } 7821 return; 7822 } 7823 7824 UserHandle user; 7825 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7826 user = UserHandle.ALL; 7827 } else { 7828 user = new UserHandle(UserHandle.getUserId(uid)); 7829 } 7830 7831 final int filteredFlags; 7832 if (uid == Process.SHELL_UID || uid == 0) { 7833 if (DEBUG_INSTALL) { 7834 Slog.v(TAG, "Install from ADB"); 7835 } 7836 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7837 } else { 7838 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7839 } 7840 7841 verificationParams.setInstallerUid(uid); 7842 7843 final Message msg = mHandler.obtainMessage(INIT_COPY); 7844 msg.obj = new InstallParams(originFile, false, observer, filteredFlags, 7845 installerPackageName, verificationParams, user, packageAbiOverride); 7846 mHandler.sendMessage(msg); 7847 } 7848 7849 void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer, 7850 PackageInstaller.SessionParams params, String installerPackageName, int installerUid, 7851 UserHandle user) { 7852 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7853 params.referrerUri, installerUid, null); 7854 7855 final Message msg = mHandler.obtainMessage(INIT_COPY); 7856 msg.obj = new InstallParams(stageDir, true, observer, params.installFlags, 7857 installerPackageName, verifParams, user, params.abiOverride); 7858 mHandler.sendMessage(msg); 7859 } 7860 7861 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7862 Bundle extras = new Bundle(1); 7863 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7864 7865 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7866 packageName, extras, null, null, new int[] {userId}); 7867 try { 7868 IActivityManager am = ActivityManagerNative.getDefault(); 7869 final boolean isSystem = 7870 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7871 if (isSystem && am.isUserRunning(userId, false)) { 7872 // The just-installed/enabled app is bundled on the system, so presumed 7873 // to be able to run automatically without needing an explicit launch. 7874 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7875 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7876 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7877 .setPackage(packageName); 7878 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7879 android.app.AppOpsManager.OP_NONE, false, false, userId); 7880 } 7881 } catch (RemoteException e) { 7882 // shouldn't happen 7883 Slog.w(TAG, "Unable to bootstrap installed package", e); 7884 } 7885 } 7886 7887 @Override 7888 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7889 int userId) { 7890 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7891 PackageSetting pkgSetting; 7892 final int uid = Binder.getCallingUid(); 7893 if (UserHandle.getUserId(uid) != userId) { 7894 mContext.enforceCallingOrSelfPermission( 7895 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7896 "setApplicationHiddenSetting for user " + userId); 7897 } 7898 7899 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7900 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7901 return false; 7902 } 7903 7904 long callingId = Binder.clearCallingIdentity(); 7905 try { 7906 boolean sendAdded = false; 7907 boolean sendRemoved = false; 7908 // writer 7909 synchronized (mPackages) { 7910 pkgSetting = mSettings.mPackages.get(packageName); 7911 if (pkgSetting == null) { 7912 return false; 7913 } 7914 if (pkgSetting.getHidden(userId) != hidden) { 7915 pkgSetting.setHidden(hidden, userId); 7916 mSettings.writePackageRestrictionsLPr(userId); 7917 if (hidden) { 7918 sendRemoved = true; 7919 } else { 7920 sendAdded = true; 7921 } 7922 } 7923 } 7924 if (sendAdded) { 7925 sendPackageAddedForUser(packageName, pkgSetting, userId); 7926 return true; 7927 } 7928 if (sendRemoved) { 7929 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7930 "hiding pkg"); 7931 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7932 } 7933 } finally { 7934 Binder.restoreCallingIdentity(callingId); 7935 } 7936 return false; 7937 } 7938 7939 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7940 int userId) { 7941 final PackageRemovedInfo info = new PackageRemovedInfo(); 7942 info.removedPackage = packageName; 7943 info.removedUsers = new int[] {userId}; 7944 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7945 info.sendBroadcast(false, false, false); 7946 } 7947 7948 /** 7949 * Returns true if application is not found or there was an error. Otherwise it returns 7950 * the hidden state of the package for the given user. 7951 */ 7952 @Override 7953 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 7954 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7955 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7956 "getApplicationHidden for user " + userId); 7957 PackageSetting pkgSetting; 7958 long callingId = Binder.clearCallingIdentity(); 7959 try { 7960 // writer 7961 synchronized (mPackages) { 7962 pkgSetting = mSettings.mPackages.get(packageName); 7963 if (pkgSetting == null) { 7964 return true; 7965 } 7966 return pkgSetting.getHidden(userId); 7967 } 7968 } finally { 7969 Binder.restoreCallingIdentity(callingId); 7970 } 7971 } 7972 7973 /** 7974 * @hide 7975 */ 7976 @Override 7977 public int installExistingPackageAsUser(String packageName, int userId) { 7978 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7979 null); 7980 PackageSetting pkgSetting; 7981 final int uid = Binder.getCallingUid(); 7982 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7983 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7984 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7985 } 7986 7987 long callingId = Binder.clearCallingIdentity(); 7988 try { 7989 boolean sendAdded = false; 7990 Bundle extras = new Bundle(1); 7991 7992 // writer 7993 synchronized (mPackages) { 7994 pkgSetting = mSettings.mPackages.get(packageName); 7995 if (pkgSetting == null) { 7996 return PackageManager.INSTALL_FAILED_INVALID_URI; 7997 } 7998 if (!pkgSetting.getInstalled(userId)) { 7999 pkgSetting.setInstalled(true, userId); 8000 pkgSetting.setHidden(false, userId); 8001 mSettings.writePackageRestrictionsLPr(userId); 8002 sendAdded = true; 8003 } 8004 } 8005 8006 if (sendAdded) { 8007 sendPackageAddedForUser(packageName, pkgSetting, userId); 8008 } 8009 } finally { 8010 Binder.restoreCallingIdentity(callingId); 8011 } 8012 8013 return PackageManager.INSTALL_SUCCEEDED; 8014 } 8015 8016 boolean isUserRestricted(int userId, String restrictionKey) { 8017 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8018 if (restrictions.getBoolean(restrictionKey, false)) { 8019 Log.w(TAG, "User is restricted: " + restrictionKey); 8020 return true; 8021 } 8022 return false; 8023 } 8024 8025 @Override 8026 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8027 mContext.enforceCallingOrSelfPermission( 8028 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8029 "Only package verification agents can verify applications"); 8030 8031 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8032 final PackageVerificationResponse response = new PackageVerificationResponse( 8033 verificationCode, Binder.getCallingUid()); 8034 msg.arg1 = id; 8035 msg.obj = response; 8036 mHandler.sendMessage(msg); 8037 } 8038 8039 @Override 8040 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8041 long millisecondsToDelay) { 8042 mContext.enforceCallingOrSelfPermission( 8043 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8044 "Only package verification agents can extend verification timeouts"); 8045 8046 final PackageVerificationState state = mPendingVerification.get(id); 8047 final PackageVerificationResponse response = new PackageVerificationResponse( 8048 verificationCodeAtTimeout, Binder.getCallingUid()); 8049 8050 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8051 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8052 } 8053 if (millisecondsToDelay < 0) { 8054 millisecondsToDelay = 0; 8055 } 8056 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8057 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8058 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8059 } 8060 8061 if ((state != null) && !state.timeoutExtended()) { 8062 state.extendTimeout(); 8063 8064 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8065 msg.arg1 = id; 8066 msg.obj = response; 8067 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8068 } 8069 } 8070 8071 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8072 int verificationCode, UserHandle user) { 8073 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8074 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8075 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8076 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8077 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8078 8079 mContext.sendBroadcastAsUser(intent, user, 8080 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8081 } 8082 8083 private ComponentName matchComponentForVerifier(String packageName, 8084 List<ResolveInfo> receivers) { 8085 ActivityInfo targetReceiver = null; 8086 8087 final int NR = receivers.size(); 8088 for (int i = 0; i < NR; i++) { 8089 final ResolveInfo info = receivers.get(i); 8090 if (info.activityInfo == null) { 8091 continue; 8092 } 8093 8094 if (packageName.equals(info.activityInfo.packageName)) { 8095 targetReceiver = info.activityInfo; 8096 break; 8097 } 8098 } 8099 8100 if (targetReceiver == null) { 8101 return null; 8102 } 8103 8104 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8105 } 8106 8107 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8108 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8109 if (pkgInfo.verifiers.length == 0) { 8110 return null; 8111 } 8112 8113 final int N = pkgInfo.verifiers.length; 8114 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8115 for (int i = 0; i < N; i++) { 8116 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8117 8118 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8119 receivers); 8120 if (comp == null) { 8121 continue; 8122 } 8123 8124 final int verifierUid = getUidForVerifier(verifierInfo); 8125 if (verifierUid == -1) { 8126 continue; 8127 } 8128 8129 if (DEBUG_VERIFY) { 8130 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8131 + " with the correct signature"); 8132 } 8133 sufficientVerifiers.add(comp); 8134 verificationState.addSufficientVerifier(verifierUid); 8135 } 8136 8137 return sufficientVerifiers; 8138 } 8139 8140 private int getUidForVerifier(VerifierInfo verifierInfo) { 8141 synchronized (mPackages) { 8142 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8143 if (pkg == null) { 8144 return -1; 8145 } else if (pkg.mSignatures.length != 1) { 8146 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8147 + " has more than one signature; ignoring"); 8148 return -1; 8149 } 8150 8151 /* 8152 * If the public key of the package's signature does not match 8153 * our expected public key, then this is a different package and 8154 * we should skip. 8155 */ 8156 8157 final byte[] expectedPublicKey; 8158 try { 8159 final Signature verifierSig = pkg.mSignatures[0]; 8160 final PublicKey publicKey = verifierSig.getPublicKey(); 8161 expectedPublicKey = publicKey.getEncoded(); 8162 } catch (CertificateException e) { 8163 return -1; 8164 } 8165 8166 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8167 8168 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8169 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8170 + " does not have the expected public key; ignoring"); 8171 return -1; 8172 } 8173 8174 return pkg.applicationInfo.uid; 8175 } 8176 } 8177 8178 @Override 8179 public void finishPackageInstall(int token) { 8180 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8181 8182 if (DEBUG_INSTALL) { 8183 Slog.v(TAG, "BM finishing package install for " + token); 8184 } 8185 8186 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8187 mHandler.sendMessage(msg); 8188 } 8189 8190 /** 8191 * Get the verification agent timeout. 8192 * 8193 * @return verification timeout in milliseconds 8194 */ 8195 private long getVerificationTimeout() { 8196 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8197 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8198 DEFAULT_VERIFICATION_TIMEOUT); 8199 } 8200 8201 /** 8202 * Get the default verification agent response code. 8203 * 8204 * @return default verification response code 8205 */ 8206 private int getDefaultVerificationResponse() { 8207 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8208 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8209 DEFAULT_VERIFICATION_RESPONSE); 8210 } 8211 8212 /** 8213 * Check whether or not package verification has been enabled. 8214 * 8215 * @return true if verification should be performed 8216 */ 8217 private boolean isVerificationEnabled(int userId, int flags) { 8218 if (!DEFAULT_VERIFY_ENABLE) { 8219 return false; 8220 } 8221 8222 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8223 8224 // Check if installing from ADB 8225 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8226 // Do not run verification in a test harness environment 8227 if (ActivityManager.isRunningInTestHarness()) { 8228 return false; 8229 } 8230 if (ensureVerifyAppsEnabled) { 8231 return true; 8232 } 8233 // Check if the developer does not want package verification for ADB installs 8234 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8235 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8236 return false; 8237 } 8238 } 8239 8240 if (ensureVerifyAppsEnabled) { 8241 return true; 8242 } 8243 8244 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8245 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8246 } 8247 8248 /** 8249 * Get the "allow unknown sources" setting. 8250 * 8251 * @return the current "allow unknown sources" setting 8252 */ 8253 private int getUnknownSourcesSettings() { 8254 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8255 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8256 -1); 8257 } 8258 8259 @Override 8260 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8261 final int uid = Binder.getCallingUid(); 8262 // writer 8263 synchronized (mPackages) { 8264 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8265 if (targetPackageSetting == null) { 8266 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8267 } 8268 8269 PackageSetting installerPackageSetting; 8270 if (installerPackageName != null) { 8271 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8272 if (installerPackageSetting == null) { 8273 throw new IllegalArgumentException("Unknown installer package: " 8274 + installerPackageName); 8275 } 8276 } else { 8277 installerPackageSetting = null; 8278 } 8279 8280 Signature[] callerSignature; 8281 Object obj = mSettings.getUserIdLPr(uid); 8282 if (obj != null) { 8283 if (obj instanceof SharedUserSetting) { 8284 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8285 } else if (obj instanceof PackageSetting) { 8286 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8287 } else { 8288 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8289 } 8290 } else { 8291 throw new SecurityException("Unknown calling uid " + uid); 8292 } 8293 8294 // Verify: can't set installerPackageName to a package that is 8295 // not signed with the same cert as the caller. 8296 if (installerPackageSetting != null) { 8297 if (compareSignatures(callerSignature, 8298 installerPackageSetting.signatures.mSignatures) 8299 != PackageManager.SIGNATURE_MATCH) { 8300 throw new SecurityException( 8301 "Caller does not have same cert as new installer package " 8302 + installerPackageName); 8303 } 8304 } 8305 8306 // Verify: if target already has an installer package, it must 8307 // be signed with the same cert as the caller. 8308 if (targetPackageSetting.installerPackageName != null) { 8309 PackageSetting setting = mSettings.mPackages.get( 8310 targetPackageSetting.installerPackageName); 8311 // If the currently set package isn't valid, then it's always 8312 // okay to change it. 8313 if (setting != null) { 8314 if (compareSignatures(callerSignature, 8315 setting.signatures.mSignatures) 8316 != PackageManager.SIGNATURE_MATCH) { 8317 throw new SecurityException( 8318 "Caller does not have same cert as old installer package " 8319 + targetPackageSetting.installerPackageName); 8320 } 8321 } 8322 } 8323 8324 // Okay! 8325 targetPackageSetting.installerPackageName = installerPackageName; 8326 scheduleWriteSettingsLocked(); 8327 } 8328 } 8329 8330 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8331 // Queue up an async operation since the package installation may take a little while. 8332 mHandler.post(new Runnable() { 8333 public void run() { 8334 mHandler.removeCallbacks(this); 8335 // Result object to be returned 8336 PackageInstalledInfo res = new PackageInstalledInfo(); 8337 res.returnCode = currentStatus; 8338 res.uid = -1; 8339 res.pkg = null; 8340 res.removedInfo = new PackageRemovedInfo(); 8341 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8342 args.doPreInstall(res.returnCode); 8343 synchronized (mInstallLock) { 8344 installPackageLI(args, true, res); 8345 } 8346 args.doPostInstall(res.returnCode, res.uid); 8347 } 8348 8349 // A restore should be performed at this point if (a) the install 8350 // succeeded, (b) the operation is not an update, and (c) the new 8351 // package has not opted out of backup participation. 8352 final boolean update = res.removedInfo.removedPackage != null; 8353 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8354 boolean doRestore = !update 8355 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8356 8357 // Set up the post-install work request bookkeeping. This will be used 8358 // and cleaned up by the post-install event handling regardless of whether 8359 // there's a restore pass performed. Token values are >= 1. 8360 int token; 8361 if (mNextInstallToken < 0) mNextInstallToken = 1; 8362 token = mNextInstallToken++; 8363 8364 PostInstallData data = new PostInstallData(args, res); 8365 mRunningInstalls.put(token, data); 8366 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8367 8368 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8369 // Pass responsibility to the Backup Manager. It will perform a 8370 // restore if appropriate, then pass responsibility back to the 8371 // Package Manager to run the post-install observer callbacks 8372 // and broadcasts. 8373 IBackupManager bm = IBackupManager.Stub.asInterface( 8374 ServiceManager.getService(Context.BACKUP_SERVICE)); 8375 if (bm != null) { 8376 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8377 + " to BM for possible restore"); 8378 try { 8379 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8380 } catch (RemoteException e) { 8381 // can't happen; the backup manager is local 8382 } catch (Exception e) { 8383 Slog.e(TAG, "Exception trying to enqueue restore", e); 8384 doRestore = false; 8385 } 8386 } else { 8387 Slog.e(TAG, "Backup Manager not found!"); 8388 doRestore = false; 8389 } 8390 } 8391 8392 if (!doRestore) { 8393 // No restore possible, or the Backup Manager was mysteriously not 8394 // available -- just fire the post-install work request directly. 8395 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8396 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8397 mHandler.sendMessage(msg); 8398 } 8399 } 8400 }); 8401 } 8402 8403 private abstract class HandlerParams { 8404 private static final int MAX_RETRIES = 4; 8405 8406 /** 8407 * Number of times startCopy() has been attempted and had a non-fatal 8408 * error. 8409 */ 8410 private int mRetries = 0; 8411 8412 /** User handle for the user requesting the information or installation. */ 8413 private final UserHandle mUser; 8414 8415 HandlerParams(UserHandle user) { 8416 mUser = user; 8417 } 8418 8419 UserHandle getUser() { 8420 return mUser; 8421 } 8422 8423 final boolean startCopy() { 8424 boolean res; 8425 try { 8426 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8427 8428 if (++mRetries > MAX_RETRIES) { 8429 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8430 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8431 handleServiceError(); 8432 return false; 8433 } else { 8434 handleStartCopy(); 8435 res = true; 8436 } 8437 } catch (RemoteException e) { 8438 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8439 mHandler.sendEmptyMessage(MCS_RECONNECT); 8440 res = false; 8441 } 8442 handleReturnCode(); 8443 return res; 8444 } 8445 8446 final void serviceError() { 8447 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8448 handleServiceError(); 8449 handleReturnCode(); 8450 } 8451 8452 abstract void handleStartCopy() throws RemoteException; 8453 abstract void handleServiceError(); 8454 abstract void handleReturnCode(); 8455 } 8456 8457 class MeasureParams extends HandlerParams { 8458 private final PackageStats mStats; 8459 private boolean mSuccess; 8460 8461 private final IPackageStatsObserver mObserver; 8462 8463 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8464 super(new UserHandle(stats.userHandle)); 8465 mObserver = observer; 8466 mStats = stats; 8467 } 8468 8469 @Override 8470 public String toString() { 8471 return "MeasureParams{" 8472 + Integer.toHexString(System.identityHashCode(this)) 8473 + " " + mStats.packageName + "}"; 8474 } 8475 8476 @Override 8477 void handleStartCopy() throws RemoteException { 8478 synchronized (mInstallLock) { 8479 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8480 } 8481 8482 if (mSuccess) { 8483 final boolean mounted; 8484 if (Environment.isExternalStorageEmulated()) { 8485 mounted = true; 8486 } else { 8487 final String status = Environment.getExternalStorageState(); 8488 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8489 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8490 } 8491 8492 if (mounted) { 8493 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8494 8495 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8496 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8497 8498 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8499 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8500 8501 // Always subtract cache size, since it's a subdirectory 8502 mStats.externalDataSize -= mStats.externalCacheSize; 8503 8504 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8505 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8506 8507 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8508 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8509 } 8510 } 8511 } 8512 8513 @Override 8514 void handleReturnCode() { 8515 if (mObserver != null) { 8516 try { 8517 mObserver.onGetStatsCompleted(mStats, mSuccess); 8518 } catch (RemoteException e) { 8519 Slog.i(TAG, "Observer no longer exists."); 8520 } 8521 } 8522 } 8523 8524 @Override 8525 void handleServiceError() { 8526 Slog.e(TAG, "Could not measure application " + mStats.packageName 8527 + " external storage"); 8528 } 8529 } 8530 8531 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8532 throws RemoteException { 8533 long result = 0; 8534 for (File path : paths) { 8535 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8536 } 8537 return result; 8538 } 8539 8540 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8541 for (File path : paths) { 8542 try { 8543 mcs.clearDirectory(path.getAbsolutePath()); 8544 } catch (RemoteException e) { 8545 } 8546 } 8547 } 8548 8549 class InstallParams extends HandlerParams { 8550 /** 8551 * Location where install is coming from, before it has been 8552 * copied/renamed into place. This could be a single monolithic APK 8553 * file, or a cluster directory. This location may be untrusted. 8554 */ 8555 final File originFile; 8556 8557 /** 8558 * Flag indicating that {@link #originFile} has already been staged, 8559 * meaning downstream users don't need to defensively copy the contents. 8560 */ 8561 boolean originStaged; 8562 8563 final IPackageInstallObserver2 observer; 8564 int flags; 8565 final String installerPackageName; 8566 final VerificationParams verificationParams; 8567 private InstallArgs mArgs; 8568 private int mRet; 8569 final String packageAbiOverride; 8570 boolean multiArch; 8571 8572 InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 8573 int flags, String installerPackageName, VerificationParams verificationParams, 8574 UserHandle user, String packageAbiOverride) { 8575 super(user); 8576 this.originFile = Preconditions.checkNotNull(originFile); 8577 this.originStaged = originStaged; 8578 this.observer = observer; 8579 this.flags = flags; 8580 this.installerPackageName = installerPackageName; 8581 this.verificationParams = verificationParams; 8582 this.packageAbiOverride = packageAbiOverride; 8583 } 8584 8585 @Override 8586 public String toString() { 8587 return "InstallParams{" 8588 + Integer.toHexString(System.identityHashCode(this)) 8589 + " " + originFile + "}"; 8590 } 8591 8592 public ManifestDigest getManifestDigest() { 8593 if (verificationParams == null) { 8594 return null; 8595 } 8596 return verificationParams.getManifestDigest(); 8597 } 8598 8599 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8600 String packageName = pkgLite.packageName; 8601 int installLocation = pkgLite.installLocation; 8602 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8603 // reader 8604 synchronized (mPackages) { 8605 PackageParser.Package pkg = mPackages.get(packageName); 8606 if (pkg != null) { 8607 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8608 // Check for downgrading. 8609 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8610 if (pkgLite.versionCode < pkg.mVersionCode) { 8611 Slog.w(TAG, "Can't install update of " + packageName 8612 + " update version " + pkgLite.versionCode 8613 + " is older than installed version " 8614 + pkg.mVersionCode); 8615 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8616 } 8617 } 8618 // Check for updated system application. 8619 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8620 if (onSd) { 8621 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8622 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8623 } 8624 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8625 } else { 8626 if (onSd) { 8627 // Install flag overrides everything. 8628 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8629 } 8630 // If current upgrade specifies particular preference 8631 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8632 // Application explicitly specified internal. 8633 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8634 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8635 // App explictly prefers external. Let policy decide 8636 } else { 8637 // Prefer previous location 8638 if (isExternal(pkg)) { 8639 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8640 } 8641 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8642 } 8643 } 8644 } else { 8645 // Invalid install. Return error code 8646 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8647 } 8648 } 8649 } 8650 // All the special cases have been taken care of. 8651 // Return result based on recommended install location. 8652 if (onSd) { 8653 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8654 } 8655 return pkgLite.recommendedInstallLocation; 8656 } 8657 8658 private long getMemoryLowThreshold() { 8659 final DeviceStorageMonitorInternal 8660 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8661 if (dsm == null) { 8662 return 0L; 8663 } 8664 return dsm.getMemoryLowThreshold(); 8665 } 8666 8667 /* 8668 * Invoke remote method to get package information and install 8669 * location values. Override install location based on default 8670 * policy if needed and then create install arguments based 8671 * on the install location. 8672 */ 8673 public void handleStartCopy() throws RemoteException { 8674 int ret = PackageManager.INSTALL_SUCCEEDED; 8675 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8676 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8677 PackageInfoLite pkgLite = null; 8678 8679 if (onInt && onSd) { 8680 // Check if both bits are set. 8681 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8682 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8683 } else { 8684 final long lowThreshold = getMemoryLowThreshold(); 8685 if (lowThreshold == 0L) { 8686 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8687 } 8688 8689 // Remote call to find out default install location 8690 final String originPath = originFile.getAbsolutePath(); 8691 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold, 8692 packageAbiOverride); 8693 // Keep track of whether this package is a multiArch package until 8694 // we perform a full scan of it. We need to do this because we might 8695 // end up extracting the package shared libraries before we perform 8696 // a full scan. 8697 multiArch = pkgLite.multiArch; 8698 8699 /* 8700 * If we have too little free space, try to free cache 8701 * before giving up. 8702 */ 8703 if (pkgLite.recommendedInstallLocation 8704 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8705 final long size = mContainerService.calculateInstalledSize( 8706 originPath, isForwardLocked(), packageAbiOverride); 8707 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8708 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, 8709 lowThreshold, packageAbiOverride); 8710 } 8711 /* 8712 * The cache free must have deleted the file we 8713 * downloaded to install. 8714 * 8715 * TODO: fix the "freeCache" call to not delete 8716 * the file we care about. 8717 */ 8718 if (pkgLite.recommendedInstallLocation 8719 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8720 pkgLite.recommendedInstallLocation 8721 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8722 } 8723 } 8724 } 8725 8726 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8727 int loc = pkgLite.recommendedInstallLocation; 8728 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8729 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8730 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8731 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8732 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8733 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8734 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8735 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8736 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8737 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8738 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8739 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8740 } else { 8741 // Override with defaults if needed. 8742 loc = installLocationPolicy(pkgLite, flags); 8743 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8744 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8745 } else if (!onSd && !onInt) { 8746 // Override install location with flags 8747 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8748 // Set the flag to install on external media. 8749 flags |= PackageManager.INSTALL_EXTERNAL; 8750 flags &= ~PackageManager.INSTALL_INTERNAL; 8751 } else { 8752 // Make sure the flag for installing on external 8753 // media is unset 8754 flags |= PackageManager.INSTALL_INTERNAL; 8755 flags &= ~PackageManager.INSTALL_EXTERNAL; 8756 } 8757 } 8758 } 8759 } 8760 8761 final InstallArgs args = createInstallArgs(this); 8762 mArgs = args; 8763 8764 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8765 /* 8766 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8767 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8768 */ 8769 int userIdentifier = getUser().getIdentifier(); 8770 if (userIdentifier == UserHandle.USER_ALL 8771 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8772 userIdentifier = UserHandle.USER_OWNER; 8773 } 8774 8775 /* 8776 * Determine if we have any installed package verifiers. If we 8777 * do, then we'll defer to them to verify the packages. 8778 */ 8779 final int requiredUid = mRequiredVerifierPackage == null ? -1 8780 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8781 if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) { 8782 // TODO: send verifier the install session instead of uri 8783 final Intent verification = new Intent( 8784 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8785 verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE); 8786 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8787 8788 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8789 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8790 0 /* TODO: Which userId? */); 8791 8792 if (DEBUG_VERIFY) { 8793 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8794 + verification.toString() + " with " + pkgLite.verifiers.length 8795 + " optional verifiers"); 8796 } 8797 8798 final int verificationId = mPendingVerificationToken++; 8799 8800 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8801 8802 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8803 installerPackageName); 8804 8805 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8806 8807 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8808 pkgLite.packageName); 8809 8810 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8811 pkgLite.versionCode); 8812 8813 if (verificationParams != null) { 8814 if (verificationParams.getVerificationURI() != null) { 8815 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8816 verificationParams.getVerificationURI()); 8817 } 8818 if (verificationParams.getOriginatingURI() != null) { 8819 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8820 verificationParams.getOriginatingURI()); 8821 } 8822 if (verificationParams.getReferrer() != null) { 8823 verification.putExtra(Intent.EXTRA_REFERRER, 8824 verificationParams.getReferrer()); 8825 } 8826 if (verificationParams.getOriginatingUid() >= 0) { 8827 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8828 verificationParams.getOriginatingUid()); 8829 } 8830 if (verificationParams.getInstallerUid() >= 0) { 8831 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8832 verificationParams.getInstallerUid()); 8833 } 8834 } 8835 8836 final PackageVerificationState verificationState = new PackageVerificationState( 8837 requiredUid, args); 8838 8839 mPendingVerification.append(verificationId, verificationState); 8840 8841 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8842 receivers, verificationState); 8843 8844 /* 8845 * If any sufficient verifiers were listed in the package 8846 * manifest, attempt to ask them. 8847 */ 8848 if (sufficientVerifiers != null) { 8849 final int N = sufficientVerifiers.size(); 8850 if (N == 0) { 8851 Slog.i(TAG, "Additional verifiers required, but none installed."); 8852 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8853 } else { 8854 for (int i = 0; i < N; i++) { 8855 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8856 8857 final Intent sufficientIntent = new Intent(verification); 8858 sufficientIntent.setComponent(verifierComponent); 8859 8860 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8861 } 8862 } 8863 } 8864 8865 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8866 mRequiredVerifierPackage, receivers); 8867 if (ret == PackageManager.INSTALL_SUCCEEDED 8868 && mRequiredVerifierPackage != null) { 8869 /* 8870 * Send the intent to the required verification agent, 8871 * but only start the verification timeout after the 8872 * target BroadcastReceivers have run. 8873 */ 8874 verification.setComponent(requiredVerifierComponent); 8875 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8876 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8877 new BroadcastReceiver() { 8878 @Override 8879 public void onReceive(Context context, Intent intent) { 8880 final Message msg = mHandler 8881 .obtainMessage(CHECK_PENDING_VERIFICATION); 8882 msg.arg1 = verificationId; 8883 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8884 } 8885 }, null, 0, null, null); 8886 8887 /* 8888 * We don't want the copy to proceed until verification 8889 * succeeds, so null out this field. 8890 */ 8891 mArgs = null; 8892 } 8893 } else { 8894 /* 8895 * No package verification is enabled, so immediately start 8896 * the remote call to initiate copy using temporary file. 8897 */ 8898 ret = args.copyApk(mContainerService, true); 8899 } 8900 } 8901 8902 mRet = ret; 8903 } 8904 8905 @Override 8906 void handleReturnCode() { 8907 // If mArgs is null, then MCS couldn't be reached. When it 8908 // reconnects, it will try again to install. At that point, this 8909 // will succeed. 8910 if (mArgs != null) { 8911 processPendingInstall(mArgs, mRet); 8912 } 8913 } 8914 8915 @Override 8916 void handleServiceError() { 8917 mArgs = createInstallArgs(this); 8918 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8919 } 8920 8921 public boolean isForwardLocked() { 8922 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8923 } 8924 } 8925 8926 /* 8927 * Utility class used in movePackage api. 8928 * srcArgs and targetArgs are not set for invalid flags and make 8929 * sure to do null checks when invoking methods on them. 8930 * We probably want to return ErrorPrams for both failed installs 8931 * and moves. 8932 */ 8933 class MoveParams extends HandlerParams { 8934 final IPackageMoveObserver observer; 8935 final int flags; 8936 final String packageName; 8937 final InstallArgs srcArgs; 8938 final InstallArgs targetArgs; 8939 int uid; 8940 int mRet; 8941 8942 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8943 String packageName, String[] instructionSets, int uid, UserHandle user, 8944 boolean isMultiArch) { 8945 super(user); 8946 this.srcArgs = srcArgs; 8947 this.observer = observer; 8948 this.flags = flags; 8949 this.packageName = packageName; 8950 this.uid = uid; 8951 if (srcArgs != null) { 8952 final String codePath = srcArgs.getCodePath(); 8953 targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, 8954 instructionSets, isMultiArch); 8955 } else { 8956 targetArgs = null; 8957 } 8958 } 8959 8960 @Override 8961 public String toString() { 8962 return "MoveParams{" 8963 + Integer.toHexString(System.identityHashCode(this)) 8964 + " " + packageName + "}"; 8965 } 8966 8967 public void handleStartCopy() throws RemoteException { 8968 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8969 // Check for storage space on target medium 8970 if (!targetArgs.checkFreeStorage(mContainerService)) { 8971 Log.w(TAG, "Insufficient storage to install"); 8972 return; 8973 } 8974 8975 mRet = srcArgs.doPreCopy(); 8976 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8977 return; 8978 } 8979 8980 mRet = targetArgs.copyApk(mContainerService, false); 8981 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8982 srcArgs.doPostCopy(uid); 8983 return; 8984 } 8985 8986 mRet = srcArgs.doPostCopy(uid); 8987 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8988 return; 8989 } 8990 8991 mRet = targetArgs.doPreInstall(mRet); 8992 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8993 return; 8994 } 8995 8996 if (DEBUG_SD_INSTALL) { 8997 StringBuilder builder = new StringBuilder(); 8998 if (srcArgs != null) { 8999 builder.append("src: "); 9000 builder.append(srcArgs.getCodePath()); 9001 } 9002 if (targetArgs != null) { 9003 builder.append(" target : "); 9004 builder.append(targetArgs.getCodePath()); 9005 } 9006 Log.i(TAG, builder.toString()); 9007 } 9008 } 9009 9010 @Override 9011 void handleReturnCode() { 9012 targetArgs.doPostInstall(mRet, uid); 9013 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 9014 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 9015 currentStatus = PackageManager.MOVE_SUCCEEDED; 9016 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 9017 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 9018 } 9019 processPendingMove(this, currentStatus); 9020 } 9021 9022 @Override 9023 void handleServiceError() { 9024 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9025 } 9026 } 9027 9028 /** 9029 * Used during creation of InstallArgs 9030 * 9031 * @param flags package installation flags 9032 * @return true if should be installed on external storage 9033 */ 9034 private static boolean installOnSd(int flags) { 9035 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 9036 return false; 9037 } 9038 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 9039 return true; 9040 } 9041 return false; 9042 } 9043 9044 /** 9045 * Used during creation of InstallArgs 9046 * 9047 * @param flags package installation flags 9048 * @return true if should be installed as forward locked 9049 */ 9050 private static boolean installForwardLocked(int flags) { 9051 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9052 } 9053 9054 private InstallArgs createInstallArgs(InstallParams params) { 9055 // TODO: extend to support incoming zero-copy locations 9056 9057 if (installOnSd(params.flags) || params.isForwardLocked()) { 9058 return new AsecInstallArgs(params); 9059 } else { 9060 return new FileInstallArgs(params); 9061 } 9062 } 9063 9064 /** 9065 * Create args that describe an existing installed package. Typically used 9066 * when cleaning up old installs, or used as a move source. 9067 */ 9068 private InstallArgs createInstallArgsForExisting(int flags, String codePath, 9069 String resourcePath, String nativeLibraryRoot, String[] instructionSets, 9070 boolean isMultiArch) { 9071 final boolean isInAsec; 9072 if (installOnSd(flags)) { 9073 /* Apps on SD card are always in ASEC containers. */ 9074 isInAsec = true; 9075 } else if (installForwardLocked(flags) 9076 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9077 /* 9078 * Forward-locked apps are only in ASEC containers if they're the 9079 * new style 9080 */ 9081 isInAsec = true; 9082 } else { 9083 isInAsec = false; 9084 } 9085 9086 if (isInAsec) { 9087 return new AsecInstallArgs(codePath, instructionSets, 9088 installOnSd(flags), installForwardLocked(flags), isMultiArch); 9089 } else { 9090 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9091 instructionSets, isMultiArch); 9092 } 9093 } 9094 9095 private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName, 9096 String[] instructionSets, boolean isMultiArch) { 9097 final File codeFile = new File(codePath); 9098 if (installOnSd(flags) || installForwardLocked(flags)) { 9099 String cid = getNextCodePath(codePath, pkgName, "/" 9100 + AsecInstallArgs.RES_FILE_NAME); 9101 return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags), 9102 installForwardLocked(flags), isMultiArch); 9103 } else { 9104 return new FileInstallArgs(codeFile, instructionSets, isMultiArch); 9105 } 9106 } 9107 9108 static abstract class InstallArgs { 9109 /** @see InstallParams#originFile */ 9110 final File originFile; 9111 /** @see InstallParams#originStaged */ 9112 final boolean originStaged; 9113 9114 // TODO: define inherit location 9115 9116 final IPackageInstallObserver2 observer; 9117 // Always refers to PackageManager flags only 9118 final int flags; 9119 final String installerPackageName; 9120 final ManifestDigest manifestDigest; 9121 final UserHandle user; 9122 final String abiOverride; 9123 final boolean multiArch; 9124 9125 // The list of instruction sets supported by this app. This is currently 9126 // only used during the rmdex() phase to clean up resources. We can get rid of this 9127 // if we move dex files under the common app path. 9128 /* nullable */ String[] instructionSets; 9129 9130 InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 9131 int flags, String installerPackageName, ManifestDigest manifestDigest, 9132 UserHandle user, String[] instructionSets, 9133 String abiOverride, boolean multiArch) { 9134 this.originFile = originFile; 9135 this.originStaged = originStaged; 9136 this.flags = flags; 9137 this.observer = observer; 9138 this.installerPackageName = installerPackageName; 9139 this.manifestDigest = manifestDigest; 9140 this.user = user; 9141 this.instructionSets = instructionSets; 9142 this.abiOverride = abiOverride; 9143 this.multiArch = multiArch; 9144 } 9145 9146 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9147 abstract int doPreInstall(int status); 9148 9149 /** 9150 * Rename package into final resting place. All paths on the given 9151 * scanned package should be updated to reflect the rename. 9152 */ 9153 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9154 abstract int doPostInstall(int status, int uid); 9155 9156 /** @see PackageSettingBase#codePathString */ 9157 abstract String getCodePath(); 9158 /** @see PackageSettingBase#resourcePathString */ 9159 abstract String getResourcePath(); 9160 abstract String getLegacyNativeLibraryPath(); 9161 9162 // Need installer lock especially for dex file removal. 9163 abstract void cleanUpResourcesLI(); 9164 abstract boolean doPostDeleteLI(boolean delete); 9165 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9166 9167 /** 9168 * Called before the source arguments are copied. This is used mostly 9169 * for MoveParams when it needs to read the source file to put it in the 9170 * destination. 9171 */ 9172 int doPreCopy() { 9173 return PackageManager.INSTALL_SUCCEEDED; 9174 } 9175 9176 /** 9177 * Called after the source arguments are copied. This is used mostly for 9178 * MoveParams when it needs to read the source file to put it in the 9179 * destination. 9180 * 9181 * @return 9182 */ 9183 int doPostCopy(int uid) { 9184 return PackageManager.INSTALL_SUCCEEDED; 9185 } 9186 9187 protected boolean isFwdLocked() { 9188 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9189 } 9190 9191 UserHandle getUser() { 9192 return user; 9193 } 9194 } 9195 9196 /** 9197 * Logic to handle installation of non-ASEC applications, including copying 9198 * and renaming logic. 9199 */ 9200 class FileInstallArgs extends InstallArgs { 9201 private File codeFile; 9202 private File resourceFile; 9203 private File legacyNativeLibraryPath; 9204 9205 // Example topology: 9206 // /data/app/com.example/base.apk 9207 // /data/app/com.example/split_foo.apk 9208 // /data/app/com.example/lib/arm/libfoo.so 9209 // /data/app/com.example/lib/arm64/libfoo.so 9210 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9211 9212 /** New install */ 9213 FileInstallArgs(InstallParams params) { 9214 super(params.originFile, params.originStaged, params.observer, params.flags, 9215 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9216 null /* instruction sets */, params.packageAbiOverride, 9217 params.multiArch); 9218 if (isFwdLocked()) { 9219 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9220 } 9221 } 9222 9223 /** Existing install */ 9224 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9225 String[] instructionSets, boolean isMultiArch) { 9226 super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch); 9227 this.codeFile = (codePath != null) ? new File(codePath) : null; 9228 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9229 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9230 new File(legacyNativeLibraryPath) : null; 9231 } 9232 9233 /** New install from existing */ 9234 FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) { 9235 super(originFile, false, null, 0, null, null, null, instructionSets, null, 9236 isMultiArch); 9237 } 9238 9239 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9240 final long lowThreshold; 9241 9242 final DeviceStorageMonitorInternal 9243 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9244 if (dsm == null) { 9245 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9246 lowThreshold = 0L; 9247 } else { 9248 if (dsm.isMemoryLow()) { 9249 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9250 return false; 9251 } 9252 9253 lowThreshold = dsm.getMemoryLowThreshold(); 9254 } 9255 9256 return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9257 lowThreshold); 9258 } 9259 9260 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9261 int ret = PackageManager.INSTALL_SUCCEEDED; 9262 9263 if (originStaged) { 9264 Slog.d(TAG, originFile + " already staged; skipping copy"); 9265 codeFile = originFile; 9266 resourceFile = originFile; 9267 } else { 9268 try { 9269 final File tempDir = mInstallerService.allocateSessionDir(); 9270 codeFile = tempDir; 9271 resourceFile = tempDir; 9272 } catch (IOException e) { 9273 Slog.w(TAG, "Failed to create copy file: " + e); 9274 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9275 } 9276 9277 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9278 @Override 9279 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9280 if (!FileUtils.isValidExtFilename(name)) { 9281 throw new IllegalArgumentException("Invalid filename: " + name); 9282 } 9283 try { 9284 final File file = new File(codeFile, name); 9285 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9286 O_RDWR | O_CREAT, 0644); 9287 Os.chmod(file.getAbsolutePath(), 0644); 9288 return new ParcelFileDescriptor(fd); 9289 } catch (ErrnoException e) { 9290 throw new RemoteException("Failed to open: " + e.getMessage()); 9291 } 9292 } 9293 }; 9294 9295 ret = imcs.copyPackage(originFile.getAbsolutePath(), target); 9296 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9297 Slog.e(TAG, "Failed to copy package"); 9298 return ret; 9299 } 9300 } 9301 9302 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9303 NativeLibraryHelper.Handle handle = null; 9304 try { 9305 handle = NativeLibraryHelper.Handle.create(codeFile); 9306 if (multiArch) { 9307 // Warn if we've set an abiOverride for multi-lib packages.. 9308 // By definition, we need to copy both 32 and 64 bit libraries for 9309 // such packages. 9310 if (abiOverride != null && !CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 9311 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9312 } 9313 9314 int copyRet = PackageManager.NO_NATIVE_LIBRARIES; 9315 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9316 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9317 Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */); 9318 maybeThrowExceptionForMultiArchCopy("Failure copying 32 bit native libraries", copyRet); 9319 } 9320 9321 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9322 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9323 Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */); 9324 maybeThrowExceptionForMultiArchCopy("Failure copying 64 bit native libraries", copyRet); 9325 } 9326 } else { 9327 final String cpuAbiOverride = deriveAbiOverride(this.abiOverride, null /* package setting */); 9328 String[] abiList = (cpuAbiOverride != null) ? 9329 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9330 9331 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9332 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9333 abiList = Build.SUPPORTED_32_BIT_ABIS; 9334 } 9335 9336 int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList, 9337 true /* use isa specific subdirs */); 9338 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9339 Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]"); 9340 return copyRet; 9341 } 9342 } 9343 } catch (IOException e) { 9344 Slog.e(TAG, "Copying native libraries failed", e); 9345 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9346 } catch (PackageManagerException pme) { 9347 Slog.e(TAG, "Copying native libraries failed", pme); 9348 ret = pme.error; 9349 } finally { 9350 IoUtils.closeQuietly(handle); 9351 } 9352 9353 return ret; 9354 } 9355 9356 int doPreInstall(int status) { 9357 if (status != PackageManager.INSTALL_SUCCEEDED) { 9358 cleanUp(); 9359 } 9360 return status; 9361 } 9362 9363 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9364 if (status != PackageManager.INSTALL_SUCCEEDED) { 9365 cleanUp(); 9366 return false; 9367 } else { 9368 final File beforeCodeFile = codeFile; 9369 final File afterCodeFile = getNextCodePath(pkg.packageName); 9370 9371 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9372 try { 9373 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9374 } catch (ErrnoException e) { 9375 Slog.d(TAG, "Failed to rename", e); 9376 return false; 9377 } 9378 9379 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9380 Slog.d(TAG, "Failed to restorecon"); 9381 return false; 9382 } 9383 9384 // Reflect the rename internally 9385 codeFile = afterCodeFile; 9386 resourceFile = afterCodeFile; 9387 9388 // Reflect the rename in scanned details 9389 pkg.codePath = afterCodeFile.getAbsolutePath(); 9390 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9391 pkg.baseCodePath); 9392 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9393 pkg.splitCodePaths); 9394 9395 // Reflect the rename in app info 9396 pkg.applicationInfo.setCodePath(pkg.codePath); 9397 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9398 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9399 pkg.applicationInfo.setResourcePath(pkg.codePath); 9400 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9401 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9402 9403 return true; 9404 } 9405 } 9406 9407 int doPostInstall(int status, int uid) { 9408 if (status != PackageManager.INSTALL_SUCCEEDED) { 9409 cleanUp(); 9410 } 9411 return status; 9412 } 9413 9414 @Override 9415 String getCodePath() { 9416 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9417 } 9418 9419 @Override 9420 String getResourcePath() { 9421 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9422 } 9423 9424 @Override 9425 String getLegacyNativeLibraryPath() { 9426 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9427 } 9428 9429 private boolean cleanUp() { 9430 if (codeFile == null || !codeFile.exists()) { 9431 return false; 9432 } 9433 9434 if (codeFile.isDirectory()) { 9435 FileUtils.deleteContents(codeFile); 9436 } 9437 codeFile.delete(); 9438 9439 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9440 resourceFile.delete(); 9441 } 9442 9443 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9444 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9445 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9446 } 9447 legacyNativeLibraryPath.delete(); 9448 } 9449 9450 return true; 9451 } 9452 9453 void cleanUpResourcesLI() { 9454 // Try enumerating all code paths before deleting 9455 List<String> allCodePaths = Collections.EMPTY_LIST; 9456 if (codeFile != null && codeFile.exists()) { 9457 try { 9458 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9459 allCodePaths = pkg.getAllCodePaths(); 9460 } catch (PackageParserException e) { 9461 // Ignored; we tried our best 9462 } 9463 } 9464 9465 cleanUp(); 9466 9467 if (!allCodePaths.isEmpty()) { 9468 if (instructionSets == null) { 9469 throw new IllegalStateException("instructionSet == null"); 9470 } 9471 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9472 for (String codePath : allCodePaths) { 9473 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9474 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9475 if (retCode < 0) { 9476 Slog.w(TAG, "Couldn't remove dex file for package: " 9477 + " at location " + codePath + ", retcode=" + retCode); 9478 // we don't consider this to be a failure of the core package deletion 9479 } 9480 } 9481 } 9482 } 9483 } 9484 9485 boolean doPostDeleteLI(boolean delete) { 9486 // XXX err, shouldn't we respect the delete flag? 9487 cleanUpResourcesLI(); 9488 return true; 9489 } 9490 } 9491 9492 private boolean isAsecExternal(String cid) { 9493 final String asecPath = PackageHelper.getSdFilesystem(cid); 9494 return !asecPath.startsWith(mAsecInternalPath); 9495 } 9496 9497 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9498 PackageManagerException { 9499 if (copyRet < 0) { 9500 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9501 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9502 throw new PackageManagerException(copyRet, message); 9503 } 9504 } 9505 } 9506 9507 /** 9508 * Extract the MountService "container ID" from the full code path of an 9509 * .apk. 9510 */ 9511 static String cidFromCodePath(String fullCodePath) { 9512 int eidx = fullCodePath.lastIndexOf("/"); 9513 String subStr1 = fullCodePath.substring(0, eidx); 9514 int sidx = subStr1.lastIndexOf("/"); 9515 return subStr1.substring(sidx+1, eidx); 9516 } 9517 9518 /** 9519 * Logic to handle installation of ASEC applications, including copying and 9520 * renaming logic. 9521 */ 9522 class AsecInstallArgs extends InstallArgs { 9523 // TODO: teach about handling cluster directories 9524 9525 static final String RES_FILE_NAME = "pkg.apk"; 9526 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9527 9528 String cid; 9529 String packagePath; 9530 String resourcePath; 9531 String legacyNativeLibraryDir; 9532 9533 /** New install */ 9534 AsecInstallArgs(InstallParams params) { 9535 super(params.originFile, params.originStaged, params.observer, params.flags, 9536 params.installerPackageName, params.getManifestDigest(), 9537 params.getUser(), null /* instruction sets */, 9538 params.packageAbiOverride, params.multiArch); 9539 } 9540 9541 /** Existing install */ 9542 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9543 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9544 super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9545 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9546 instructionSets, null, isMultiArch); 9547 // Extract cid from fullCodePath 9548 int eidx = fullCodePath.lastIndexOf("/"); 9549 String subStr1 = fullCodePath.substring(0, eidx); 9550 int sidx = subStr1.lastIndexOf("/"); 9551 cid = subStr1.substring(sidx+1, eidx); 9552 setCachePath(subStr1); 9553 } 9554 9555 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked, 9556 boolean isMultiArch) { 9557 super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9558 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9559 instructionSets, null, isMultiArch); 9560 this.cid = cid; 9561 setCachePath(PackageHelper.getSdDir(cid)); 9562 } 9563 9564 /** New install from existing */ 9565 AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets, 9566 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9567 super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9568 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9569 instructionSets, null, isMultiArch); 9570 this.cid = cid; 9571 } 9572 9573 void createCopyFile() { 9574 cid = getTempContainerId(); 9575 } 9576 9577 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9578 return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9579 abiOverride); 9580 } 9581 9582 private final boolean isExternal() { 9583 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9584 } 9585 9586 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9587 if (temp) { 9588 createCopyFile(); 9589 } else { 9590 /* 9591 * Pre-emptively destroy the container since it's destroyed if 9592 * copying fails due to it existing anyway. 9593 */ 9594 PackageHelper.destroySdDir(cid); 9595 } 9596 9597 final String newCachePath = imcs.copyPackageToContainer( 9598 originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9599 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9600 9601 if (newCachePath != null) { 9602 setCachePath(newCachePath); 9603 return PackageManager.INSTALL_SUCCEEDED; 9604 } else { 9605 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9606 } 9607 } 9608 9609 @Override 9610 String getCodePath() { 9611 return packagePath; 9612 } 9613 9614 @Override 9615 String getResourcePath() { 9616 return resourcePath; 9617 } 9618 9619 @Override 9620 String getLegacyNativeLibraryPath() { 9621 return legacyNativeLibraryDir; 9622 } 9623 9624 int doPreInstall(int status) { 9625 if (status != PackageManager.INSTALL_SUCCEEDED) { 9626 // Destroy container 9627 PackageHelper.destroySdDir(cid); 9628 } else { 9629 boolean mounted = PackageHelper.isContainerMounted(cid); 9630 if (!mounted) { 9631 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9632 Process.SYSTEM_UID); 9633 if (newCachePath != null) { 9634 setCachePath(newCachePath); 9635 } else { 9636 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9637 } 9638 } 9639 } 9640 return status; 9641 } 9642 9643 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9644 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9645 String newCachePath = null; 9646 if (PackageHelper.isContainerMounted(cid)) { 9647 // Unmount the container 9648 if (!PackageHelper.unMountSdDir(cid)) { 9649 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9650 return false; 9651 } 9652 } 9653 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9654 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9655 " which might be stale. Will try to clean up."); 9656 // Clean up the stale container and proceed to recreate. 9657 if (!PackageHelper.destroySdDir(newCacheId)) { 9658 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9659 return false; 9660 } 9661 // Successfully cleaned up stale container. Try to rename again. 9662 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9663 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9664 + " inspite of cleaning it up."); 9665 return false; 9666 } 9667 } 9668 if (!PackageHelper.isContainerMounted(newCacheId)) { 9669 Slog.w(TAG, "Mounting container " + newCacheId); 9670 newCachePath = PackageHelper.mountSdDir(newCacheId, 9671 getEncryptKey(), Process.SYSTEM_UID); 9672 } else { 9673 newCachePath = PackageHelper.getSdDir(newCacheId); 9674 } 9675 if (newCachePath == null) { 9676 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9677 return false; 9678 } 9679 Log.i(TAG, "Succesfully renamed " + cid + 9680 " to " + newCacheId + 9681 " at new path: " + newCachePath); 9682 cid = newCacheId; 9683 setCachePath(newCachePath); 9684 9685 // TODO: extend to support split APKs 9686 pkg.codePath = getCodePath(); 9687 pkg.baseCodePath = getCodePath(); 9688 pkg.splitCodePaths = null; 9689 9690 pkg.applicationInfo.setCodePath(getCodePath()); 9691 pkg.applicationInfo.setBaseCodePath(getCodePath()); 9692 pkg.applicationInfo.setSplitCodePaths(null); 9693 pkg.applicationInfo.setResourcePath(getResourcePath()); 9694 pkg.applicationInfo.setBaseResourcePath(getResourcePath()); 9695 pkg.applicationInfo.setSplitResourcePaths(null); 9696 9697 return true; 9698 } 9699 9700 private void setCachePath(String newCachePath) { 9701 File cachePath = new File(newCachePath); 9702 legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath(); 9703 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9704 9705 if (isFwdLocked()) { 9706 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9707 } else { 9708 resourcePath = packagePath; 9709 } 9710 } 9711 9712 int doPostInstall(int status, int uid) { 9713 if (status != PackageManager.INSTALL_SUCCEEDED) { 9714 cleanUp(); 9715 } else { 9716 final int groupOwner; 9717 final String protectedFile; 9718 if (isFwdLocked()) { 9719 groupOwner = UserHandle.getSharedAppGid(uid); 9720 protectedFile = RES_FILE_NAME; 9721 } else { 9722 groupOwner = -1; 9723 protectedFile = null; 9724 } 9725 9726 if (uid < Process.FIRST_APPLICATION_UID 9727 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9728 Slog.e(TAG, "Failed to finalize " + cid); 9729 PackageHelper.destroySdDir(cid); 9730 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9731 } 9732 9733 boolean mounted = PackageHelper.isContainerMounted(cid); 9734 if (!mounted) { 9735 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9736 } 9737 } 9738 return status; 9739 } 9740 9741 private void cleanUp() { 9742 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9743 9744 // Destroy secure container 9745 PackageHelper.destroySdDir(cid); 9746 } 9747 9748 void cleanUpResourcesLI() { 9749 String sourceFile = getCodePath(); 9750 // Remove dex file 9751 if (instructionSets == null) { 9752 throw new IllegalStateException("instructionSet == null"); 9753 } 9754 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9755 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9756 int retCode = mInstaller.rmdex(sourceFile, dexCodeInstructionSet); 9757 if (retCode < 0) { 9758 Slog.w(TAG, "Couldn't remove dex file for package: " 9759 + " at location " 9760 + sourceFile.toString() + ", retcode=" + retCode); 9761 // we don't consider this to be a failure of the core package deletion 9762 } 9763 } 9764 cleanUp(); 9765 } 9766 9767 boolean matchContainer(String app) { 9768 if (cid.startsWith(app)) { 9769 return true; 9770 } 9771 return false; 9772 } 9773 9774 String getPackageName() { 9775 return getAsecPackageName(cid); 9776 } 9777 9778 boolean doPostDeleteLI(boolean delete) { 9779 boolean ret = false; 9780 boolean mounted = PackageHelper.isContainerMounted(cid); 9781 if (mounted) { 9782 // Unmount first 9783 ret = PackageHelper.unMountSdDir(cid); 9784 } 9785 if (ret && delete) { 9786 cleanUpResourcesLI(); 9787 } 9788 return ret; 9789 } 9790 9791 @Override 9792 int doPreCopy() { 9793 if (isFwdLocked()) { 9794 if (!PackageHelper.fixSdPermissions(cid, 9795 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9796 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9797 } 9798 } 9799 9800 return PackageManager.INSTALL_SUCCEEDED; 9801 } 9802 9803 @Override 9804 int doPostCopy(int uid) { 9805 if (isFwdLocked()) { 9806 if (uid < Process.FIRST_APPLICATION_UID 9807 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9808 RES_FILE_NAME)) { 9809 Slog.e(TAG, "Failed to finalize " + cid); 9810 PackageHelper.destroySdDir(cid); 9811 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9812 } 9813 } 9814 9815 return PackageManager.INSTALL_SUCCEEDED; 9816 } 9817 } 9818 9819 static String getAsecPackageName(String packageCid) { 9820 int idx = packageCid.lastIndexOf("-"); 9821 if (idx == -1) { 9822 return packageCid; 9823 } 9824 return packageCid.substring(0, idx); 9825 } 9826 9827 // Utility method used to create code paths based on package name and available index. 9828 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9829 String idxStr = ""; 9830 int idx = 1; 9831 // Fall back to default value of idx=1 if prefix is not 9832 // part of oldCodePath 9833 if (oldCodePath != null) { 9834 String subStr = oldCodePath; 9835 // Drop the suffix right away 9836 if (suffix != null && subStr.endsWith(suffix)) { 9837 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9838 } 9839 // If oldCodePath already contains prefix find out the 9840 // ending index to either increment or decrement. 9841 int sidx = subStr.lastIndexOf(prefix); 9842 if (sidx != -1) { 9843 subStr = subStr.substring(sidx + prefix.length()); 9844 if (subStr != null) { 9845 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9846 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9847 } 9848 try { 9849 idx = Integer.parseInt(subStr); 9850 if (idx <= 1) { 9851 idx++; 9852 } else { 9853 idx--; 9854 } 9855 } catch(NumberFormatException e) { 9856 } 9857 } 9858 } 9859 } 9860 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9861 return prefix + idxStr; 9862 } 9863 9864 private File getNextCodePath(String packageName) { 9865 int suffix = 1; 9866 File result; 9867 do { 9868 result = new File(mAppInstallDir, packageName + "-" + suffix); 9869 suffix++; 9870 } while (result.exists()); 9871 return result; 9872 } 9873 9874 // Utility method used to ignore ADD/REMOVE events 9875 // by directory observer. 9876 private static boolean ignoreCodePath(String fullPathStr) { 9877 String apkName = deriveCodePathName(fullPathStr); 9878 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9879 if (idx != -1 && ((idx+1) < apkName.length())) { 9880 // Make sure the package ends with a numeral 9881 String version = apkName.substring(idx+1); 9882 try { 9883 Integer.parseInt(version); 9884 return true; 9885 } catch (NumberFormatException e) {} 9886 } 9887 return false; 9888 } 9889 9890 // Utility method that returns the relative package path with respect 9891 // to the installation directory. Like say for /data/data/com.test-1.apk 9892 // string com.test-1 is returned. 9893 static String deriveCodePathName(String codePath) { 9894 if (codePath == null) { 9895 return null; 9896 } 9897 final File codeFile = new File(codePath); 9898 final String name = codeFile.getName(); 9899 if (codeFile.isDirectory()) { 9900 return name; 9901 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9902 final int lastDot = name.lastIndexOf('.'); 9903 return name.substring(0, lastDot); 9904 } else { 9905 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9906 return null; 9907 } 9908 } 9909 9910 class PackageInstalledInfo { 9911 String name; 9912 int uid; 9913 // The set of users that originally had this package installed. 9914 int[] origUsers; 9915 // The set of users that now have this package installed. 9916 int[] newUsers; 9917 PackageParser.Package pkg; 9918 int returnCode; 9919 String returnMsg; 9920 PackageRemovedInfo removedInfo; 9921 9922 public void setError(int code, String msg) { 9923 returnCode = code; 9924 returnMsg = msg; 9925 Slog.w(TAG, msg); 9926 } 9927 9928 public void setError(String msg, PackageParserException e) { 9929 returnCode = e.error; 9930 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9931 Slog.w(TAG, msg, e); 9932 } 9933 9934 public void setError(String msg, PackageManagerException e) { 9935 returnCode = e.error; 9936 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9937 Slog.w(TAG, msg, e); 9938 } 9939 9940 // In some error cases we want to convey more info back to the observer 9941 String origPackage; 9942 String origPermission; 9943 } 9944 9945 /* 9946 * Install a non-existing package. 9947 */ 9948 private void installNewPackageLI(PackageParser.Package pkg, 9949 int parseFlags, int scanMode, UserHandle user, 9950 String installerPackageName, PackageInstalledInfo res) { 9951 // Remember this for later, in case we need to rollback this install 9952 String pkgName = pkg.packageName; 9953 9954 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9955 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9956 synchronized(mPackages) { 9957 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9958 // A package with the same name is already installed, though 9959 // it has been renamed to an older name. The package we 9960 // are trying to install should be installed as an update to 9961 // the existing one, but that has not been requested, so bail. 9962 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9963 + " without first uninstalling package running as " 9964 + mSettings.mRenamedPackages.get(pkgName)); 9965 return; 9966 } 9967 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9968 // Don't allow installation over an existing package with the same name. 9969 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9970 + " without first uninstalling."); 9971 return; 9972 } 9973 } 9974 9975 try { 9976 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9977 System.currentTimeMillis(), user); 9978 9979 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9980 // delete the partially installed application. the data directory will have to be 9981 // restored if it was already existing 9982 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9983 // remove package from internal structures. Note that we want deletePackageX to 9984 // delete the package data and cache directories that it created in 9985 // scanPackageLocked, unless those directories existed before we even tried to 9986 // install. 9987 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9988 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9989 res.removedInfo, true); 9990 } 9991 9992 } catch (PackageManagerException e) { 9993 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9994 } 9995 } 9996 9997 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9998 // Upgrade keysets are being used. Determine if new package has a superset of the 9999 // required keys. 10000 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10001 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10002 for (int i = 0; i < upgradeKeySets.length; i++) { 10003 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10004 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10005 return true; 10006 } 10007 } 10008 return false; 10009 } 10010 10011 private void replacePackageLI(PackageParser.Package pkg, 10012 int parseFlags, int scanMode, UserHandle user, 10013 String installerPackageName, PackageInstalledInfo res) { 10014 PackageParser.Package oldPackage; 10015 String pkgName = pkg.packageName; 10016 int[] allUsers; 10017 boolean[] perUserInstalled; 10018 10019 // First find the old package info and check signatures 10020 synchronized(mPackages) { 10021 oldPackage = mPackages.get(pkgName); 10022 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10023 PackageSetting ps = mSettings.mPackages.get(pkgName); 10024 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10025 // default to original signature matching 10026 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10027 != PackageManager.SIGNATURE_MATCH) { 10028 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10029 "New package has a different signature: " + pkgName); 10030 return; 10031 } 10032 } else { 10033 if(!checkUpgradeKeySetLP(ps, pkg)) { 10034 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10035 "New package not signed by keys specified by upgrade-keysets: " 10036 + pkgName); 10037 return; 10038 } 10039 } 10040 10041 // In case of rollback, remember per-user/profile install state 10042 allUsers = sUserManager.getUserIds(); 10043 perUserInstalled = new boolean[allUsers.length]; 10044 for (int i = 0; i < allUsers.length; i++) { 10045 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10046 } 10047 } 10048 10049 boolean sysPkg = (isSystemApp(oldPackage)); 10050 if (sysPkg) { 10051 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10052 user, allUsers, perUserInstalled, installerPackageName, res); 10053 } else { 10054 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10055 user, allUsers, perUserInstalled, installerPackageName, res); 10056 } 10057 } 10058 10059 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10060 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10061 int[] allUsers, boolean[] perUserInstalled, 10062 String installerPackageName, PackageInstalledInfo res) { 10063 String pkgName = deletedPackage.packageName; 10064 boolean deletedPkg = true; 10065 boolean updatedSettings = false; 10066 10067 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10068 + deletedPackage); 10069 long origUpdateTime; 10070 if (pkg.mExtras != null) { 10071 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10072 } else { 10073 origUpdateTime = 0; 10074 } 10075 10076 // First delete the existing package while retaining the data directory 10077 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10078 res.removedInfo, true)) { 10079 // If the existing package wasn't successfully deleted 10080 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10081 deletedPkg = false; 10082 } else { 10083 // Successfully deleted the old package. Now proceed with re-installation 10084 deleteCodeCacheDirsLI(pkgName); 10085 try { 10086 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10087 scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10088 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10089 updatedSettings = true; 10090 } catch (PackageManagerException e) { 10091 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10092 } 10093 } 10094 10095 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10096 // remove package from internal structures. Note that we want deletePackageX to 10097 // delete the package data and cache directories that it created in 10098 // scanPackageLocked, unless those directories existed before we even tried to 10099 // install. 10100 if(updatedSettings) { 10101 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10102 deletePackageLI( 10103 pkgName, null, true, allUsers, perUserInstalled, 10104 PackageManager.DELETE_KEEP_DATA, 10105 res.removedInfo, true); 10106 } 10107 // Since we failed to install the new package we need to restore the old 10108 // package that we deleted. 10109 if (deletedPkg) { 10110 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10111 File restoreFile = new File(deletedPackage.codePath); 10112 // Parse old package 10113 boolean oldOnSd = isExternal(deletedPackage); 10114 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10115 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10116 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10117 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 10118 | SCAN_UPDATE_TIME; 10119 try { 10120 scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null); 10121 } catch (PackageManagerException e) { 10122 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10123 + e.getMessage()); 10124 return; 10125 } 10126 // Restore of old package succeeded. Update permissions. 10127 // writer 10128 synchronized (mPackages) { 10129 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10130 UPDATE_PERMISSIONS_ALL); 10131 // can downgrade to reader 10132 mSettings.writeLPr(); 10133 } 10134 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10135 } 10136 } 10137 } 10138 10139 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10140 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10141 int[] allUsers, boolean[] perUserInstalled, 10142 String installerPackageName, PackageInstalledInfo res) { 10143 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10144 + ", old=" + deletedPackage); 10145 boolean updatedSettings = false; 10146 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 10147 PackageParser.PARSE_IS_SYSTEM; 10148 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10149 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10150 } 10151 String packageName = deletedPackage.packageName; 10152 if (packageName == null) { 10153 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10154 "Attempt to delete null packageName."); 10155 return; 10156 } 10157 PackageParser.Package oldPkg; 10158 PackageSetting oldPkgSetting; 10159 // reader 10160 synchronized (mPackages) { 10161 oldPkg = mPackages.get(packageName); 10162 oldPkgSetting = mSettings.mPackages.get(packageName); 10163 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10164 (oldPkgSetting == null)) { 10165 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10166 "Couldn't find package:" + packageName + " information"); 10167 return; 10168 } 10169 } 10170 10171 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10172 10173 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10174 res.removedInfo.removedPackage = packageName; 10175 // Remove existing system package 10176 removePackageLI(oldPkgSetting, true); 10177 // writer 10178 synchronized (mPackages) { 10179 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10180 // We didn't need to disable the .apk as a current system package, 10181 // which means we are replacing another update that is already 10182 // installed. We need to make sure to delete the older one's .apk. 10183 res.removedInfo.args = createInstallArgsForExisting(0, 10184 deletedPackage.applicationInfo.getCodePath(), 10185 deletedPackage.applicationInfo.getResourcePath(), 10186 deletedPackage.applicationInfo.nativeLibraryRootDir, 10187 getAppDexInstructionSets(deletedPackage.applicationInfo), 10188 isMultiArch(deletedPackage.applicationInfo)); 10189 } else { 10190 res.removedInfo.args = null; 10191 } 10192 } 10193 10194 // Successfully disabled the old package. Now proceed with re-installation 10195 deleteCodeCacheDirsLI(packageName); 10196 10197 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10198 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10199 10200 PackageParser.Package newPackage = null; 10201 try { 10202 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user); 10203 if (newPackage.mExtras != null) { 10204 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10205 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10206 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10207 10208 // is the update attempting to change shared user? that isn't going to work... 10209 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10210 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10211 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10212 + " to " + newPkgSetting.sharedUser); 10213 updatedSettings = true; 10214 } 10215 } 10216 10217 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10218 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10219 updatedSettings = true; 10220 } 10221 10222 } catch (PackageManagerException e) { 10223 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10224 } 10225 10226 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10227 // Re installation failed. Restore old information 10228 // Remove new pkg information 10229 if (newPackage != null) { 10230 removeInstalledPackageLI(newPackage, true); 10231 } 10232 // Add back the old system package 10233 try { 10234 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user); 10235 } catch (PackageManagerException e) { 10236 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10237 } 10238 // Restore the old system information in Settings 10239 synchronized(mPackages) { 10240 if (updatedSettings) { 10241 mSettings.enableSystemPackageLPw(packageName); 10242 mSettings.setInstallerPackageName(packageName, 10243 oldPkgSetting.installerPackageName); 10244 } 10245 mSettings.writeLPr(); 10246 } 10247 } 10248 } 10249 10250 // Utility method used to move dex files during install. 10251 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10252 // TODO: extend to move split APK dex files 10253 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10254 final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo); 10255 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10256 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10257 int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath, 10258 dexCodeInstructionSet); 10259 if (retCode != 0) { 10260 /* 10261 * Programs may be lazily run through dexopt, so the 10262 * source may not exist. However, something seems to 10263 * have gone wrong, so note that dexopt needs to be 10264 * run again and remove the source file. In addition, 10265 * remove the target to make sure there isn't a stale 10266 * file from a previous version of the package. 10267 */ 10268 newPackage.mDexOptPerformed.clear(); 10269 mInstaller.rmdex(oldCodePath, dexCodeInstructionSet); 10270 mInstaller.rmdex(newPackage.baseCodePath, dexCodeInstructionSet); 10271 } 10272 } 10273 } 10274 return PackageManager.INSTALL_SUCCEEDED; 10275 } 10276 10277 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10278 int[] allUsers, boolean[] perUserInstalled, 10279 PackageInstalledInfo res) { 10280 String pkgName = newPackage.packageName; 10281 synchronized (mPackages) { 10282 //write settings. the installStatus will be incomplete at this stage. 10283 //note that the new package setting would have already been 10284 //added to mPackages. It hasn't been persisted yet. 10285 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10286 mSettings.writeLPr(); 10287 } 10288 10289 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10290 10291 synchronized (mPackages) { 10292 updatePermissionsLPw(newPackage.packageName, newPackage, 10293 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10294 ? UPDATE_PERMISSIONS_ALL : 0)); 10295 // For system-bundled packages, we assume that installing an upgraded version 10296 // of the package implies that the user actually wants to run that new code, 10297 // so we enable the package. 10298 if (isSystemApp(newPackage)) { 10299 // NB: implicit assumption that system package upgrades apply to all users 10300 if (DEBUG_INSTALL) { 10301 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10302 } 10303 PackageSetting ps = mSettings.mPackages.get(pkgName); 10304 if (ps != null) { 10305 if (res.origUsers != null) { 10306 for (int userHandle : res.origUsers) { 10307 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10308 userHandle, installerPackageName); 10309 } 10310 } 10311 // Also convey the prior install/uninstall state 10312 if (allUsers != null && perUserInstalled != null) { 10313 for (int i = 0; i < allUsers.length; i++) { 10314 if (DEBUG_INSTALL) { 10315 Slog.d(TAG, " user " + allUsers[i] 10316 + " => " + perUserInstalled[i]); 10317 } 10318 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10319 } 10320 // these install state changes will be persisted in the 10321 // upcoming call to mSettings.writeLPr(). 10322 } 10323 } 10324 } 10325 res.name = pkgName; 10326 res.uid = newPackage.applicationInfo.uid; 10327 res.pkg = newPackage; 10328 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10329 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10330 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10331 //to update install status 10332 mSettings.writeLPr(); 10333 } 10334 } 10335 10336 private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) { 10337 int pFlags = args.flags; 10338 String installerPackageName = args.installerPackageName; 10339 File tmpPackageFile = new File(args.getCodePath()); 10340 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10341 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10342 boolean replace = false; 10343 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10344 | (newInstall ? SCAN_NEW_INSTALL : 0); 10345 // Result object to be returned 10346 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10347 10348 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10349 // Retrieve PackageSettings and parse package 10350 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10351 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10352 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10353 PackageParser pp = new PackageParser(); 10354 pp.setSeparateProcesses(mSeparateProcesses); 10355 pp.setDisplayMetrics(mMetrics); 10356 10357 final PackageParser.Package pkg; 10358 try { 10359 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10360 } catch (PackageParserException e) { 10361 res.setError("Failed parse during installPackageLI", e); 10362 return; 10363 } 10364 10365 // Mark that we have an install time CPU ABI override. 10366 pkg.cpuAbiOverride = args.abiOverride; 10367 10368 String pkgName = res.name = pkg.packageName; 10369 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10370 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10371 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10372 return; 10373 } 10374 } 10375 10376 try { 10377 pp.collectCertificates(pkg, parseFlags); 10378 pp.collectManifestDigest(pkg); 10379 } catch (PackageParserException e) { 10380 res.setError("Failed collect during installPackageLI", e); 10381 return; 10382 } 10383 10384 /* If the installer passed in a manifest digest, compare it now. */ 10385 if (args.manifestDigest != null) { 10386 if (DEBUG_INSTALL) { 10387 final String parsedManifest = pkg.manifestDigest == null ? "null" 10388 : pkg.manifestDigest.toString(); 10389 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10390 + parsedManifest); 10391 } 10392 10393 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10394 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10395 return; 10396 } 10397 } else if (DEBUG_INSTALL) { 10398 final String parsedManifest = pkg.manifestDigest == null 10399 ? "null" : pkg.manifestDigest.toString(); 10400 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10401 } 10402 10403 // Get rid of all references to package scan path via parser. 10404 pp = null; 10405 String oldCodePath = null; 10406 boolean systemApp = false; 10407 synchronized (mPackages) { 10408 // Check whether the newly-scanned package wants to define an already-defined perm 10409 int N = pkg.permissions.size(); 10410 for (int i = N-1; i >= 0; i--) { 10411 PackageParser.Permission perm = pkg.permissions.get(i); 10412 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10413 if (bp != null) { 10414 // If the defining package is signed with our cert, it's okay. This 10415 // also includes the "updating the same package" case, of course. 10416 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10417 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10418 // If the owning package is the system itself, we log but allow 10419 // install to proceed; we fail the install on all other permission 10420 // redefinitions. 10421 if (!bp.sourcePackage.equals("android")) { 10422 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10423 + pkg.packageName + " attempting to redeclare permission " 10424 + perm.info.name + " already owned by " + bp.sourcePackage); 10425 res.origPermission = perm.info.name; 10426 res.origPackage = bp.sourcePackage; 10427 return; 10428 } else { 10429 Slog.w(TAG, "Package " + pkg.packageName 10430 + " attempting to redeclare system permission " 10431 + perm.info.name + "; ignoring new declaration"); 10432 pkg.permissions.remove(i); 10433 } 10434 } 10435 } 10436 } 10437 10438 // Check if installing already existing package 10439 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10440 String oldName = mSettings.mRenamedPackages.get(pkgName); 10441 if (pkg.mOriginalPackages != null 10442 && pkg.mOriginalPackages.contains(oldName) 10443 && mPackages.containsKey(oldName)) { 10444 // This package is derived from an original package, 10445 // and this device has been updating from that original 10446 // name. We must continue using the original name, so 10447 // rename the new package here. 10448 pkg.setPackageName(oldName); 10449 pkgName = pkg.packageName; 10450 replace = true; 10451 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10452 + oldName + " pkgName=" + pkgName); 10453 } else if (mPackages.containsKey(pkgName)) { 10454 // This package, under its official name, already exists 10455 // on the device; we should replace it. 10456 replace = true; 10457 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10458 } 10459 } 10460 PackageSetting ps = mSettings.mPackages.get(pkgName); 10461 if (ps != null) { 10462 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10463 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10464 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10465 systemApp = (ps.pkg.applicationInfo.flags & 10466 ApplicationInfo.FLAG_SYSTEM) != 0; 10467 } 10468 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10469 } 10470 } 10471 10472 if (systemApp && onSd) { 10473 // Disable updates to system apps on sdcard 10474 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10475 "Cannot install updates to system apps on sdcard"); 10476 return; 10477 } 10478 10479 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10480 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10481 return; 10482 } 10483 10484 if (replace) { 10485 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10486 installerPackageName, res); 10487 } else { 10488 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10489 installerPackageName, res); 10490 } 10491 synchronized (mPackages) { 10492 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10493 if (ps != null) { 10494 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10495 } 10496 } 10497 } 10498 10499 private static boolean isForwardLocked(PackageParser.Package pkg) { 10500 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10501 } 10502 10503 private static boolean isForwardLocked(ApplicationInfo info) { 10504 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10505 } 10506 10507 private boolean isForwardLocked(PackageSetting ps) { 10508 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10509 } 10510 10511 private static boolean isMultiArch(PackageSetting ps) { 10512 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10513 } 10514 10515 private static boolean isMultiArch(ApplicationInfo info) { 10516 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10517 } 10518 10519 private static boolean isExternal(PackageParser.Package pkg) { 10520 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10521 } 10522 10523 private static boolean isExternal(PackageSetting ps) { 10524 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10525 } 10526 10527 private static boolean isExternal(ApplicationInfo info) { 10528 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10529 } 10530 10531 private static boolean isSystemApp(PackageParser.Package pkg) { 10532 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10533 } 10534 10535 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10536 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10537 } 10538 10539 private static boolean isSystemApp(ApplicationInfo info) { 10540 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10541 } 10542 10543 private static boolean isSystemApp(PackageSetting ps) { 10544 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10545 } 10546 10547 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10548 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10549 } 10550 10551 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10552 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10553 } 10554 10555 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10556 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10557 } 10558 10559 private int packageFlagsToInstallFlags(PackageSetting ps) { 10560 int installFlags = 0; 10561 if (isExternal(ps)) { 10562 installFlags |= PackageManager.INSTALL_EXTERNAL; 10563 } 10564 if (isForwardLocked(ps)) { 10565 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10566 } 10567 return installFlags; 10568 } 10569 10570 private void deleteTempPackageFiles() { 10571 final FilenameFilter filter = new FilenameFilter() { 10572 public boolean accept(File dir, String name) { 10573 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10574 } 10575 }; 10576 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10577 file.delete(); 10578 } 10579 } 10580 10581 @Override 10582 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10583 int flags) { 10584 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10585 flags); 10586 } 10587 10588 @Override 10589 public void deletePackage(final String packageName, 10590 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10591 mContext.enforceCallingOrSelfPermission( 10592 android.Manifest.permission.DELETE_PACKAGES, null); 10593 final int uid = Binder.getCallingUid(); 10594 if (UserHandle.getUserId(uid) != userId) { 10595 mContext.enforceCallingPermission( 10596 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10597 "deletePackage for user " + userId); 10598 } 10599 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10600 try { 10601 observer.onPackageDeleted(packageName, 10602 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10603 } catch (RemoteException re) { 10604 } 10605 return; 10606 } 10607 10608 boolean uninstallBlocked = false; 10609 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10610 int[] users = sUserManager.getUserIds(); 10611 for (int i = 0; i < users.length; ++i) { 10612 if (getBlockUninstallForUser(packageName, users[i])) { 10613 uninstallBlocked = true; 10614 break; 10615 } 10616 } 10617 } else { 10618 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10619 } 10620 if (uninstallBlocked) { 10621 try { 10622 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10623 null); 10624 } catch (RemoteException re) { 10625 } 10626 return; 10627 } 10628 10629 if (DEBUG_REMOVE) { 10630 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10631 } 10632 // Queue up an async operation since the package deletion may take a little while. 10633 mHandler.post(new Runnable() { 10634 public void run() { 10635 mHandler.removeCallbacks(this); 10636 final int returnCode = deletePackageX(packageName, userId, flags); 10637 if (observer != null) { 10638 try { 10639 observer.onPackageDeleted(packageName, returnCode, null); 10640 } catch (RemoteException e) { 10641 Log.i(TAG, "Observer no longer exists."); 10642 } //end catch 10643 } //end if 10644 } //end run 10645 }); 10646 } 10647 10648 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10649 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10650 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10651 try { 10652 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10653 || dpm.isDeviceOwner(packageName))) { 10654 return true; 10655 } 10656 } catch (RemoteException e) { 10657 } 10658 return false; 10659 } 10660 10661 /** 10662 * This method is an internal method that could be get invoked either 10663 * to delete an installed package or to clean up a failed installation. 10664 * After deleting an installed package, a broadcast is sent to notify any 10665 * listeners that the package has been installed. For cleaning up a failed 10666 * installation, the broadcast is not necessary since the package's 10667 * installation wouldn't have sent the initial broadcast either 10668 * The key steps in deleting a package are 10669 * deleting the package information in internal structures like mPackages, 10670 * deleting the packages base directories through installd 10671 * updating mSettings to reflect current status 10672 * persisting settings for later use 10673 * sending a broadcast if necessary 10674 */ 10675 private int deletePackageX(String packageName, int userId, int flags) { 10676 final PackageRemovedInfo info = new PackageRemovedInfo(); 10677 final boolean res; 10678 10679 if (isPackageDeviceAdmin(packageName, userId)) { 10680 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10681 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10682 } 10683 10684 boolean removedForAllUsers = false; 10685 boolean systemUpdate = false; 10686 10687 // for the uninstall-updates case and restricted profiles, remember the per- 10688 // userhandle installed state 10689 int[] allUsers; 10690 boolean[] perUserInstalled; 10691 synchronized (mPackages) { 10692 PackageSetting ps = mSettings.mPackages.get(packageName); 10693 allUsers = sUserManager.getUserIds(); 10694 perUserInstalled = new boolean[allUsers.length]; 10695 for (int i = 0; i < allUsers.length; i++) { 10696 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10697 } 10698 } 10699 10700 synchronized (mInstallLock) { 10701 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10702 res = deletePackageLI(packageName, 10703 (flags & PackageManager.DELETE_ALL_USERS) != 0 10704 ? UserHandle.ALL : new UserHandle(userId), 10705 true, allUsers, perUserInstalled, 10706 flags | REMOVE_CHATTY, info, true); 10707 systemUpdate = info.isRemovedPackageSystemUpdate; 10708 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10709 removedForAllUsers = true; 10710 } 10711 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10712 + " removedForAllUsers=" + removedForAllUsers); 10713 } 10714 10715 if (res) { 10716 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10717 10718 // If the removed package was a system update, the old system package 10719 // was re-enabled; we need to broadcast this information 10720 if (systemUpdate) { 10721 Bundle extras = new Bundle(1); 10722 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10723 ? info.removedAppId : info.uid); 10724 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10725 10726 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10727 extras, null, null, null); 10728 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10729 extras, null, null, null); 10730 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10731 null, packageName, null, null); 10732 } 10733 } 10734 // Force a gc here. 10735 Runtime.getRuntime().gc(); 10736 // Delete the resources here after sending the broadcast to let 10737 // other processes clean up before deleting resources. 10738 if (info.args != null) { 10739 synchronized (mInstallLock) { 10740 info.args.doPostDeleteLI(true); 10741 } 10742 } 10743 10744 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10745 } 10746 10747 static class PackageRemovedInfo { 10748 String removedPackage; 10749 int uid = -1; 10750 int removedAppId = -1; 10751 int[] removedUsers = null; 10752 boolean isRemovedPackageSystemUpdate = false; 10753 // Clean up resources deleted packages. 10754 InstallArgs args = null; 10755 10756 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10757 Bundle extras = new Bundle(1); 10758 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10759 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10760 if (replacing) { 10761 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10762 } 10763 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10764 if (removedPackage != null) { 10765 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10766 extras, null, null, removedUsers); 10767 if (fullRemove && !replacing) { 10768 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10769 extras, null, null, removedUsers); 10770 } 10771 } 10772 if (removedAppId >= 0) { 10773 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10774 removedUsers); 10775 } 10776 } 10777 } 10778 10779 /* 10780 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10781 * flag is not set, the data directory is removed as well. 10782 * make sure this flag is set for partially installed apps. If not its meaningless to 10783 * delete a partially installed application. 10784 */ 10785 private void removePackageDataLI(PackageSetting ps, 10786 int[] allUserHandles, boolean[] perUserInstalled, 10787 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10788 String packageName = ps.name; 10789 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10790 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10791 // Retrieve object to delete permissions for shared user later on 10792 final PackageSetting deletedPs; 10793 // reader 10794 synchronized (mPackages) { 10795 deletedPs = mSettings.mPackages.get(packageName); 10796 if (outInfo != null) { 10797 outInfo.removedPackage = packageName; 10798 outInfo.removedUsers = deletedPs != null 10799 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10800 : null; 10801 } 10802 } 10803 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10804 removeDataDirsLI(packageName); 10805 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10806 } 10807 // writer 10808 synchronized (mPackages) { 10809 if (deletedPs != null) { 10810 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10811 if (outInfo != null) { 10812 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10813 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10814 } 10815 if (deletedPs != null) { 10816 updatePermissionsLPw(deletedPs.name, null, 0); 10817 if (deletedPs.sharedUser != null) { 10818 // remove permissions associated with package 10819 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10820 } 10821 } 10822 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10823 } 10824 // make sure to preserve per-user disabled state if this removal was just 10825 // a downgrade of a system app to the factory package 10826 if (allUserHandles != null && perUserInstalled != null) { 10827 if (DEBUG_REMOVE) { 10828 Slog.d(TAG, "Propagating install state across downgrade"); 10829 } 10830 for (int i = 0; i < allUserHandles.length; i++) { 10831 if (DEBUG_REMOVE) { 10832 Slog.d(TAG, " user " + allUserHandles[i] 10833 + " => " + perUserInstalled[i]); 10834 } 10835 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10836 } 10837 } 10838 } 10839 // can downgrade to reader 10840 if (writeSettings) { 10841 // Save settings now 10842 mSettings.writeLPr(); 10843 } 10844 } 10845 if (outInfo != null) { 10846 // A user ID was deleted here. Go through all users and remove it 10847 // from KeyStore. 10848 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10849 } 10850 } 10851 10852 static boolean locationIsPrivileged(File path) { 10853 try { 10854 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10855 .getCanonicalPath(); 10856 return path.getCanonicalPath().startsWith(privilegedAppDir); 10857 } catch (IOException e) { 10858 Slog.e(TAG, "Unable to access code path " + path); 10859 } 10860 return false; 10861 } 10862 10863 /* 10864 * Tries to delete system package. 10865 */ 10866 private boolean deleteSystemPackageLI(PackageSetting newPs, 10867 int[] allUserHandles, boolean[] perUserInstalled, 10868 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10869 final boolean applyUserRestrictions 10870 = (allUserHandles != null) && (perUserInstalled != null); 10871 PackageSetting disabledPs = null; 10872 // Confirm if the system package has been updated 10873 // An updated system app can be deleted. This will also have to restore 10874 // the system pkg from system partition 10875 // reader 10876 synchronized (mPackages) { 10877 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10878 } 10879 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10880 + " disabledPs=" + disabledPs); 10881 if (disabledPs == null) { 10882 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10883 return false; 10884 } else if (DEBUG_REMOVE) { 10885 Slog.d(TAG, "Deleting system pkg from data partition"); 10886 } 10887 if (DEBUG_REMOVE) { 10888 if (applyUserRestrictions) { 10889 Slog.d(TAG, "Remembering install states:"); 10890 for (int i = 0; i < allUserHandles.length; i++) { 10891 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10892 } 10893 } 10894 } 10895 // Delete the updated package 10896 outInfo.isRemovedPackageSystemUpdate = true; 10897 if (disabledPs.versionCode < newPs.versionCode) { 10898 // Delete data for downgrades 10899 flags &= ~PackageManager.DELETE_KEEP_DATA; 10900 } else { 10901 // Preserve data by setting flag 10902 flags |= PackageManager.DELETE_KEEP_DATA; 10903 } 10904 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10905 allUserHandles, perUserInstalled, outInfo, writeSettings); 10906 if (!ret) { 10907 return false; 10908 } 10909 // writer 10910 synchronized (mPackages) { 10911 // Reinstate the old system package 10912 mSettings.enableSystemPackageLPw(newPs.name); 10913 // Remove any native libraries from the upgraded package. 10914 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10915 } 10916 // Install the system package 10917 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10918 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10919 if (locationIsPrivileged(disabledPs.codePath)) { 10920 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10921 } 10922 10923 final PackageParser.Package newPkg; 10924 try { 10925 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null); 10926 } catch (PackageManagerException e) { 10927 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10928 return false; 10929 } 10930 10931 // writer 10932 synchronized (mPackages) { 10933 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10934 updatePermissionsLPw(newPkg.packageName, newPkg, 10935 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10936 if (applyUserRestrictions) { 10937 if (DEBUG_REMOVE) { 10938 Slog.d(TAG, "Propagating install state across reinstall"); 10939 } 10940 for (int i = 0; i < allUserHandles.length; i++) { 10941 if (DEBUG_REMOVE) { 10942 Slog.d(TAG, " user " + allUserHandles[i] 10943 + " => " + perUserInstalled[i]); 10944 } 10945 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10946 } 10947 // Regardless of writeSettings we need to ensure that this restriction 10948 // state propagation is persisted 10949 mSettings.writeAllUsersPackageRestrictionsLPr(); 10950 } 10951 // can downgrade to reader here 10952 if (writeSettings) { 10953 mSettings.writeLPr(); 10954 } 10955 } 10956 return true; 10957 } 10958 10959 private boolean deleteInstalledPackageLI(PackageSetting ps, 10960 boolean deleteCodeAndResources, int flags, 10961 int[] allUserHandles, boolean[] perUserInstalled, 10962 PackageRemovedInfo outInfo, boolean writeSettings) { 10963 if (outInfo != null) { 10964 outInfo.uid = ps.appId; 10965 } 10966 10967 // Delete package data from internal structures and also remove data if flag is set 10968 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10969 10970 // Delete application code and resources 10971 if (deleteCodeAndResources && (outInfo != null)) { 10972 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10973 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10974 getAppDexInstructionSets(ps), isMultiArch(ps)); 10975 } 10976 return true; 10977 } 10978 10979 @Override 10980 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10981 int userId) { 10982 mContext.enforceCallingOrSelfPermission( 10983 android.Manifest.permission.DELETE_PACKAGES, null); 10984 synchronized (mPackages) { 10985 PackageSetting ps = mSettings.mPackages.get(packageName); 10986 if (ps == null) { 10987 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10988 return false; 10989 } 10990 if (!ps.getInstalled(userId)) { 10991 // Can't block uninstall for an app that is not installed or enabled. 10992 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10993 return false; 10994 } 10995 ps.setBlockUninstall(blockUninstall, userId); 10996 mSettings.writePackageRestrictionsLPr(userId); 10997 } 10998 return true; 10999 } 11000 11001 @Override 11002 public boolean getBlockUninstallForUser(String packageName, int userId) { 11003 synchronized (mPackages) { 11004 PackageSetting ps = mSettings.mPackages.get(packageName); 11005 if (ps == null) { 11006 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11007 return false; 11008 } 11009 return ps.getBlockUninstall(userId); 11010 } 11011 } 11012 11013 /* 11014 * This method handles package deletion in general 11015 */ 11016 private boolean deletePackageLI(String packageName, UserHandle user, 11017 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11018 int flags, PackageRemovedInfo outInfo, 11019 boolean writeSettings) { 11020 if (packageName == null) { 11021 Slog.w(TAG, "Attempt to delete null packageName."); 11022 return false; 11023 } 11024 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11025 PackageSetting ps; 11026 boolean dataOnly = false; 11027 int removeUser = -1; 11028 int appId = -1; 11029 synchronized (mPackages) { 11030 ps = mSettings.mPackages.get(packageName); 11031 if (ps == null) { 11032 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11033 return false; 11034 } 11035 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11036 && user.getIdentifier() != UserHandle.USER_ALL) { 11037 // The caller is asking that the package only be deleted for a single 11038 // user. To do this, we just mark its uninstalled state and delete 11039 // its data. If this is a system app, we only allow this to happen if 11040 // they have set the special DELETE_SYSTEM_APP which requests different 11041 // semantics than normal for uninstalling system apps. 11042 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11043 ps.setUserState(user.getIdentifier(), 11044 COMPONENT_ENABLED_STATE_DEFAULT, 11045 false, //installed 11046 true, //stopped 11047 true, //notLaunched 11048 false, //hidden 11049 null, null, null, 11050 false // blockUninstall 11051 ); 11052 if (!isSystemApp(ps)) { 11053 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11054 // Other user still have this package installed, so all 11055 // we need to do is clear this user's data and save that 11056 // it is uninstalled. 11057 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11058 removeUser = user.getIdentifier(); 11059 appId = ps.appId; 11060 mSettings.writePackageRestrictionsLPr(removeUser); 11061 } else { 11062 // We need to set it back to 'installed' so the uninstall 11063 // broadcasts will be sent correctly. 11064 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11065 ps.setInstalled(true, user.getIdentifier()); 11066 } 11067 } else { 11068 // This is a system app, so we assume that the 11069 // other users still have this package installed, so all 11070 // we need to do is clear this user's data and save that 11071 // it is uninstalled. 11072 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11073 removeUser = user.getIdentifier(); 11074 appId = ps.appId; 11075 mSettings.writePackageRestrictionsLPr(removeUser); 11076 } 11077 } 11078 } 11079 11080 if (removeUser >= 0) { 11081 // From above, we determined that we are deleting this only 11082 // for a single user. Continue the work here. 11083 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11084 if (outInfo != null) { 11085 outInfo.removedPackage = packageName; 11086 outInfo.removedAppId = appId; 11087 outInfo.removedUsers = new int[] {removeUser}; 11088 } 11089 mInstaller.clearUserData(packageName, removeUser); 11090 removeKeystoreDataIfNeeded(removeUser, appId); 11091 schedulePackageCleaning(packageName, removeUser, false); 11092 return true; 11093 } 11094 11095 if (dataOnly) { 11096 // Delete application data first 11097 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11098 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11099 return true; 11100 } 11101 11102 boolean ret = false; 11103 if (isSystemApp(ps)) { 11104 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11105 // When an updated system application is deleted we delete the existing resources as well and 11106 // fall back to existing code in system partition 11107 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11108 flags, outInfo, writeSettings); 11109 } else { 11110 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11111 // Kill application pre-emptively especially for apps on sd. 11112 killApplication(packageName, ps.appId, "uninstall pkg"); 11113 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11114 allUserHandles, perUserInstalled, 11115 outInfo, writeSettings); 11116 } 11117 11118 return ret; 11119 } 11120 11121 private final class ClearStorageConnection implements ServiceConnection { 11122 IMediaContainerService mContainerService; 11123 11124 @Override 11125 public void onServiceConnected(ComponentName name, IBinder service) { 11126 synchronized (this) { 11127 mContainerService = IMediaContainerService.Stub.asInterface(service); 11128 notifyAll(); 11129 } 11130 } 11131 11132 @Override 11133 public void onServiceDisconnected(ComponentName name) { 11134 } 11135 } 11136 11137 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11138 final boolean mounted; 11139 if (Environment.isExternalStorageEmulated()) { 11140 mounted = true; 11141 } else { 11142 final String status = Environment.getExternalStorageState(); 11143 11144 mounted = status.equals(Environment.MEDIA_MOUNTED) 11145 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11146 } 11147 11148 if (!mounted) { 11149 return; 11150 } 11151 11152 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11153 int[] users; 11154 if (userId == UserHandle.USER_ALL) { 11155 users = sUserManager.getUserIds(); 11156 } else { 11157 users = new int[] { userId }; 11158 } 11159 final ClearStorageConnection conn = new ClearStorageConnection(); 11160 if (mContext.bindServiceAsUser( 11161 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11162 try { 11163 for (int curUser : users) { 11164 long timeout = SystemClock.uptimeMillis() + 5000; 11165 synchronized (conn) { 11166 long now = SystemClock.uptimeMillis(); 11167 while (conn.mContainerService == null && now < timeout) { 11168 try { 11169 conn.wait(timeout - now); 11170 } catch (InterruptedException e) { 11171 } 11172 } 11173 } 11174 if (conn.mContainerService == null) { 11175 return; 11176 } 11177 11178 final UserEnvironment userEnv = new UserEnvironment(curUser); 11179 clearDirectory(conn.mContainerService, 11180 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11181 if (allData) { 11182 clearDirectory(conn.mContainerService, 11183 userEnv.buildExternalStorageAppDataDirs(packageName)); 11184 clearDirectory(conn.mContainerService, 11185 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11186 } 11187 } 11188 } finally { 11189 mContext.unbindService(conn); 11190 } 11191 } 11192 } 11193 11194 @Override 11195 public void clearApplicationUserData(final String packageName, 11196 final IPackageDataObserver observer, final int userId) { 11197 mContext.enforceCallingOrSelfPermission( 11198 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11199 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11200 // Queue up an async operation since the package deletion may take a little while. 11201 mHandler.post(new Runnable() { 11202 public void run() { 11203 mHandler.removeCallbacks(this); 11204 final boolean succeeded; 11205 synchronized (mInstallLock) { 11206 succeeded = clearApplicationUserDataLI(packageName, userId); 11207 } 11208 clearExternalStorageDataSync(packageName, userId, true); 11209 if (succeeded) { 11210 // invoke DeviceStorageMonitor's update method to clear any notifications 11211 DeviceStorageMonitorInternal 11212 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11213 if (dsm != null) { 11214 dsm.checkMemory(); 11215 } 11216 } 11217 if(observer != null) { 11218 try { 11219 observer.onRemoveCompleted(packageName, succeeded); 11220 } catch (RemoteException e) { 11221 Log.i(TAG, "Observer no longer exists."); 11222 } 11223 } //end if observer 11224 } //end run 11225 }); 11226 } 11227 11228 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11229 if (packageName == null) { 11230 Slog.w(TAG, "Attempt to delete null packageName."); 11231 return false; 11232 } 11233 PackageParser.Package p; 11234 boolean dataOnly = false; 11235 final int appId; 11236 synchronized (mPackages) { 11237 p = mPackages.get(packageName); 11238 if (p == null) { 11239 dataOnly = true; 11240 PackageSetting ps = mSettings.mPackages.get(packageName); 11241 if ((ps == null) || (ps.pkg == null)) { 11242 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11243 return false; 11244 } 11245 p = ps.pkg; 11246 } 11247 if (!dataOnly) { 11248 // need to check this only for fully installed applications 11249 if (p == null) { 11250 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11251 return false; 11252 } 11253 final ApplicationInfo applicationInfo = p.applicationInfo; 11254 if (applicationInfo == null) { 11255 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11256 return false; 11257 } 11258 } 11259 if (p != null && p.applicationInfo != null) { 11260 appId = p.applicationInfo.uid; 11261 } else { 11262 appId = -1; 11263 } 11264 } 11265 int retCode = mInstaller.clearUserData(packageName, userId); 11266 if (retCode < 0) { 11267 Slog.w(TAG, "Couldn't remove cache files for package: " 11268 + packageName); 11269 return false; 11270 } 11271 removeKeystoreDataIfNeeded(userId, appId); 11272 return true; 11273 } 11274 11275 /** 11276 * Remove entries from the keystore daemon. Will only remove it if the 11277 * {@code appId} is valid. 11278 */ 11279 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11280 if (appId < 0) { 11281 return; 11282 } 11283 11284 final KeyStore keyStore = KeyStore.getInstance(); 11285 if (keyStore != null) { 11286 if (userId == UserHandle.USER_ALL) { 11287 for (final int individual : sUserManager.getUserIds()) { 11288 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11289 } 11290 } else { 11291 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11292 } 11293 } else { 11294 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11295 } 11296 } 11297 11298 @Override 11299 public void deleteApplicationCacheFiles(final String packageName, 11300 final IPackageDataObserver observer) { 11301 mContext.enforceCallingOrSelfPermission( 11302 android.Manifest.permission.DELETE_CACHE_FILES, null); 11303 // Queue up an async operation since the package deletion may take a little while. 11304 final int userId = UserHandle.getCallingUserId(); 11305 mHandler.post(new Runnable() { 11306 public void run() { 11307 mHandler.removeCallbacks(this); 11308 final boolean succeded; 11309 synchronized (mInstallLock) { 11310 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11311 } 11312 clearExternalStorageDataSync(packageName, userId, false); 11313 if(observer != null) { 11314 try { 11315 observer.onRemoveCompleted(packageName, succeded); 11316 } catch (RemoteException e) { 11317 Log.i(TAG, "Observer no longer exists."); 11318 } 11319 } //end if observer 11320 } //end run 11321 }); 11322 } 11323 11324 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11325 if (packageName == null) { 11326 Slog.w(TAG, "Attempt to delete null packageName."); 11327 return false; 11328 } 11329 PackageParser.Package p; 11330 synchronized (mPackages) { 11331 p = mPackages.get(packageName); 11332 } 11333 if (p == null) { 11334 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11335 return false; 11336 } 11337 final ApplicationInfo applicationInfo = p.applicationInfo; 11338 if (applicationInfo == null) { 11339 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11340 return false; 11341 } 11342 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11343 if (retCode < 0) { 11344 Slog.w(TAG, "Couldn't remove cache files for package: " 11345 + packageName + " u" + userId); 11346 return false; 11347 } 11348 return true; 11349 } 11350 11351 @Override 11352 public void getPackageSizeInfo(final String packageName, int userHandle, 11353 final IPackageStatsObserver observer) { 11354 mContext.enforceCallingOrSelfPermission( 11355 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11356 if (packageName == null) { 11357 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11358 } 11359 11360 PackageStats stats = new PackageStats(packageName, userHandle); 11361 11362 /* 11363 * Queue up an async operation since the package measurement may take a 11364 * little while. 11365 */ 11366 Message msg = mHandler.obtainMessage(INIT_COPY); 11367 msg.obj = new MeasureParams(stats, observer); 11368 mHandler.sendMessage(msg); 11369 } 11370 11371 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11372 PackageStats pStats) { 11373 if (packageName == null) { 11374 Slog.w(TAG, "Attempt to get size of null packageName."); 11375 return false; 11376 } 11377 PackageParser.Package p; 11378 boolean dataOnly = false; 11379 String libDirRoot = null; 11380 String asecPath = null; 11381 PackageSetting ps = null; 11382 synchronized (mPackages) { 11383 p = mPackages.get(packageName); 11384 ps = mSettings.mPackages.get(packageName); 11385 if(p == null) { 11386 dataOnly = true; 11387 if((ps == null) || (ps.pkg == null)) { 11388 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11389 return false; 11390 } 11391 p = ps.pkg; 11392 } 11393 if (ps != null) { 11394 libDirRoot = ps.legacyNativeLibraryPathString; 11395 } 11396 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11397 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11398 if (secureContainerId != null) { 11399 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11400 } 11401 } 11402 } 11403 String publicSrcDir = null; 11404 if(!dataOnly) { 11405 final ApplicationInfo applicationInfo = p.applicationInfo; 11406 if (applicationInfo == null) { 11407 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11408 return false; 11409 } 11410 if (isForwardLocked(p)) { 11411 publicSrcDir = applicationInfo.getBaseResourcePath(); 11412 } 11413 } 11414 // TODO: extend to measure size of split APKs 11415 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11416 // not just the first level. 11417 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11418 // just the primary. 11419 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11420 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11421 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11422 if (res < 0) { 11423 return false; 11424 } 11425 11426 // Fix-up for forward-locked applications in ASEC containers. 11427 if (!isExternal(p)) { 11428 pStats.codeSize += pStats.externalCodeSize; 11429 pStats.externalCodeSize = 0L; 11430 } 11431 11432 return true; 11433 } 11434 11435 11436 @Override 11437 public void addPackageToPreferred(String packageName) { 11438 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11439 } 11440 11441 @Override 11442 public void removePackageFromPreferred(String packageName) { 11443 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11444 } 11445 11446 @Override 11447 public List<PackageInfo> getPreferredPackages(int flags) { 11448 return new ArrayList<PackageInfo>(); 11449 } 11450 11451 private int getUidTargetSdkVersionLockedLPr(int uid) { 11452 Object obj = mSettings.getUserIdLPr(uid); 11453 if (obj instanceof SharedUserSetting) { 11454 final SharedUserSetting sus = (SharedUserSetting) obj; 11455 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11456 final Iterator<PackageSetting> it = sus.packages.iterator(); 11457 while (it.hasNext()) { 11458 final PackageSetting ps = it.next(); 11459 if (ps.pkg != null) { 11460 int v = ps.pkg.applicationInfo.targetSdkVersion; 11461 if (v < vers) vers = v; 11462 } 11463 } 11464 return vers; 11465 } else if (obj instanceof PackageSetting) { 11466 final PackageSetting ps = (PackageSetting) obj; 11467 if (ps.pkg != null) { 11468 return ps.pkg.applicationInfo.targetSdkVersion; 11469 } 11470 } 11471 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11472 } 11473 11474 @Override 11475 public void addPreferredActivity(IntentFilter filter, int match, 11476 ComponentName[] set, ComponentName activity, int userId) { 11477 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11478 "Adding preferred"); 11479 } 11480 11481 private void addPreferredActivityInternal(IntentFilter filter, int match, 11482 ComponentName[] set, ComponentName activity, boolean always, int userId, 11483 String opname) { 11484 // writer 11485 int callingUid = Binder.getCallingUid(); 11486 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11487 if (filter.countActions() == 0) { 11488 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11489 return; 11490 } 11491 synchronized (mPackages) { 11492 if (mContext.checkCallingOrSelfPermission( 11493 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11494 != PackageManager.PERMISSION_GRANTED) { 11495 if (getUidTargetSdkVersionLockedLPr(callingUid) 11496 < Build.VERSION_CODES.FROYO) { 11497 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11498 + callingUid); 11499 return; 11500 } 11501 mContext.enforceCallingOrSelfPermission( 11502 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11503 } 11504 11505 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11506 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11507 + userId + ":"); 11508 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11509 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11510 mSettings.writePackageRestrictionsLPr(userId); 11511 } 11512 } 11513 11514 @Override 11515 public void replacePreferredActivity(IntentFilter filter, int match, 11516 ComponentName[] set, ComponentName activity, int userId) { 11517 if (filter.countActions() != 1) { 11518 throw new IllegalArgumentException( 11519 "replacePreferredActivity expects filter to have only 1 action."); 11520 } 11521 if (filter.countDataAuthorities() != 0 11522 || filter.countDataPaths() != 0 11523 || filter.countDataSchemes() > 1 11524 || filter.countDataTypes() != 0) { 11525 throw new IllegalArgumentException( 11526 "replacePreferredActivity expects filter to have no data authorities, " + 11527 "paths, or types; and at most one scheme."); 11528 } 11529 11530 final int callingUid = Binder.getCallingUid(); 11531 enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity"); 11532 synchronized (mPackages) { 11533 if (mContext.checkCallingOrSelfPermission( 11534 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11535 != PackageManager.PERMISSION_GRANTED) { 11536 if (getUidTargetSdkVersionLockedLPr(callingUid) 11537 < Build.VERSION_CODES.FROYO) { 11538 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11539 + Binder.getCallingUid()); 11540 return; 11541 } 11542 mContext.enforceCallingOrSelfPermission( 11543 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11544 } 11545 11546 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11547 if (pir != null) { 11548 // Get all of the existing entries that exactly match this filter. 11549 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11550 if (existing != null && existing.size() == 1) { 11551 PreferredActivity cur = existing.get(0); 11552 if (DEBUG_PREFERRED) { 11553 Slog.i(TAG, "Checking replace of preferred:"); 11554 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11555 if (!cur.mPref.mAlways) { 11556 Slog.i(TAG, " -- CUR; not mAlways!"); 11557 } else { 11558 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11559 Slog.i(TAG, " -- CUR: mSet=" 11560 + Arrays.toString(cur.mPref.mSetComponents)); 11561 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11562 Slog.i(TAG, " -- NEW: mMatch=" 11563 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11564 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11565 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11566 } 11567 } 11568 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11569 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11570 && cur.mPref.sameSet(set)) { 11571 if (DEBUG_PREFERRED) { 11572 Slog.i(TAG, "Replacing with same preferred activity " 11573 + cur.mPref.mShortComponent + " for user " 11574 + userId + ":"); 11575 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11576 } else { 11577 Slog.i(TAG, "Replacing with same preferred activity " 11578 + cur.mPref.mShortComponent + " for user " 11579 + userId); 11580 } 11581 return; 11582 } 11583 } 11584 11585 if (DEBUG_PREFERRED) { 11586 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11587 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11588 } 11589 for (int i = 0; i < existing.size(); i++) { 11590 PreferredActivity pa = existing.get(i); 11591 if (DEBUG_PREFERRED) { 11592 Slog.i(TAG, "Removing existing preferred activity " 11593 + pa.mPref.mComponent + ":"); 11594 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11595 } 11596 pir.removeFilter(pa); 11597 } 11598 } 11599 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11600 "Replacing preferred"); 11601 } 11602 } 11603 11604 @Override 11605 public void clearPackagePreferredActivities(String packageName) { 11606 final int uid = Binder.getCallingUid(); 11607 // writer 11608 synchronized (mPackages) { 11609 PackageParser.Package pkg = mPackages.get(packageName); 11610 if (pkg == null || pkg.applicationInfo.uid != uid) { 11611 if (mContext.checkCallingOrSelfPermission( 11612 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11613 != PackageManager.PERMISSION_GRANTED) { 11614 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11615 < Build.VERSION_CODES.FROYO) { 11616 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11617 + Binder.getCallingUid()); 11618 return; 11619 } 11620 mContext.enforceCallingOrSelfPermission( 11621 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11622 } 11623 } 11624 11625 int user = UserHandle.getCallingUserId(); 11626 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11627 mSettings.writePackageRestrictionsLPr(user); 11628 scheduleWriteSettingsLocked(); 11629 } 11630 } 11631 } 11632 11633 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11634 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11635 ArrayList<PreferredActivity> removed = null; 11636 boolean changed = false; 11637 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11638 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11639 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11640 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11641 continue; 11642 } 11643 Iterator<PreferredActivity> it = pir.filterIterator(); 11644 while (it.hasNext()) { 11645 PreferredActivity pa = it.next(); 11646 // Mark entry for removal only if it matches the package name 11647 // and the entry is of type "always". 11648 if (packageName == null || 11649 (pa.mPref.mComponent.getPackageName().equals(packageName) 11650 && pa.mPref.mAlways)) { 11651 if (removed == null) { 11652 removed = new ArrayList<PreferredActivity>(); 11653 } 11654 removed.add(pa); 11655 } 11656 } 11657 if (removed != null) { 11658 for (int j=0; j<removed.size(); j++) { 11659 PreferredActivity pa = removed.get(j); 11660 pir.removeFilter(pa); 11661 } 11662 changed = true; 11663 } 11664 } 11665 return changed; 11666 } 11667 11668 @Override 11669 public void resetPreferredActivities(int userId) { 11670 mContext.enforceCallingOrSelfPermission( 11671 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11672 // writer 11673 synchronized (mPackages) { 11674 int user = UserHandle.getCallingUserId(); 11675 clearPackagePreferredActivitiesLPw(null, user); 11676 mSettings.readDefaultPreferredAppsLPw(this, user); 11677 mSettings.writePackageRestrictionsLPr(user); 11678 scheduleWriteSettingsLocked(); 11679 } 11680 } 11681 11682 @Override 11683 public int getPreferredActivities(List<IntentFilter> outFilters, 11684 List<ComponentName> outActivities, String packageName) { 11685 11686 int num = 0; 11687 final int userId = UserHandle.getCallingUserId(); 11688 // reader 11689 synchronized (mPackages) { 11690 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11691 if (pir != null) { 11692 final Iterator<PreferredActivity> it = pir.filterIterator(); 11693 while (it.hasNext()) { 11694 final PreferredActivity pa = it.next(); 11695 if (packageName == null 11696 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11697 && pa.mPref.mAlways)) { 11698 if (outFilters != null) { 11699 outFilters.add(new IntentFilter(pa)); 11700 } 11701 if (outActivities != null) { 11702 outActivities.add(pa.mPref.mComponent); 11703 } 11704 } 11705 } 11706 } 11707 } 11708 11709 return num; 11710 } 11711 11712 @Override 11713 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11714 int userId) { 11715 int callingUid = Binder.getCallingUid(); 11716 if (callingUid != Process.SYSTEM_UID) { 11717 throw new SecurityException( 11718 "addPersistentPreferredActivity can only be run by the system"); 11719 } 11720 if (filter.countActions() == 0) { 11721 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11722 return; 11723 } 11724 synchronized (mPackages) { 11725 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11726 " :"); 11727 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11728 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11729 new PersistentPreferredActivity(filter, activity)); 11730 mSettings.writePackageRestrictionsLPr(userId); 11731 } 11732 } 11733 11734 @Override 11735 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11736 int callingUid = Binder.getCallingUid(); 11737 if (callingUid != Process.SYSTEM_UID) { 11738 throw new SecurityException( 11739 "clearPackagePersistentPreferredActivities can only be run by the system"); 11740 } 11741 ArrayList<PersistentPreferredActivity> removed = null; 11742 boolean changed = false; 11743 synchronized (mPackages) { 11744 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11745 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11746 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11747 .valueAt(i); 11748 if (userId != thisUserId) { 11749 continue; 11750 } 11751 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11752 while (it.hasNext()) { 11753 PersistentPreferredActivity ppa = it.next(); 11754 // Mark entry for removal only if it matches the package name. 11755 if (ppa.mComponent.getPackageName().equals(packageName)) { 11756 if (removed == null) { 11757 removed = new ArrayList<PersistentPreferredActivity>(); 11758 } 11759 removed.add(ppa); 11760 } 11761 } 11762 if (removed != null) { 11763 for (int j=0; j<removed.size(); j++) { 11764 PersistentPreferredActivity ppa = removed.get(j); 11765 ppir.removeFilter(ppa); 11766 } 11767 changed = true; 11768 } 11769 } 11770 11771 if (changed) { 11772 mSettings.writePackageRestrictionsLPr(userId); 11773 } 11774 } 11775 } 11776 11777 @Override 11778 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11779 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11780 mContext.enforceCallingOrSelfPermission( 11781 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11782 int callingUid = Binder.getCallingUid(); 11783 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11784 if (intentFilter.countActions() == 0) { 11785 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11786 return; 11787 } 11788 synchronized (mPackages) { 11789 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11790 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11791 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11792 mSettings.writePackageRestrictionsLPr(sourceUserId); 11793 } 11794 } 11795 11796 @Override 11797 public void addCrossProfileIntentsForPackage(String packageName, 11798 int sourceUserId, int targetUserId) { 11799 mContext.enforceCallingOrSelfPermission( 11800 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11801 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11802 mSettings.writePackageRestrictionsLPr(sourceUserId); 11803 } 11804 11805 @Override 11806 public void removeCrossProfileIntentsForPackage(String packageName, 11807 int sourceUserId, int targetUserId) { 11808 mContext.enforceCallingOrSelfPermission( 11809 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11810 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11811 mSettings.writePackageRestrictionsLPr(sourceUserId); 11812 } 11813 11814 @Override 11815 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11816 int ownerUserId) { 11817 mContext.enforceCallingOrSelfPermission( 11818 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11819 int callingUid = Binder.getCallingUid(); 11820 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11821 int callingUserId = UserHandle.getUserId(callingUid); 11822 synchronized (mPackages) { 11823 CrossProfileIntentResolver resolver = 11824 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11825 HashSet<CrossProfileIntentFilter> set = 11826 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11827 for (CrossProfileIntentFilter filter : set) { 11828 if (filter.getOwnerPackage().equals(ownerPackage) 11829 && filter.getOwnerUserId() == callingUserId) { 11830 resolver.removeFilter(filter); 11831 } 11832 } 11833 mSettings.writePackageRestrictionsLPr(sourceUserId); 11834 } 11835 } 11836 11837 // Enforcing that callingUid is owning pkg on userId 11838 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11839 // The system owns everything. 11840 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11841 return; 11842 } 11843 int callingUserId = UserHandle.getUserId(callingUid); 11844 if (callingUserId != userId) { 11845 throw new SecurityException("calling uid " + callingUid 11846 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11847 + callingUserId); 11848 } 11849 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11850 if (pi == null) { 11851 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11852 + callingUserId); 11853 } 11854 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11855 throw new SecurityException("Calling uid " + callingUid 11856 + " does not own package " + pkg); 11857 } 11858 } 11859 11860 @Override 11861 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11862 Intent intent = new Intent(Intent.ACTION_MAIN); 11863 intent.addCategory(Intent.CATEGORY_HOME); 11864 11865 final int callingUserId = UserHandle.getCallingUserId(); 11866 List<ResolveInfo> list = queryIntentActivities(intent, null, 11867 PackageManager.GET_META_DATA, callingUserId); 11868 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11869 true, false, false, callingUserId); 11870 11871 allHomeCandidates.clear(); 11872 if (list != null) { 11873 for (ResolveInfo ri : list) { 11874 allHomeCandidates.add(ri); 11875 } 11876 } 11877 return (preferred == null || preferred.activityInfo == null) 11878 ? null 11879 : new ComponentName(preferred.activityInfo.packageName, 11880 preferred.activityInfo.name); 11881 } 11882 11883 /** 11884 * Check if calling UID is the current home app. This handles both the case 11885 * where the user has selected a specific home app, and where there is only 11886 * one home app. 11887 */ 11888 public boolean checkCallerIsHomeApp() { 11889 final Intent intent = new Intent(Intent.ACTION_MAIN); 11890 intent.addCategory(Intent.CATEGORY_HOME); 11891 11892 final int callingUid = Binder.getCallingUid(); 11893 final int callingUserId = UserHandle.getCallingUserId(); 11894 final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId); 11895 final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true, 11896 false, false, callingUserId); 11897 11898 if (preferredHome != null) { 11899 if (callingUid == preferredHome.activityInfo.applicationInfo.uid) { 11900 return true; 11901 } 11902 } else { 11903 for (ResolveInfo info : allHomes) { 11904 if (callingUid == info.activityInfo.applicationInfo.uid) { 11905 return true; 11906 } 11907 } 11908 } 11909 11910 return false; 11911 } 11912 11913 /** 11914 * Enforce that calling UID is the current home app. This handles both the 11915 * case where the user has selected a specific home app, and where there is 11916 * only one home app. 11917 */ 11918 public void enforceCallerIsHomeApp() { 11919 if (!checkCallerIsHomeApp()) { 11920 throw new SecurityException("Caller is not currently selected home app"); 11921 } 11922 } 11923 11924 @Override 11925 public void setApplicationEnabledSetting(String appPackageName, 11926 int newState, int flags, int userId, String callingPackage) { 11927 if (!sUserManager.exists(userId)) return; 11928 if (callingPackage == null) { 11929 callingPackage = Integer.toString(Binder.getCallingUid()); 11930 } 11931 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11932 } 11933 11934 @Override 11935 public void setComponentEnabledSetting(ComponentName componentName, 11936 int newState, int flags, int userId) { 11937 if (!sUserManager.exists(userId)) return; 11938 setEnabledSetting(componentName.getPackageName(), 11939 componentName.getClassName(), newState, flags, userId, null); 11940 } 11941 11942 private void setEnabledSetting(final String packageName, String className, int newState, 11943 final int flags, int userId, String callingPackage) { 11944 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11945 || newState == COMPONENT_ENABLED_STATE_ENABLED 11946 || newState == COMPONENT_ENABLED_STATE_DISABLED 11947 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11948 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11949 throw new IllegalArgumentException("Invalid new component state: " 11950 + newState); 11951 } 11952 PackageSetting pkgSetting; 11953 final int uid = Binder.getCallingUid(); 11954 final int permission = mContext.checkCallingOrSelfPermission( 11955 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11956 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11957 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11958 boolean sendNow = false; 11959 boolean isApp = (className == null); 11960 String componentName = isApp ? packageName : className; 11961 int packageUid = -1; 11962 ArrayList<String> components; 11963 11964 // writer 11965 synchronized (mPackages) { 11966 pkgSetting = mSettings.mPackages.get(packageName); 11967 if (pkgSetting == null) { 11968 if (className == null) { 11969 throw new IllegalArgumentException( 11970 "Unknown package: " + packageName); 11971 } 11972 throw new IllegalArgumentException( 11973 "Unknown component: " + packageName 11974 + "/" + className); 11975 } 11976 // Allow root and verify that userId is not being specified by a different user 11977 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11978 throw new SecurityException( 11979 "Permission Denial: attempt to change component state from pid=" 11980 + Binder.getCallingPid() 11981 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11982 } 11983 if (className == null) { 11984 // We're dealing with an application/package level state change 11985 if (pkgSetting.getEnabled(userId) == newState) { 11986 // Nothing to do 11987 return; 11988 } 11989 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11990 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11991 // Don't care about who enables an app. 11992 callingPackage = null; 11993 } 11994 pkgSetting.setEnabled(newState, userId, callingPackage); 11995 // pkgSetting.pkg.mSetEnabled = newState; 11996 } else { 11997 // We're dealing with a component level state change 11998 // First, verify that this is a valid class name. 11999 PackageParser.Package pkg = pkgSetting.pkg; 12000 if (pkg == null || !pkg.hasComponentClassName(className)) { 12001 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 12002 throw new IllegalArgumentException("Component class " + className 12003 + " does not exist in " + packageName); 12004 } else { 12005 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 12006 + className + " does not exist in " + packageName); 12007 } 12008 } 12009 switch (newState) { 12010 case COMPONENT_ENABLED_STATE_ENABLED: 12011 if (!pkgSetting.enableComponentLPw(className, userId)) { 12012 return; 12013 } 12014 break; 12015 case COMPONENT_ENABLED_STATE_DISABLED: 12016 if (!pkgSetting.disableComponentLPw(className, userId)) { 12017 return; 12018 } 12019 break; 12020 case COMPONENT_ENABLED_STATE_DEFAULT: 12021 if (!pkgSetting.restoreComponentLPw(className, userId)) { 12022 return; 12023 } 12024 break; 12025 default: 12026 Slog.e(TAG, "Invalid new component state: " + newState); 12027 return; 12028 } 12029 } 12030 mSettings.writePackageRestrictionsLPr(userId); 12031 components = mPendingBroadcasts.get(userId, packageName); 12032 final boolean newPackage = components == null; 12033 if (newPackage) { 12034 components = new ArrayList<String>(); 12035 } 12036 if (!components.contains(componentName)) { 12037 components.add(componentName); 12038 } 12039 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 12040 sendNow = true; 12041 // Purge entry from pending broadcast list if another one exists already 12042 // since we are sending one right away. 12043 mPendingBroadcasts.remove(userId, packageName); 12044 } else { 12045 if (newPackage) { 12046 mPendingBroadcasts.put(userId, packageName, components); 12047 } 12048 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12049 // Schedule a message 12050 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12051 } 12052 } 12053 } 12054 12055 long callingId = Binder.clearCallingIdentity(); 12056 try { 12057 if (sendNow) { 12058 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12059 sendPackageChangedBroadcast(packageName, 12060 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12061 } 12062 } finally { 12063 Binder.restoreCallingIdentity(callingId); 12064 } 12065 } 12066 12067 private void sendPackageChangedBroadcast(String packageName, 12068 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12069 if (DEBUG_INSTALL) 12070 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12071 + componentNames); 12072 Bundle extras = new Bundle(4); 12073 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12074 String nameList[] = new String[componentNames.size()]; 12075 componentNames.toArray(nameList); 12076 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12077 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12078 extras.putInt(Intent.EXTRA_UID, packageUid); 12079 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12080 new int[] {UserHandle.getUserId(packageUid)}); 12081 } 12082 12083 @Override 12084 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12085 if (!sUserManager.exists(userId)) return; 12086 final int uid = Binder.getCallingUid(); 12087 final int permission = mContext.checkCallingOrSelfPermission( 12088 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12089 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12090 enforceCrossUserPermission(uid, userId, true, "stop package"); 12091 // writer 12092 synchronized (mPackages) { 12093 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12094 uid, userId)) { 12095 scheduleWritePackageRestrictionsLocked(userId); 12096 } 12097 } 12098 } 12099 12100 @Override 12101 public String getInstallerPackageName(String packageName) { 12102 // reader 12103 synchronized (mPackages) { 12104 return mSettings.getInstallerPackageNameLPr(packageName); 12105 } 12106 } 12107 12108 @Override 12109 public int getApplicationEnabledSetting(String packageName, int userId) { 12110 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12111 int uid = Binder.getCallingUid(); 12112 enforceCrossUserPermission(uid, userId, false, "get enabled"); 12113 // reader 12114 synchronized (mPackages) { 12115 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12116 } 12117 } 12118 12119 @Override 12120 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12121 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12122 int uid = Binder.getCallingUid(); 12123 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 12124 // reader 12125 synchronized (mPackages) { 12126 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12127 } 12128 } 12129 12130 @Override 12131 public void enterSafeMode() { 12132 enforceSystemOrRoot("Only the system can request entering safe mode"); 12133 12134 if (!mSystemReady) { 12135 mSafeMode = true; 12136 } 12137 } 12138 12139 @Override 12140 public void systemReady() { 12141 mSystemReady = true; 12142 12143 // Read the compatibilty setting when the system is ready. 12144 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12145 mContext.getContentResolver(), 12146 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12147 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12148 if (DEBUG_SETTINGS) { 12149 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12150 } 12151 12152 synchronized (mPackages) { 12153 // Verify that all of the preferred activity components actually 12154 // exist. It is possible for applications to be updated and at 12155 // that point remove a previously declared activity component that 12156 // had been set as a preferred activity. We try to clean this up 12157 // the next time we encounter that preferred activity, but it is 12158 // possible for the user flow to never be able to return to that 12159 // situation so here we do a sanity check to make sure we haven't 12160 // left any junk around. 12161 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12162 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12163 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12164 removed.clear(); 12165 for (PreferredActivity pa : pir.filterSet()) { 12166 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12167 removed.add(pa); 12168 } 12169 } 12170 if (removed.size() > 0) { 12171 for (int r=0; r<removed.size(); r++) { 12172 PreferredActivity pa = removed.get(r); 12173 Slog.w(TAG, "Removing dangling preferred activity: " 12174 + pa.mPref.mComponent); 12175 pir.removeFilter(pa); 12176 } 12177 mSettings.writePackageRestrictionsLPr( 12178 mSettings.mPreferredActivities.keyAt(i)); 12179 } 12180 } 12181 } 12182 sUserManager.systemReady(); 12183 } 12184 12185 @Override 12186 public boolean isSafeMode() { 12187 return mSafeMode; 12188 } 12189 12190 @Override 12191 public boolean hasSystemUidErrors() { 12192 return mHasSystemUidErrors; 12193 } 12194 12195 static String arrayToString(int[] array) { 12196 StringBuffer buf = new StringBuffer(128); 12197 buf.append('['); 12198 if (array != null) { 12199 for (int i=0; i<array.length; i++) { 12200 if (i > 0) buf.append(", "); 12201 buf.append(array[i]); 12202 } 12203 } 12204 buf.append(']'); 12205 return buf.toString(); 12206 } 12207 12208 static class DumpState { 12209 public static final int DUMP_LIBS = 1 << 0; 12210 public static final int DUMP_FEATURES = 1 << 1; 12211 public static final int DUMP_RESOLVERS = 1 << 2; 12212 public static final int DUMP_PERMISSIONS = 1 << 3; 12213 public static final int DUMP_PACKAGES = 1 << 4; 12214 public static final int DUMP_SHARED_USERS = 1 << 5; 12215 public static final int DUMP_MESSAGES = 1 << 6; 12216 public static final int DUMP_PROVIDERS = 1 << 7; 12217 public static final int DUMP_VERIFIERS = 1 << 8; 12218 public static final int DUMP_PREFERRED = 1 << 9; 12219 public static final int DUMP_PREFERRED_XML = 1 << 10; 12220 public static final int DUMP_KEYSETS = 1 << 11; 12221 public static final int DUMP_VERSION = 1 << 12; 12222 public static final int DUMP_INSTALLS = 1 << 13; 12223 12224 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12225 12226 private int mTypes; 12227 12228 private int mOptions; 12229 12230 private boolean mTitlePrinted; 12231 12232 private SharedUserSetting mSharedUser; 12233 12234 public boolean isDumping(int type) { 12235 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12236 return true; 12237 } 12238 12239 return (mTypes & type) != 0; 12240 } 12241 12242 public void setDump(int type) { 12243 mTypes |= type; 12244 } 12245 12246 public boolean isOptionEnabled(int option) { 12247 return (mOptions & option) != 0; 12248 } 12249 12250 public void setOptionEnabled(int option) { 12251 mOptions |= option; 12252 } 12253 12254 public boolean onTitlePrinted() { 12255 final boolean printed = mTitlePrinted; 12256 mTitlePrinted = true; 12257 return printed; 12258 } 12259 12260 public boolean getTitlePrinted() { 12261 return mTitlePrinted; 12262 } 12263 12264 public void setTitlePrinted(boolean enabled) { 12265 mTitlePrinted = enabled; 12266 } 12267 12268 public SharedUserSetting getSharedUser() { 12269 return mSharedUser; 12270 } 12271 12272 public void setSharedUser(SharedUserSetting user) { 12273 mSharedUser = user; 12274 } 12275 } 12276 12277 @Override 12278 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12279 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12280 != PackageManager.PERMISSION_GRANTED) { 12281 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12282 + Binder.getCallingPid() 12283 + ", uid=" + Binder.getCallingUid() 12284 + " without permission " 12285 + android.Manifest.permission.DUMP); 12286 return; 12287 } 12288 12289 DumpState dumpState = new DumpState(); 12290 boolean fullPreferred = false; 12291 boolean checkin = false; 12292 12293 String packageName = null; 12294 12295 int opti = 0; 12296 while (opti < args.length) { 12297 String opt = args[opti]; 12298 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12299 break; 12300 } 12301 opti++; 12302 if ("-a".equals(opt)) { 12303 // Right now we only know how to print all. 12304 } else if ("-h".equals(opt)) { 12305 pw.println("Package manager dump options:"); 12306 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12307 pw.println(" --checkin: dump for a checkin"); 12308 pw.println(" -f: print details of intent filters"); 12309 pw.println(" -h: print this help"); 12310 pw.println(" cmd may be one of:"); 12311 pw.println(" l[ibraries]: list known shared libraries"); 12312 pw.println(" f[ibraries]: list device features"); 12313 pw.println(" k[eysets]: print known keysets"); 12314 pw.println(" r[esolvers]: dump intent resolvers"); 12315 pw.println(" perm[issions]: dump permissions"); 12316 pw.println(" pref[erred]: print preferred package settings"); 12317 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12318 pw.println(" prov[iders]: dump content providers"); 12319 pw.println(" p[ackages]: dump installed packages"); 12320 pw.println(" s[hared-users]: dump shared user IDs"); 12321 pw.println(" m[essages]: print collected runtime messages"); 12322 pw.println(" v[erifiers]: print package verifier info"); 12323 pw.println(" version: print database version info"); 12324 pw.println(" write: write current settings now"); 12325 pw.println(" <package.name>: info about given package"); 12326 pw.println(" installs: details about install sessions"); 12327 return; 12328 } else if ("--checkin".equals(opt)) { 12329 checkin = true; 12330 } else if ("-f".equals(opt)) { 12331 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12332 } else { 12333 pw.println("Unknown argument: " + opt + "; use -h for help"); 12334 } 12335 } 12336 12337 // Is the caller requesting to dump a particular piece of data? 12338 if (opti < args.length) { 12339 String cmd = args[opti]; 12340 opti++; 12341 // Is this a package name? 12342 if ("android".equals(cmd) || cmd.contains(".")) { 12343 packageName = cmd; 12344 // When dumping a single package, we always dump all of its 12345 // filter information since the amount of data will be reasonable. 12346 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12347 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12348 dumpState.setDump(DumpState.DUMP_LIBS); 12349 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12350 dumpState.setDump(DumpState.DUMP_FEATURES); 12351 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12352 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12353 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12354 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12355 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12356 dumpState.setDump(DumpState.DUMP_PREFERRED); 12357 } else if ("preferred-xml".equals(cmd)) { 12358 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12359 if (opti < args.length && "--full".equals(args[opti])) { 12360 fullPreferred = true; 12361 opti++; 12362 } 12363 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12364 dumpState.setDump(DumpState.DUMP_PACKAGES); 12365 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12366 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12367 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12368 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12369 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12370 dumpState.setDump(DumpState.DUMP_MESSAGES); 12371 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12372 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12373 } else if ("version".equals(cmd)) { 12374 dumpState.setDump(DumpState.DUMP_VERSION); 12375 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12376 dumpState.setDump(DumpState.DUMP_KEYSETS); 12377 } else if ("write".equals(cmd)) { 12378 synchronized (mPackages) { 12379 mSettings.writeLPr(); 12380 pw.println("Settings written."); 12381 return; 12382 } 12383 } else if ("installs".equals(cmd)) { 12384 dumpState.setDump(DumpState.DUMP_INSTALLS); 12385 } 12386 } 12387 12388 if (checkin) { 12389 pw.println("vers,1"); 12390 } 12391 12392 // reader 12393 synchronized (mPackages) { 12394 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12395 if (!checkin) { 12396 if (dumpState.onTitlePrinted()) 12397 pw.println(); 12398 pw.println("Database versions:"); 12399 pw.print(" SDK Version:"); 12400 pw.print(" internal="); 12401 pw.print(mSettings.mInternalSdkPlatform); 12402 pw.print(" external="); 12403 pw.println(mSettings.mExternalSdkPlatform); 12404 pw.print(" DB Version:"); 12405 pw.print(" internal="); 12406 pw.print(mSettings.mInternalDatabaseVersion); 12407 pw.print(" external="); 12408 pw.println(mSettings.mExternalDatabaseVersion); 12409 } 12410 } 12411 12412 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12413 if (!checkin) { 12414 if (dumpState.onTitlePrinted()) 12415 pw.println(); 12416 pw.println("Verifiers:"); 12417 pw.print(" Required: "); 12418 pw.print(mRequiredVerifierPackage); 12419 pw.print(" (uid="); 12420 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12421 pw.println(")"); 12422 } else if (mRequiredVerifierPackage != null) { 12423 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12424 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12425 } 12426 } 12427 12428 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12429 boolean printedHeader = false; 12430 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12431 while (it.hasNext()) { 12432 String name = it.next(); 12433 SharedLibraryEntry ent = mSharedLibraries.get(name); 12434 if (!checkin) { 12435 if (!printedHeader) { 12436 if (dumpState.onTitlePrinted()) 12437 pw.println(); 12438 pw.println("Libraries:"); 12439 printedHeader = true; 12440 } 12441 pw.print(" "); 12442 } else { 12443 pw.print("lib,"); 12444 } 12445 pw.print(name); 12446 if (!checkin) { 12447 pw.print(" -> "); 12448 } 12449 if (ent.path != null) { 12450 if (!checkin) { 12451 pw.print("(jar) "); 12452 pw.print(ent.path); 12453 } else { 12454 pw.print(",jar,"); 12455 pw.print(ent.path); 12456 } 12457 } else { 12458 if (!checkin) { 12459 pw.print("(apk) "); 12460 pw.print(ent.apk); 12461 } else { 12462 pw.print(",apk,"); 12463 pw.print(ent.apk); 12464 } 12465 } 12466 pw.println(); 12467 } 12468 } 12469 12470 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12471 if (dumpState.onTitlePrinted()) 12472 pw.println(); 12473 if (!checkin) { 12474 pw.println("Features:"); 12475 } 12476 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12477 while (it.hasNext()) { 12478 String name = it.next(); 12479 if (!checkin) { 12480 pw.print(" "); 12481 } else { 12482 pw.print("feat,"); 12483 } 12484 pw.println(name); 12485 } 12486 } 12487 12488 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12489 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12490 : "Activity Resolver Table:", " ", packageName, 12491 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12492 dumpState.setTitlePrinted(true); 12493 } 12494 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12495 : "Receiver Resolver Table:", " ", packageName, 12496 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12497 dumpState.setTitlePrinted(true); 12498 } 12499 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12500 : "Service Resolver Table:", " ", packageName, 12501 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12502 dumpState.setTitlePrinted(true); 12503 } 12504 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12505 : "Provider Resolver Table:", " ", packageName, 12506 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12507 dumpState.setTitlePrinted(true); 12508 } 12509 } 12510 12511 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12512 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12513 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12514 int user = mSettings.mPreferredActivities.keyAt(i); 12515 if (pir.dump(pw, 12516 dumpState.getTitlePrinted() 12517 ? "\nPreferred Activities User " + user + ":" 12518 : "Preferred Activities User " + user + ":", " ", 12519 packageName, true)) { 12520 dumpState.setTitlePrinted(true); 12521 } 12522 } 12523 } 12524 12525 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12526 pw.flush(); 12527 FileOutputStream fout = new FileOutputStream(fd); 12528 BufferedOutputStream str = new BufferedOutputStream(fout); 12529 XmlSerializer serializer = new FastXmlSerializer(); 12530 try { 12531 serializer.setOutput(str, "utf-8"); 12532 serializer.startDocument(null, true); 12533 serializer.setFeature( 12534 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12535 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12536 serializer.endDocument(); 12537 serializer.flush(); 12538 } catch (IllegalArgumentException e) { 12539 pw.println("Failed writing: " + e); 12540 } catch (IllegalStateException e) { 12541 pw.println("Failed writing: " + e); 12542 } catch (IOException e) { 12543 pw.println("Failed writing: " + e); 12544 } 12545 } 12546 12547 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12548 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12549 if (packageName == null) { 12550 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12551 if (iperm == 0) { 12552 if (dumpState.onTitlePrinted()) 12553 pw.println(); 12554 pw.println("AppOp Permissions:"); 12555 } 12556 pw.print(" AppOp Permission "); 12557 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12558 pw.println(":"); 12559 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12560 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12561 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12562 } 12563 } 12564 } 12565 } 12566 12567 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12568 boolean printedSomething = false; 12569 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12570 if (packageName != null && !packageName.equals(p.info.packageName)) { 12571 continue; 12572 } 12573 if (!printedSomething) { 12574 if (dumpState.onTitlePrinted()) 12575 pw.println(); 12576 pw.println("Registered ContentProviders:"); 12577 printedSomething = true; 12578 } 12579 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12580 pw.print(" "); pw.println(p.toString()); 12581 } 12582 printedSomething = false; 12583 for (Map.Entry<String, PackageParser.Provider> entry : 12584 mProvidersByAuthority.entrySet()) { 12585 PackageParser.Provider p = entry.getValue(); 12586 if (packageName != null && !packageName.equals(p.info.packageName)) { 12587 continue; 12588 } 12589 if (!printedSomething) { 12590 if (dumpState.onTitlePrinted()) 12591 pw.println(); 12592 pw.println("ContentProvider Authorities:"); 12593 printedSomething = true; 12594 } 12595 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12596 pw.print(" "); pw.println(p.toString()); 12597 if (p.info != null && p.info.applicationInfo != null) { 12598 final String appInfo = p.info.applicationInfo.toString(); 12599 pw.print(" applicationInfo="); pw.println(appInfo); 12600 } 12601 } 12602 } 12603 12604 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12605 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12606 } 12607 12608 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12609 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12610 } 12611 12612 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12613 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12614 } 12615 12616 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) { 12617 if (dumpState.onTitlePrinted()) pw.println(); 12618 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12619 } 12620 12621 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12622 if (dumpState.onTitlePrinted()) pw.println(); 12623 mSettings.dumpReadMessagesLPr(pw, dumpState); 12624 12625 pw.println(); 12626 pw.println("Package warning messages:"); 12627 final File fname = getSettingsProblemFile(); 12628 FileInputStream in = null; 12629 try { 12630 in = new FileInputStream(fname); 12631 final int avail = in.available(); 12632 final byte[] data = new byte[avail]; 12633 in.read(data); 12634 pw.print(new String(data)); 12635 } catch (FileNotFoundException e) { 12636 } catch (IOException e) { 12637 } finally { 12638 if (in != null) { 12639 try { 12640 in.close(); 12641 } catch (IOException e) { 12642 } 12643 } 12644 } 12645 } 12646 } 12647 } 12648 12649 // ------- apps on sdcard specific code ------- 12650 static final boolean DEBUG_SD_INSTALL = false; 12651 12652 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12653 12654 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12655 12656 private boolean mMediaMounted = false; 12657 12658 private String getEncryptKey() { 12659 try { 12660 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12661 SD_ENCRYPTION_KEYSTORE_NAME); 12662 if (sdEncKey == null) { 12663 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12664 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12665 if (sdEncKey == null) { 12666 Slog.e(TAG, "Failed to create encryption keys"); 12667 return null; 12668 } 12669 } 12670 return sdEncKey; 12671 } catch (NoSuchAlgorithmException nsae) { 12672 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12673 return null; 12674 } catch (IOException ioe) { 12675 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12676 return null; 12677 } 12678 12679 } 12680 12681 /* package */static String getTempContainerId() { 12682 int tmpIdx = 1; 12683 String list[] = PackageHelper.getSecureContainerList(); 12684 if (list != null) { 12685 for (final String name : list) { 12686 // Ignore null and non-temporary container entries 12687 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12688 continue; 12689 } 12690 12691 String subStr = name.substring(mTempContainerPrefix.length()); 12692 try { 12693 int cid = Integer.parseInt(subStr); 12694 if (cid >= tmpIdx) { 12695 tmpIdx = cid + 1; 12696 } 12697 } catch (NumberFormatException e) { 12698 } 12699 } 12700 } 12701 return mTempContainerPrefix + tmpIdx; 12702 } 12703 12704 /* 12705 * Update media status on PackageManager. 12706 */ 12707 @Override 12708 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12709 int callingUid = Binder.getCallingUid(); 12710 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12711 throw new SecurityException("Media status can only be updated by the system"); 12712 } 12713 // reader; this apparently protects mMediaMounted, but should probably 12714 // be a different lock in that case. 12715 synchronized (mPackages) { 12716 Log.i(TAG, "Updating external media status from " 12717 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12718 + (mediaStatus ? "mounted" : "unmounted")); 12719 if (DEBUG_SD_INSTALL) 12720 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12721 + ", mMediaMounted=" + mMediaMounted); 12722 if (mediaStatus == mMediaMounted) { 12723 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12724 : 0, -1); 12725 mHandler.sendMessage(msg); 12726 return; 12727 } 12728 mMediaMounted = mediaStatus; 12729 } 12730 // Queue up an async operation since the package installation may take a 12731 // little while. 12732 mHandler.post(new Runnable() { 12733 public void run() { 12734 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12735 } 12736 }); 12737 } 12738 12739 /** 12740 * Called by MountService when the initial ASECs to scan are available. 12741 * Should block until all the ASEC containers are finished being scanned. 12742 */ 12743 public void scanAvailableAsecs() { 12744 updateExternalMediaStatusInner(true, false, false); 12745 if (mShouldRestoreconData) { 12746 SELinuxMMAC.setRestoreconDone(); 12747 mShouldRestoreconData = false; 12748 } 12749 } 12750 12751 /* 12752 * Collect information of applications on external media, map them against 12753 * existing containers and update information based on current mount status. 12754 * Please note that we always have to report status if reportStatus has been 12755 * set to true especially when unloading packages. 12756 */ 12757 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12758 boolean externalStorage) { 12759 // Collection of uids 12760 int uidArr[] = null; 12761 // Collection of stale containers 12762 HashSet<String> removeCids = new HashSet<String>(); 12763 // Collection of packages on external media with valid containers. 12764 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12765 // Get list of secure containers. 12766 final String list[] = PackageHelper.getSecureContainerList(); 12767 if (list == null || list.length == 0) { 12768 Log.i(TAG, "No secure containers on sdcard"); 12769 } else { 12770 // Process list of secure containers and categorize them 12771 // as active or stale based on their package internal state. 12772 int uidList[] = new int[list.length]; 12773 int num = 0; 12774 // reader 12775 synchronized (mPackages) { 12776 for (String cid : list) { 12777 if (DEBUG_SD_INSTALL) 12778 Log.i(TAG, "Processing container " + cid); 12779 String pkgName = getAsecPackageName(cid); 12780 if (pkgName == null) { 12781 if (DEBUG_SD_INSTALL) 12782 Log.i(TAG, "Container : " + cid + " stale"); 12783 removeCids.add(cid); 12784 continue; 12785 } 12786 if (DEBUG_SD_INSTALL) 12787 Log.i(TAG, "Looking for pkg : " + pkgName); 12788 12789 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12790 if (ps == null) { 12791 Log.i(TAG, "Deleting container with no matching settings " + cid); 12792 removeCids.add(cid); 12793 continue; 12794 } 12795 12796 /* 12797 * Skip packages that are not external if we're unmounting 12798 * external storage. 12799 */ 12800 if (externalStorage && !isMounted && !isExternal(ps)) { 12801 continue; 12802 } 12803 12804 final AsecInstallArgs args = new AsecInstallArgs(cid, 12805 getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps)); 12806 // The package status is changed only if the code path 12807 // matches between settings and the container id. 12808 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12809 if (DEBUG_SD_INSTALL) { 12810 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12811 + " at code path: " + ps.codePathString); 12812 } 12813 12814 // We do have a valid package installed on sdcard 12815 processCids.put(args, ps.codePathString); 12816 final int uid = ps.appId; 12817 if (uid != -1) { 12818 uidList[num++] = uid; 12819 } 12820 } else { 12821 Log.i(TAG, "Deleting stale container for " + cid); 12822 removeCids.add(cid); 12823 } 12824 } 12825 } 12826 12827 if (num > 0) { 12828 // Sort uid list 12829 Arrays.sort(uidList, 0, num); 12830 // Throw away duplicates 12831 uidArr = new int[num]; 12832 uidArr[0] = uidList[0]; 12833 int di = 0; 12834 for (int i = 1; i < num; i++) { 12835 if (uidList[i - 1] != uidList[i]) { 12836 uidArr[di++] = uidList[i]; 12837 } 12838 } 12839 } 12840 } 12841 // Process packages with valid entries. 12842 if (isMounted) { 12843 if (DEBUG_SD_INSTALL) 12844 Log.i(TAG, "Loading packages"); 12845 loadMediaPackages(processCids, uidArr, removeCids); 12846 startCleaningPackages(); 12847 } else { 12848 if (DEBUG_SD_INSTALL) 12849 Log.i(TAG, "Unloading packages"); 12850 unloadMediaPackages(processCids, uidArr, reportStatus); 12851 } 12852 } 12853 12854 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12855 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12856 int size = pkgList.size(); 12857 if (size > 0) { 12858 // Send broadcasts here 12859 Bundle extras = new Bundle(); 12860 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12861 .toArray(new String[size])); 12862 if (uidArr != null) { 12863 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12864 } 12865 if (replacing) { 12866 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12867 } 12868 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12869 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12870 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12871 } 12872 } 12873 12874 /* 12875 * Look at potentially valid container ids from processCids If package 12876 * information doesn't match the one on record or package scanning fails, 12877 * the cid is added to list of removeCids. We currently don't delete stale 12878 * containers. 12879 */ 12880 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12881 HashSet<String> removeCids) { 12882 ArrayList<String> pkgList = new ArrayList<String>(); 12883 Set<AsecInstallArgs> keys = processCids.keySet(); 12884 boolean doGc = false; 12885 for (AsecInstallArgs args : keys) { 12886 String codePath = processCids.get(args); 12887 if (DEBUG_SD_INSTALL) 12888 Log.i(TAG, "Loading container : " + args.cid); 12889 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12890 try { 12891 // Make sure there are no container errors first. 12892 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12893 Slog.e(TAG, "Failed to mount cid : " + args.cid 12894 + " when installing from sdcard"); 12895 continue; 12896 } 12897 // Check code path here. 12898 if (codePath == null || !codePath.equals(args.getCodePath())) { 12899 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12900 + " does not match one in settings " + codePath); 12901 continue; 12902 } 12903 // Parse package 12904 int parseFlags = mDefParseFlags; 12905 if (args.isExternal()) { 12906 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12907 } 12908 if (args.isFwdLocked()) { 12909 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12910 } 12911 12912 doGc = true; 12913 synchronized (mInstallLock) { 12914 PackageParser.Package pkg = null; 12915 try { 12916 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12917 } catch (PackageManagerException e) { 12918 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12919 } 12920 // Scan the package 12921 if (pkg != null) { 12922 /* 12923 * TODO why is the lock being held? doPostInstall is 12924 * called in other places without the lock. This needs 12925 * to be straightened out. 12926 */ 12927 // writer 12928 synchronized (mPackages) { 12929 retCode = PackageManager.INSTALL_SUCCEEDED; 12930 pkgList.add(pkg.packageName); 12931 // Post process args 12932 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12933 pkg.applicationInfo.uid); 12934 } 12935 } else { 12936 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12937 } 12938 } 12939 12940 } finally { 12941 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12942 // Don't destroy container here. Wait till gc clears things 12943 // up. 12944 removeCids.add(args.cid); 12945 } 12946 } 12947 } 12948 // writer 12949 synchronized (mPackages) { 12950 // If the platform SDK has changed since the last time we booted, 12951 // we need to re-grant app permission to catch any new ones that 12952 // appear. This is really a hack, and means that apps can in some 12953 // cases get permissions that the user didn't initially explicitly 12954 // allow... it would be nice to have some better way to handle 12955 // this situation. 12956 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12957 if (regrantPermissions) 12958 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12959 + mSdkVersion + "; regranting permissions for external storage"); 12960 mSettings.mExternalSdkPlatform = mSdkVersion; 12961 12962 // Make sure group IDs have been assigned, and any permission 12963 // changes in other apps are accounted for 12964 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12965 | (regrantPermissions 12966 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12967 : 0)); 12968 12969 mSettings.updateExternalDatabaseVersion(); 12970 12971 // can downgrade to reader 12972 // Persist settings 12973 mSettings.writeLPr(); 12974 } 12975 // Send a broadcast to let everyone know we are done processing 12976 if (pkgList.size() > 0) { 12977 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12978 } 12979 // Force gc to avoid any stale parser references that we might have. 12980 if (doGc) { 12981 Runtime.getRuntime().gc(); 12982 } 12983 // List stale containers and destroy stale temporary containers. 12984 if (removeCids != null) { 12985 for (String cid : removeCids) { 12986 if (cid.startsWith(mTempContainerPrefix)) { 12987 Log.i(TAG, "Destroying stale temporary container " + cid); 12988 PackageHelper.destroySdDir(cid); 12989 } else { 12990 Log.w(TAG, "Container " + cid + " is stale"); 12991 } 12992 } 12993 } 12994 } 12995 12996 /* 12997 * Utility method to unload a list of specified containers 12998 */ 12999 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 13000 // Just unmount all valid containers. 13001 for (AsecInstallArgs arg : cidArgs) { 13002 synchronized (mInstallLock) { 13003 arg.doPostDeleteLI(false); 13004 } 13005 } 13006 } 13007 13008 /* 13009 * Unload packages mounted on external media. This involves deleting package 13010 * data from internal structures, sending broadcasts about diabled packages, 13011 * gc'ing to free up references, unmounting all secure containers 13012 * corresponding to packages on external media, and posting a 13013 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 13014 * that we always have to post this message if status has been requested no 13015 * matter what. 13016 */ 13017 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 13018 final boolean reportStatus) { 13019 if (DEBUG_SD_INSTALL) 13020 Log.i(TAG, "unloading media packages"); 13021 ArrayList<String> pkgList = new ArrayList<String>(); 13022 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 13023 final Set<AsecInstallArgs> keys = processCids.keySet(); 13024 for (AsecInstallArgs args : keys) { 13025 String pkgName = args.getPackageName(); 13026 if (DEBUG_SD_INSTALL) 13027 Log.i(TAG, "Trying to unload pkg : " + pkgName); 13028 // Delete package internally 13029 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 13030 synchronized (mInstallLock) { 13031 boolean res = deletePackageLI(pkgName, null, false, null, null, 13032 PackageManager.DELETE_KEEP_DATA, outInfo, false); 13033 if (res) { 13034 pkgList.add(pkgName); 13035 } else { 13036 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 13037 failedList.add(args); 13038 } 13039 } 13040 } 13041 13042 // reader 13043 synchronized (mPackages) { 13044 // We didn't update the settings after removing each package; 13045 // write them now for all packages. 13046 mSettings.writeLPr(); 13047 } 13048 13049 // We have to absolutely send UPDATED_MEDIA_STATUS only 13050 // after confirming that all the receivers processed the ordered 13051 // broadcast when packages get disabled, force a gc to clean things up. 13052 // and unload all the containers. 13053 if (pkgList.size() > 0) { 13054 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 13055 new IIntentReceiver.Stub() { 13056 public void performReceive(Intent intent, int resultCode, String data, 13057 Bundle extras, boolean ordered, boolean sticky, 13058 int sendingUser) throws RemoteException { 13059 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 13060 reportStatus ? 1 : 0, 1, keys); 13061 mHandler.sendMessage(msg); 13062 } 13063 }); 13064 } else { 13065 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 13066 keys); 13067 mHandler.sendMessage(msg); 13068 } 13069 } 13070 13071 /** Binder call */ 13072 @Override 13073 public void movePackage(final String packageName, final IPackageMoveObserver observer, 13074 final int flags) { 13075 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 13076 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 13077 int returnCode = PackageManager.MOVE_SUCCEEDED; 13078 int currFlags = 0; 13079 int newFlags = 0; 13080 // reader 13081 synchronized (mPackages) { 13082 PackageParser.Package pkg = mPackages.get(packageName); 13083 if (pkg == null) { 13084 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13085 } else { 13086 // Disable moving fwd locked apps and system packages 13087 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 13088 Slog.w(TAG, "Cannot move system application"); 13089 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13090 } else if (pkg.mOperationPending) { 13091 Slog.w(TAG, "Attempt to move package which has pending operations"); 13092 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13093 } else { 13094 // Find install location first 13095 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13096 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13097 Slog.w(TAG, "Ambigous flags specified for move location."); 13098 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13099 } else { 13100 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 13101 : PackageManager.INSTALL_INTERNAL; 13102 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 13103 : PackageManager.INSTALL_INTERNAL; 13104 13105 if (newFlags == currFlags) { 13106 Slog.w(TAG, "No move required. Trying to move to same location"); 13107 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13108 } else { 13109 if (isForwardLocked(pkg)) { 13110 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13111 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13112 } 13113 } 13114 } 13115 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13116 pkg.mOperationPending = true; 13117 } 13118 } 13119 } 13120 13121 /* 13122 * TODO this next block probably shouldn't be inside the lock. We 13123 * can't guarantee these won't change after this is fired off 13124 * anyway. 13125 */ 13126 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13127 processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false), 13128 returnCode); 13129 } else { 13130 Message msg = mHandler.obtainMessage(INIT_COPY); 13131 final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 13132 final boolean multiArch = isMultiArch(pkg.applicationInfo); 13133 InstallArgs srcArgs = createInstallArgsForExisting(currFlags, 13134 pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(), 13135 pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch); 13136 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 13137 instructionSets, pkg.applicationInfo.uid, user, multiArch); 13138 msg.obj = mp; 13139 mHandler.sendMessage(msg); 13140 } 13141 } 13142 } 13143 13144 private void processPendingMove(final MoveParams mp, final int currentStatus) { 13145 // Queue up an async operation since the package deletion may take a 13146 // little while. 13147 mHandler.post(new Runnable() { 13148 public void run() { 13149 // TODO fix this; this does nothing. 13150 mHandler.removeCallbacks(this); 13151 int returnCode = currentStatus; 13152 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 13153 int uidArr[] = null; 13154 ArrayList<String> pkgList = null; 13155 synchronized (mPackages) { 13156 PackageParser.Package pkg = mPackages.get(mp.packageName); 13157 if (pkg == null) { 13158 Slog.w(TAG, " Package " + mp.packageName 13159 + " doesn't exist. Aborting move"); 13160 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13161 } else if (!mp.srcArgs.getCodePath().equals( 13162 pkg.applicationInfo.getCodePath())) { 13163 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 13164 + mp.srcArgs.getCodePath() + " to " 13165 + pkg.applicationInfo.getCodePath() 13166 + " Aborting move and returning error"); 13167 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13168 } else { 13169 uidArr = new int[] { 13170 pkg.applicationInfo.uid 13171 }; 13172 pkgList = new ArrayList<String>(); 13173 pkgList.add(mp.packageName); 13174 } 13175 } 13176 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13177 // Send resources unavailable broadcast 13178 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 13179 // Update package code and resource paths 13180 synchronized (mInstallLock) { 13181 synchronized (mPackages) { 13182 PackageParser.Package pkg = mPackages.get(mp.packageName); 13183 // Recheck for package again. 13184 if (pkg == null) { 13185 Slog.w(TAG, " Package " + mp.packageName 13186 + " doesn't exist. Aborting move"); 13187 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13188 } else if (!mp.srcArgs.getCodePath().equals( 13189 pkg.applicationInfo.getCodePath())) { 13190 Slog.w(TAG, "Package " + mp.packageName 13191 + " code path changed from " + mp.srcArgs.getCodePath() 13192 + " to " + pkg.applicationInfo.getCodePath() 13193 + " Aborting move and returning error"); 13194 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13195 } else { 13196 final String oldCodePath = pkg.codePath; 13197 final String newCodePath = mp.targetArgs.getCodePath(); 13198 final String newResPath = mp.targetArgs.getResourcePath(); 13199 // TODO: This assumes the new style of installation. 13200 // should we look at legacyNativeLibraryPath ? 13201 final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath(); 13202 final File newNativeDir = new File(newNativeRoot); 13203 13204 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 13205 // TODO(multiArch): Fix this so that it looks at the existing 13206 // recorded CPU abis from the package. There's no need for a separate 13207 // round of ABI scanning here. 13208 NativeLibraryHelper.Handle handle = null; 13209 try { 13210 handle = NativeLibraryHelper.Handle.create( 13211 new File(newCodePath)); 13212 final int abi = NativeLibraryHelper.findSupportedAbi( 13213 handle, Build.SUPPORTED_ABIS); 13214 if (abi >= 0) { 13215 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 13216 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 13217 } 13218 } catch (IOException ioe) { 13219 Slog.w(TAG, "Unable to extract native libs for package :" 13220 + mp.packageName, ioe); 13221 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13222 } finally { 13223 IoUtils.closeQuietly(handle); 13224 } 13225 } 13226 13227 final int[] users = sUserManager.getUserIds(); 13228 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13229 for (int user : users) { 13230 // TODO(multiArch): Fix this so that it links to the 13231 // correct directory. We're currently pointing to root. but we 13232 // must point to the arch specific subdirectory (if applicable). 13233 // 13234 // TODO(multiArch): Bogus reference to nativeLibraryDir. 13235 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 13236 newNativeRoot, user) < 0) { 13237 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13238 } 13239 } 13240 } 13241 13242 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13243 pkg.codePath = newCodePath; 13244 pkg.baseCodePath = newCodePath; 13245 // Move dex files around 13246 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 13247 // Moving of dex files failed. Set 13248 // error code and abort move. 13249 pkg.codePath = oldCodePath; 13250 pkg.baseCodePath = oldCodePath; 13251 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13252 } 13253 } 13254 13255 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13256 pkg.applicationInfo.setCodePath(newCodePath); 13257 pkg.applicationInfo.setBaseCodePath(newCodePath); 13258 pkg.applicationInfo.setSplitCodePaths(null); 13259 pkg.applicationInfo.setResourcePath(newResPath); 13260 pkg.applicationInfo.setBaseResourcePath(newResPath); 13261 pkg.applicationInfo.setSplitResourcePaths(null); 13262 13263 PackageSetting ps = (PackageSetting) pkg.mExtras; 13264 ps.codePath = new File(pkg.applicationInfo.getCodePath()); 13265 ps.codePathString = ps.codePath.getPath(); 13266 ps.resourcePath = new File(pkg.applicationInfo.getResourcePath()); 13267 ps.resourcePathString = ps.resourcePath.getPath(); 13268 13269 // Note that we don't have to recalculate the primary and secondary 13270 // CPU ABIs because they must already have been calculated during the 13271 // initial install of the app. 13272 ps.legacyNativeLibraryPathString = null; 13273 13274 // Set the application info flag 13275 // correctly. 13276 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 13277 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13278 } else { 13279 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13280 } 13281 ps.setFlags(pkg.applicationInfo.flags); 13282 mAppDirs.remove(oldCodePath); 13283 mAppDirs.put(newCodePath, pkg); 13284 // Persist settings 13285 mSettings.writeLPr(); 13286 } 13287 } 13288 } 13289 } 13290 // Send resources available broadcast 13291 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13292 } 13293 } 13294 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13295 // Clean up failed installation 13296 if (mp.targetArgs != null) { 13297 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 13298 -1); 13299 } 13300 } else { 13301 // Force a gc to clear things up. 13302 Runtime.getRuntime().gc(); 13303 // Delete older code 13304 synchronized (mInstallLock) { 13305 mp.srcArgs.doPostDeleteLI(true); 13306 } 13307 } 13308 13309 // Allow more operations on this file if we didn't fail because 13310 // an operation was already pending for this package. 13311 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 13312 synchronized (mPackages) { 13313 PackageParser.Package pkg = mPackages.get(mp.packageName); 13314 if (pkg != null) { 13315 pkg.mOperationPending = false; 13316 } 13317 } 13318 } 13319 13320 IPackageMoveObserver observer = mp.observer; 13321 if (observer != null) { 13322 try { 13323 observer.packageMoved(mp.packageName, returnCode); 13324 } catch (RemoteException e) { 13325 Log.i(TAG, "Observer no longer exists."); 13326 } 13327 } 13328 } 13329 }); 13330 } 13331 13332 @Override 13333 public boolean setInstallLocation(int loc) { 13334 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13335 null); 13336 if (getInstallLocation() == loc) { 13337 return true; 13338 } 13339 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13340 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13341 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13342 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13343 return true; 13344 } 13345 return false; 13346 } 13347 13348 @Override 13349 public int getInstallLocation() { 13350 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13351 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13352 PackageHelper.APP_INSTALL_AUTO); 13353 } 13354 13355 /** Called by UserManagerService */ 13356 void cleanUpUserLILPw(int userHandle) { 13357 mDirtyUsers.remove(userHandle); 13358 mSettings.removeUserLPw(userHandle); 13359 mPendingBroadcasts.remove(userHandle); 13360 if (mInstaller != null) { 13361 // Technically, we shouldn't be doing this with the package lock 13362 // held. However, this is very rare, and there is already so much 13363 // other disk I/O going on, that we'll let it slide for now. 13364 mInstaller.removeUserDataDirs(userHandle); 13365 } 13366 mUserNeedsBadging.delete(userHandle); 13367 } 13368 13369 /** Called by UserManagerService */ 13370 void createNewUserLILPw(int userHandle, File path) { 13371 if (mInstaller != null) { 13372 mInstaller.createUserConfig(userHandle); 13373 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13374 } 13375 } 13376 13377 @Override 13378 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13379 mContext.enforceCallingOrSelfPermission( 13380 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13381 "Only package verification agents can read the verifier device identity"); 13382 13383 synchronized (mPackages) { 13384 return mSettings.getVerifierDeviceIdentityLPw(); 13385 } 13386 } 13387 13388 @Override 13389 public void setPermissionEnforced(String permission, boolean enforced) { 13390 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13391 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13392 synchronized (mPackages) { 13393 if (mSettings.mReadExternalStorageEnforced == null 13394 || mSettings.mReadExternalStorageEnforced != enforced) { 13395 mSettings.mReadExternalStorageEnforced = enforced; 13396 mSettings.writeLPr(); 13397 } 13398 } 13399 // kill any non-foreground processes so we restart them and 13400 // grant/revoke the GID. 13401 final IActivityManager am = ActivityManagerNative.getDefault(); 13402 if (am != null) { 13403 final long token = Binder.clearCallingIdentity(); 13404 try { 13405 am.killProcessesBelowForeground("setPermissionEnforcement"); 13406 } catch (RemoteException e) { 13407 } finally { 13408 Binder.restoreCallingIdentity(token); 13409 } 13410 } 13411 } else { 13412 throw new IllegalArgumentException("No selective enforcement for " + permission); 13413 } 13414 } 13415 13416 @Override 13417 @Deprecated 13418 public boolean isPermissionEnforced(String permission) { 13419 return true; 13420 } 13421 13422 @Override 13423 public boolean isStorageLow() { 13424 final long token = Binder.clearCallingIdentity(); 13425 try { 13426 final DeviceStorageMonitorInternal 13427 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13428 if (dsm != null) { 13429 return dsm.isMemoryLow(); 13430 } else { 13431 return false; 13432 } 13433 } finally { 13434 Binder.restoreCallingIdentity(token); 13435 } 13436 } 13437 13438 @Override 13439 public IPackageInstaller getPackageInstaller() { 13440 return mInstallerService; 13441 } 13442 13443 private boolean userNeedsBadging(int userId) { 13444 int index = mUserNeedsBadging.indexOfKey(userId); 13445 if (index < 0) { 13446 final UserInfo userInfo; 13447 final long token = Binder.clearCallingIdentity(); 13448 try { 13449 userInfo = sUserManager.getUserInfo(userId); 13450 } finally { 13451 Binder.restoreCallingIdentity(token); 13452 } 13453 final boolean b; 13454 if (userInfo != null && userInfo.isManagedProfile()) { 13455 b = true; 13456 } else { 13457 b = false; 13458 } 13459 mUserNeedsBadging.put(userId, b); 13460 return b; 13461 } 13462 return mUserNeedsBadging.valueAt(index); 13463 } 13464 13465 @Override 13466 public KeySetHandle getKeySetByAlias(String packageName, String alias) { 13467 if (packageName == null || alias == null) { 13468 return null; 13469 } 13470 synchronized(mPackages) { 13471 final PackageParser.Package pkg = mPackages.get(packageName); 13472 if (pkg == null) { 13473 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13474 throw new IllegalArgumentException("Unknown package: " + packageName); 13475 } 13476 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13477 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13478 throw new SecurityException("May not access KeySets defined by" 13479 + " aliases in other applications."); 13480 } 13481 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13482 return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias); 13483 } 13484 } 13485 13486 @Override 13487 public KeySetHandle getSigningKeySet(String packageName) { 13488 if (packageName == null) { 13489 return null; 13490 } 13491 synchronized(mPackages) { 13492 final PackageParser.Package pkg = mPackages.get(packageName); 13493 if (pkg == null) { 13494 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13495 throw new IllegalArgumentException("Unknown package: " + packageName); 13496 } 13497 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13498 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13499 throw new SecurityException("May not access signing KeySet of other apps."); 13500 } 13501 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13502 return ksms.getSigningKeySetByPackageNameLPr(packageName); 13503 } 13504 } 13505 13506 @Override 13507 public boolean isPackageSignedByKeySet(String packageName, IBinder ks) { 13508 if (packageName == null || ks == null) { 13509 return false; 13510 } 13511 synchronized(mPackages) { 13512 final PackageParser.Package pkg = mPackages.get(packageName); 13513 if (pkg == null) { 13514 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13515 throw new IllegalArgumentException("Unknown package: " + packageName); 13516 } 13517 if (ks instanceof KeySetHandle) { 13518 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13519 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks); 13520 } 13521 return false; 13522 } 13523 } 13524 13525 @Override 13526 public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) { 13527 if (packageName == null || ks == null) { 13528 return false; 13529 } 13530 synchronized(mPackages) { 13531 final PackageParser.Package pkg = mPackages.get(packageName); 13532 if (pkg == null) { 13533 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13534 throw new IllegalArgumentException("Unknown package: " + packageName); 13535 } 13536 if (ks instanceof KeySetHandle) { 13537 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13538 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks); 13539 } 13540 return false; 13541 } 13542 } 13543} 13544