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