PackageManagerService.java revision 7c97bbc39f0b748e413de3cd0b0f0c995a2af0ce
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 45import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 46import static android.content.pm.PackageParser.isApkFile; 47import static android.os.Process.PACKAGE_INFO_GID; 48import static android.os.Process.SYSTEM_UID; 49import static android.system.OsConstants.O_CREAT; 50import static android.system.OsConstants.O_RDWR; 51import static android.system.OsConstants.S_IRGRP; 52import static android.system.OsConstants.S_IROTH; 53import static android.system.OsConstants.S_IRWXU; 54import static android.system.OsConstants.S_IXGRP; 55import static android.system.OsConstants.S_IXOTH; 56import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 57import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 58import static com.android.internal.util.ArrayUtils.appendInt; 59import static com.android.internal.util.ArrayUtils.removeInt; 60 61import android.util.ArrayMap; 62 63import com.android.internal.R; 64import com.android.internal.app.IMediaContainerService; 65import com.android.internal.app.ResolverActivity; 66import com.android.internal.content.NativeLibraryHelper; 67import com.android.internal.content.PackageHelper; 68import com.android.internal.os.IParcelFileDescriptorFactory; 69import com.android.internal.util.ArrayUtils; 70import com.android.internal.util.FastPrintWriter; 71import com.android.internal.util.FastXmlSerializer; 72import com.android.internal.util.IndentingPrintWriter; 73import com.android.internal.util.Preconditions; 74import com.android.server.EventLogTags; 75import com.android.server.IntentResolver; 76import com.android.server.LocalServices; 77import com.android.server.ServiceThread; 78import com.android.server.SystemConfig; 79import com.android.server.Watchdog; 80import com.android.server.pm.Settings.DatabaseVersion; 81import com.android.server.storage.DeviceStorageMonitorInternal; 82 83import org.xmlpull.v1.XmlSerializer; 84 85import android.app.ActivityManager; 86import android.app.ActivityManagerNative; 87import android.app.IActivityManager; 88import android.app.admin.IDevicePolicyManager; 89import android.app.backup.IBackupManager; 90import android.content.BroadcastReceiver; 91import android.content.ComponentName; 92import android.content.Context; 93import android.content.IIntentReceiver; 94import android.content.Intent; 95import android.content.IntentFilter; 96import android.content.IntentSender; 97import android.content.IntentSender.SendIntentException; 98import android.content.ServiceConnection; 99import android.content.pm.ActivityInfo; 100import android.content.pm.ApplicationInfo; 101import android.content.pm.FeatureInfo; 102import android.content.pm.IPackageDataObserver; 103import android.content.pm.IPackageDeleteObserver; 104import android.content.pm.IPackageDeleteObserver2; 105import android.content.pm.IPackageInstallObserver2; 106import android.content.pm.IPackageInstaller; 107import android.content.pm.IPackageManager; 108import android.content.pm.IPackageMoveObserver; 109import android.content.pm.IPackageStatsObserver; 110import android.content.pm.InstallSessionParams; 111import android.content.pm.InstrumentationInfo; 112import android.content.pm.ManifestDigest; 113import android.content.pm.PackageCleanItem; 114import android.content.pm.PackageInfo; 115import android.content.pm.PackageInfoLite; 116import android.content.pm.PackageManager; 117import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 118import android.content.pm.PackageParser.ActivityIntentInfo; 119import android.content.pm.PackageParser.PackageLite; 120import android.content.pm.PackageParser.PackageParserException; 121import android.content.pm.PackageParser; 122import android.content.pm.PackageStats; 123import android.content.pm.PackageUserState; 124import android.content.pm.ParceledListSlice; 125import android.content.pm.PermissionGroupInfo; 126import android.content.pm.PermissionInfo; 127import android.content.pm.ProviderInfo; 128import android.content.pm.ResolveInfo; 129import android.content.pm.ServiceInfo; 130import android.content.pm.Signature; 131import android.content.pm.UserInfo; 132import android.content.pm.VerificationParams; 133import android.content.pm.VerifierDeviceIdentity; 134import android.content.pm.VerifierInfo; 135import android.content.res.Resources; 136import android.hardware.display.DisplayManager; 137import android.net.Uri; 138import android.os.Binder; 139import android.os.Build; 140import android.os.Bundle; 141import android.os.Environment; 142import android.os.Environment.UserEnvironment; 143import android.os.FileUtils; 144import android.os.Handler; 145import android.os.IBinder; 146import android.os.Looper; 147import android.os.Message; 148import android.os.Parcel; 149import android.os.ParcelFileDescriptor; 150import android.os.Process; 151import android.os.RemoteException; 152import android.os.SELinux; 153import android.os.ServiceManager; 154import android.os.SystemClock; 155import android.os.SystemProperties; 156import android.os.UserHandle; 157import android.os.UserManager; 158import android.security.KeyStore; 159import android.security.SystemKeyStore; 160import android.system.ErrnoException; 161import android.system.Os; 162import android.system.StructStat; 163import android.text.TextUtils; 164import android.util.ArraySet; 165import android.util.AtomicFile; 166import android.util.DisplayMetrics; 167import android.util.EventLog; 168import android.util.ExceptionUtils; 169import android.util.Log; 170import android.util.LogPrinter; 171import android.util.PrintStreamPrinter; 172import android.util.Slog; 173import android.util.SparseArray; 174import android.util.SparseBooleanArray; 175import android.view.Display; 176 177import java.io.BufferedInputStream; 178import java.io.BufferedOutputStream; 179import java.io.File; 180import java.io.FileDescriptor; 181import java.io.FileInputStream; 182import java.io.FileNotFoundException; 183import java.io.FileOutputStream; 184import java.io.FilenameFilter; 185import java.io.IOException; 186import java.io.InputStream; 187import java.io.PrintWriter; 188import java.nio.charset.StandardCharsets; 189import java.security.NoSuchAlgorithmException; 190import java.security.PublicKey; 191import java.security.cert.CertificateEncodingException; 192import java.security.cert.CertificateException; 193import java.text.SimpleDateFormat; 194import java.util.ArrayList; 195import java.util.Arrays; 196import java.util.Collection; 197import java.util.Collections; 198import java.util.Comparator; 199import java.util.Date; 200import java.util.HashMap; 201import java.util.HashSet; 202import java.util.Iterator; 203import java.util.List; 204import java.util.Map; 205import java.util.Set; 206import java.util.concurrent.atomic.AtomicBoolean; 207import java.util.concurrent.atomic.AtomicLong; 208 209import dalvik.system.DexFile; 210import dalvik.system.StaleDexCacheError; 211import dalvik.system.VMRuntime; 212 213import libcore.io.IoUtils; 214 215/** 216 * Keep track of all those .apks everywhere. 217 * 218 * This is very central to the platform's security; please run the unit 219 * tests whenever making modifications here: 220 * 221mmm frameworks/base/tests/AndroidTests 222adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 223adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 224 * 225 * {@hide} 226 */ 227public class PackageManagerService extends IPackageManager.Stub { 228 static final String TAG = "PackageManager"; 229 static final boolean DEBUG_SETTINGS = false; 230 static final boolean DEBUG_PREFERRED = false; 231 static final boolean DEBUG_UPGRADE = false; 232 private static final boolean DEBUG_INSTALL = false; 233 private static final boolean DEBUG_REMOVE = false; 234 private static final boolean DEBUG_BROADCASTS = false; 235 private static final boolean DEBUG_SHOW_INFO = false; 236 private static final boolean DEBUG_PACKAGE_INFO = false; 237 private static final boolean DEBUG_INTENT_MATCHING = false; 238 private static final boolean DEBUG_PACKAGE_SCANNING = false; 239 private static final boolean DEBUG_VERIFY = false; 240 private static final boolean DEBUG_DEXOPT = false; 241 private static final boolean DEBUG_ABI_SELECTION = false; 242 243 private static final int RADIO_UID = Process.PHONE_UID; 244 private static final int LOG_UID = Process.LOG_UID; 245 private static final int NFC_UID = Process.NFC_UID; 246 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 247 private static final int SHELL_UID = Process.SHELL_UID; 248 249 // Cap the size of permission trees that 3rd party apps can define 250 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 251 252 // Suffix used during package installation when copying/moving 253 // package apks to install directory. 254 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 255 256 static final int SCAN_MONITOR = 1<<0; 257 static final int SCAN_NO_DEX = 1<<1; 258 static final int SCAN_FORCE_DEX = 1<<2; 259 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 260 static final int SCAN_NEW_INSTALL = 1<<4; 261 static final int SCAN_NO_PATHS = 1<<5; 262 static final int SCAN_UPDATE_TIME = 1<<6; 263 static final int SCAN_DEFER_DEX = 1<<7; 264 static final int SCAN_BOOTING = 1<<8; 265 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 266 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 267 268 static final int REMOVE_CHATTY = 1<<16; 269 270 /** 271 * Timeout (in milliseconds) after which the watchdog should declare that 272 * our handler thread is wedged. The usual default for such things is one 273 * minute but we sometimes do very lengthy I/O operations on this thread, 274 * such as installing multi-gigabyte applications, so ours needs to be longer. 275 */ 276 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 277 278 /** 279 * Whether verification is enabled by default. 280 */ 281 private static final boolean DEFAULT_VERIFY_ENABLE = true; 282 283 /** 284 * The default maximum time to wait for the verification agent to return in 285 * milliseconds. 286 */ 287 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 288 289 /** 290 * The default response for package verification timeout. 291 * 292 * This can be either PackageManager.VERIFICATION_ALLOW or 293 * PackageManager.VERIFICATION_REJECT. 294 */ 295 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 296 297 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 298 299 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 300 DEFAULT_CONTAINER_PACKAGE, 301 "com.android.defcontainer.DefaultContainerService"); 302 303 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 304 305 private static final String LIB_DIR_NAME = "lib"; 306 private static final String LIB64_DIR_NAME = "lib64"; 307 308 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 309 310 static final String mTempContainerPrefix = "smdl2tmp"; 311 312 private static String sPreferredInstructionSet; 313 314 final ServiceThread mHandlerThread; 315 316 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 317 private static final String IDMAP_SUFFIX = "@idmap"; 318 319 final PackageHandler mHandler; 320 321 final int mSdkVersion = Build.VERSION.SDK_INT; 322 323 final Context mContext; 324 final boolean mFactoryTest; 325 final boolean mOnlyCore; 326 final DisplayMetrics mMetrics; 327 final int mDefParseFlags; 328 final String[] mSeparateProcesses; 329 330 // This is where all application persistent data goes. 331 final File mAppDataDir; 332 333 // This is where all application persistent data goes for secondary users. 334 final File mUserAppDataDir; 335 336 /** The location for ASEC container files on internal storage. */ 337 final String mAsecInternalPath; 338 339 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 340 // LOCK HELD. Can be called with mInstallLock held. 341 final Installer mInstaller; 342 343 /** Directory where installed third-party apps stored */ 344 final File mAppInstallDir; 345 346 /** 347 * Directory to which applications installed internally have their 348 * 32 bit native libraries copied. 349 */ 350 private File mAppLib32InstallDir; 351 352 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 353 // apps. 354 final File mDrmAppPrivateInstallDir; 355 356 // ---------------------------------------------------------------- 357 358 // Lock for state used when installing and doing other long running 359 // operations. Methods that must be called with this lock held have 360 // the suffix "LI". 361 final Object mInstallLock = new Object(); 362 363 // These are the directories in the 3rd party applications installed dir 364 // that we have currently loaded packages from. Keys are the application's 365 // installed zip file (absolute codePath), and values are Package. 366 final HashMap<String, PackageParser.Package> mAppDirs = 367 new HashMap<String, PackageParser.Package>(); 368 369 // ---------------------------------------------------------------- 370 371 // Keys are String (package name), values are Package. This also serves 372 // as the lock for the global state. Methods that must be called with 373 // this lock held have the prefix "LP". 374 final HashMap<String, PackageParser.Package> mPackages = 375 new HashMap<String, PackageParser.Package>(); 376 377 // Tracks available target package names -> overlay package paths. 378 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 379 new HashMap<String, HashMap<String, PackageParser.Package>>(); 380 381 final Settings mSettings; 382 boolean mRestoredSettings; 383 384 // System configuration read by SystemConfig. 385 final int[] mGlobalGids; 386 final SparseArray<HashSet<String>> mSystemPermissions; 387 final HashMap<String, FeatureInfo> mAvailableFeatures; 388 389 // If mac_permissions.xml was found for seinfo labeling. 390 boolean mFoundPolicyFile; 391 392 // If a recursive restorecon of /data/data/<pkg> is needed. 393 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 394 395 public static final class SharedLibraryEntry { 396 public final String path; 397 public final String apk; 398 399 SharedLibraryEntry(String _path, String _apk) { 400 path = _path; 401 apk = _apk; 402 } 403 } 404 405 // Currently known shared libraries. 406 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 407 new HashMap<String, SharedLibraryEntry>(); 408 409 // All available activities, for your resolving pleasure. 410 final ActivityIntentResolver mActivities = 411 new ActivityIntentResolver(); 412 413 // All available receivers, for your resolving pleasure. 414 final ActivityIntentResolver mReceivers = 415 new ActivityIntentResolver(); 416 417 // All available services, for your resolving pleasure. 418 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 419 420 // All available providers, for your resolving pleasure. 421 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 422 423 // Mapping from provider base names (first directory in content URI codePath) 424 // to the provider information. 425 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 426 new HashMap<String, PackageParser.Provider>(); 427 428 // Mapping from instrumentation class names to info about them. 429 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 430 new HashMap<ComponentName, PackageParser.Instrumentation>(); 431 432 // Mapping from permission names to info about them. 433 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 434 new HashMap<String, PackageParser.PermissionGroup>(); 435 436 // Packages whose data we have transfered into another package, thus 437 // should no longer exist. 438 final HashSet<String> mTransferedPackages = new HashSet<String>(); 439 440 // Broadcast actions that are only available to the system. 441 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 442 443 /** List of packages waiting for verification. */ 444 final SparseArray<PackageVerificationState> mPendingVerification 445 = new SparseArray<PackageVerificationState>(); 446 447 /** Set of packages associated with each app op permission. */ 448 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 449 450 final PackageInstallerService mInstallerService; 451 452 HashSet<PackageParser.Package> mDeferredDexOpt = null; 453 454 // Cache of users who need badging. 455 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 456 457 /** Token for keys in mPendingVerification. */ 458 private int mPendingVerificationToken = 0; 459 460 boolean mSystemReady; 461 boolean mSafeMode; 462 boolean mHasSystemUidErrors; 463 464 ApplicationInfo mAndroidApplication; 465 final ActivityInfo mResolveActivity = new ActivityInfo(); 466 final ResolveInfo mResolveInfo = new ResolveInfo(); 467 ComponentName mResolveComponentName; 468 PackageParser.Package mPlatformPackage; 469 ComponentName mCustomResolverComponentName; 470 471 boolean mResolverReplaced = false; 472 473 // Set of pending broadcasts for aggregating enable/disable of components. 474 static class PendingPackageBroadcasts { 475 // for each user id, a map of <package name -> components within that package> 476 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 477 478 public PendingPackageBroadcasts() { 479 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 480 } 481 482 public ArrayList<String> get(int userId, String packageName) { 483 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 484 return packages.get(packageName); 485 } 486 487 public void put(int userId, String packageName, ArrayList<String> components) { 488 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 489 packages.put(packageName, components); 490 } 491 492 public void remove(int userId, String packageName) { 493 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 494 if (packages != null) { 495 packages.remove(packageName); 496 } 497 } 498 499 public void remove(int userId) { 500 mUidMap.remove(userId); 501 } 502 503 public int userIdCount() { 504 return mUidMap.size(); 505 } 506 507 public int userIdAt(int n) { 508 return mUidMap.keyAt(n); 509 } 510 511 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 512 return mUidMap.get(userId); 513 } 514 515 public int size() { 516 // total number of pending broadcast entries across all userIds 517 int num = 0; 518 for (int i = 0; i< mUidMap.size(); i++) { 519 num += mUidMap.valueAt(i).size(); 520 } 521 return num; 522 } 523 524 public void clear() { 525 mUidMap.clear(); 526 } 527 528 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 529 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 530 if (map == null) { 531 map = new HashMap<String, ArrayList<String>>(); 532 mUidMap.put(userId, map); 533 } 534 return map; 535 } 536 } 537 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 538 539 // Service Connection to remote media container service to copy 540 // package uri's from external media onto secure containers 541 // or internal storage. 542 private IMediaContainerService mContainerService = null; 543 544 static final int SEND_PENDING_BROADCAST = 1; 545 static final int MCS_BOUND = 3; 546 static final int END_COPY = 4; 547 static final int INIT_COPY = 5; 548 static final int MCS_UNBIND = 6; 549 static final int START_CLEANING_PACKAGE = 7; 550 static final int FIND_INSTALL_LOC = 8; 551 static final int POST_INSTALL = 9; 552 static final int MCS_RECONNECT = 10; 553 static final int MCS_GIVE_UP = 11; 554 static final int UPDATED_MEDIA_STATUS = 12; 555 static final int WRITE_SETTINGS = 13; 556 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 557 static final int PACKAGE_VERIFIED = 15; 558 static final int CHECK_PENDING_VERIFICATION = 16; 559 560 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 561 562 // Delay time in millisecs 563 static final int BROADCAST_DELAY = 10 * 1000; 564 565 static UserManagerService sUserManager; 566 567 // Stores a list of users whose package restrictions file needs to be updated 568 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 569 570 final private DefaultContainerConnection mDefContainerConn = 571 new DefaultContainerConnection(); 572 class DefaultContainerConnection implements ServiceConnection { 573 public void onServiceConnected(ComponentName name, IBinder service) { 574 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 575 IMediaContainerService imcs = 576 IMediaContainerService.Stub.asInterface(service); 577 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 578 } 579 580 public void onServiceDisconnected(ComponentName name) { 581 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 582 } 583 }; 584 585 // Recordkeeping of restore-after-install operations that are currently in flight 586 // between the Package Manager and the Backup Manager 587 class PostInstallData { 588 public InstallArgs args; 589 public PackageInstalledInfo res; 590 591 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 592 args = _a; 593 res = _r; 594 } 595 }; 596 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 597 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 598 599 private final String mRequiredVerifierPackage; 600 601 private final PackageUsage mPackageUsage = new PackageUsage(); 602 603 private class PackageUsage { 604 private static final int WRITE_INTERVAL 605 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 606 607 private final Object mFileLock = new Object(); 608 private final AtomicLong mLastWritten = new AtomicLong(0); 609 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 610 611 private boolean mIsHistoricalPackageUsageAvailable = true; 612 613 boolean isHistoricalPackageUsageAvailable() { 614 return mIsHistoricalPackageUsageAvailable; 615 } 616 617 void write(boolean force) { 618 if (force) { 619 writeInternal(); 620 return; 621 } 622 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 623 && !DEBUG_DEXOPT) { 624 return; 625 } 626 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 627 new Thread("PackageUsage_DiskWriter") { 628 @Override 629 public void run() { 630 try { 631 writeInternal(); 632 } finally { 633 mBackgroundWriteRunning.set(false); 634 } 635 } 636 }.start(); 637 } 638 } 639 640 private void writeInternal() { 641 synchronized (mPackages) { 642 synchronized (mFileLock) { 643 AtomicFile file = getFile(); 644 FileOutputStream f = null; 645 try { 646 f = file.startWrite(); 647 BufferedOutputStream out = new BufferedOutputStream(f); 648 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 649 StringBuilder sb = new StringBuilder(); 650 for (PackageParser.Package pkg : mPackages.values()) { 651 if (pkg.mLastPackageUsageTimeInMills == 0) { 652 continue; 653 } 654 sb.setLength(0); 655 sb.append(pkg.packageName); 656 sb.append(' '); 657 sb.append((long)pkg.mLastPackageUsageTimeInMills); 658 sb.append('\n'); 659 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 660 } 661 out.flush(); 662 file.finishWrite(f); 663 } catch (IOException e) { 664 if (f != null) { 665 file.failWrite(f); 666 } 667 Log.e(TAG, "Failed to write package usage times", e); 668 } 669 } 670 } 671 mLastWritten.set(SystemClock.elapsedRealtime()); 672 } 673 674 void readLP() { 675 synchronized (mFileLock) { 676 AtomicFile file = getFile(); 677 BufferedInputStream in = null; 678 try { 679 in = new BufferedInputStream(file.openRead()); 680 StringBuffer sb = new StringBuffer(); 681 while (true) { 682 String packageName = readToken(in, sb, ' '); 683 if (packageName == null) { 684 break; 685 } 686 String timeInMillisString = readToken(in, sb, '\n'); 687 if (timeInMillisString == null) { 688 throw new IOException("Failed to find last usage time for package " 689 + packageName); 690 } 691 PackageParser.Package pkg = mPackages.get(packageName); 692 if (pkg == null) { 693 continue; 694 } 695 long timeInMillis; 696 try { 697 timeInMillis = Long.parseLong(timeInMillisString.toString()); 698 } catch (NumberFormatException e) { 699 throw new IOException("Failed to parse " + timeInMillisString 700 + " as a long.", e); 701 } 702 pkg.mLastPackageUsageTimeInMills = timeInMillis; 703 } 704 } catch (FileNotFoundException expected) { 705 mIsHistoricalPackageUsageAvailable = false; 706 } catch (IOException e) { 707 Log.w(TAG, "Failed to read package usage times", e); 708 } finally { 709 IoUtils.closeQuietly(in); 710 } 711 } 712 mLastWritten.set(SystemClock.elapsedRealtime()); 713 } 714 715 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 716 throws IOException { 717 sb.setLength(0); 718 while (true) { 719 int ch = in.read(); 720 if (ch == -1) { 721 if (sb.length() == 0) { 722 return null; 723 } 724 throw new IOException("Unexpected EOF"); 725 } 726 if (ch == endOfToken) { 727 return sb.toString(); 728 } 729 sb.append((char)ch); 730 } 731 } 732 733 private AtomicFile getFile() { 734 File dataDir = Environment.getDataDirectory(); 735 File systemDir = new File(dataDir, "system"); 736 File fname = new File(systemDir, "package-usage.list"); 737 return new AtomicFile(fname); 738 } 739 } 740 741 class PackageHandler extends Handler { 742 private boolean mBound = false; 743 final ArrayList<HandlerParams> mPendingInstalls = 744 new ArrayList<HandlerParams>(); 745 746 private boolean connectToService() { 747 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 748 " DefaultContainerService"); 749 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 750 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 751 if (mContext.bindServiceAsUser(service, mDefContainerConn, 752 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 753 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 754 mBound = true; 755 return true; 756 } 757 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 758 return false; 759 } 760 761 private void disconnectService() { 762 mContainerService = null; 763 mBound = false; 764 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 765 mContext.unbindService(mDefContainerConn); 766 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 767 } 768 769 PackageHandler(Looper looper) { 770 super(looper); 771 } 772 773 public void handleMessage(Message msg) { 774 try { 775 doHandleMessage(msg); 776 } finally { 777 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 778 } 779 } 780 781 void doHandleMessage(Message msg) { 782 switch (msg.what) { 783 case INIT_COPY: { 784 HandlerParams params = (HandlerParams) msg.obj; 785 int idx = mPendingInstalls.size(); 786 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 787 // If a bind was already initiated we dont really 788 // need to do anything. The pending install 789 // will be processed later on. 790 if (!mBound) { 791 // If this is the only one pending we might 792 // have to bind to the service again. 793 if (!connectToService()) { 794 Slog.e(TAG, "Failed to bind to media container service"); 795 params.serviceError(); 796 return; 797 } else { 798 // Once we bind to the service, the first 799 // pending request will be processed. 800 mPendingInstalls.add(idx, params); 801 } 802 } else { 803 mPendingInstalls.add(idx, params); 804 // Already bound to the service. Just make 805 // sure we trigger off processing the first request. 806 if (idx == 0) { 807 mHandler.sendEmptyMessage(MCS_BOUND); 808 } 809 } 810 break; 811 } 812 case MCS_BOUND: { 813 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 814 if (msg.obj != null) { 815 mContainerService = (IMediaContainerService) msg.obj; 816 } 817 if (mContainerService == null) { 818 // Something seriously wrong. Bail out 819 Slog.e(TAG, "Cannot bind to media container service"); 820 for (HandlerParams params : mPendingInstalls) { 821 // Indicate service bind error 822 params.serviceError(); 823 } 824 mPendingInstalls.clear(); 825 } else if (mPendingInstalls.size() > 0) { 826 HandlerParams params = mPendingInstalls.get(0); 827 if (params != null) { 828 if (params.startCopy()) { 829 // We are done... look for more work or to 830 // go idle. 831 if (DEBUG_SD_INSTALL) Log.i(TAG, 832 "Checking for more work or unbind..."); 833 // Delete pending install 834 if (mPendingInstalls.size() > 0) { 835 mPendingInstalls.remove(0); 836 } 837 if (mPendingInstalls.size() == 0) { 838 if (mBound) { 839 if (DEBUG_SD_INSTALL) Log.i(TAG, 840 "Posting delayed MCS_UNBIND"); 841 removeMessages(MCS_UNBIND); 842 Message ubmsg = obtainMessage(MCS_UNBIND); 843 // Unbind after a little delay, to avoid 844 // continual thrashing. 845 sendMessageDelayed(ubmsg, 10000); 846 } 847 } else { 848 // There are more pending requests in queue. 849 // Just post MCS_BOUND message to trigger processing 850 // of next pending install. 851 if (DEBUG_SD_INSTALL) Log.i(TAG, 852 "Posting MCS_BOUND for next work"); 853 mHandler.sendEmptyMessage(MCS_BOUND); 854 } 855 } 856 } 857 } else { 858 // Should never happen ideally. 859 Slog.w(TAG, "Empty queue"); 860 } 861 break; 862 } 863 case MCS_RECONNECT: { 864 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 865 if (mPendingInstalls.size() > 0) { 866 if (mBound) { 867 disconnectService(); 868 } 869 if (!connectToService()) { 870 Slog.e(TAG, "Failed to bind to media container service"); 871 for (HandlerParams params : mPendingInstalls) { 872 // Indicate service bind error 873 params.serviceError(); 874 } 875 mPendingInstalls.clear(); 876 } 877 } 878 break; 879 } 880 case MCS_UNBIND: { 881 // If there is no actual work left, then time to unbind. 882 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 883 884 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 885 if (mBound) { 886 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 887 888 disconnectService(); 889 } 890 } else if (mPendingInstalls.size() > 0) { 891 // There are more pending requests in queue. 892 // Just post MCS_BOUND message to trigger processing 893 // of next pending install. 894 mHandler.sendEmptyMessage(MCS_BOUND); 895 } 896 897 break; 898 } 899 case MCS_GIVE_UP: { 900 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 901 mPendingInstalls.remove(0); 902 break; 903 } 904 case SEND_PENDING_BROADCAST: { 905 String packages[]; 906 ArrayList<String> components[]; 907 int size = 0; 908 int uids[]; 909 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 910 synchronized (mPackages) { 911 if (mPendingBroadcasts == null) { 912 return; 913 } 914 size = mPendingBroadcasts.size(); 915 if (size <= 0) { 916 // Nothing to be done. Just return 917 return; 918 } 919 packages = new String[size]; 920 components = new ArrayList[size]; 921 uids = new int[size]; 922 int i = 0; // filling out the above arrays 923 924 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 925 int packageUserId = mPendingBroadcasts.userIdAt(n); 926 Iterator<Map.Entry<String, ArrayList<String>>> it 927 = mPendingBroadcasts.packagesForUserId(packageUserId) 928 .entrySet().iterator(); 929 while (it.hasNext() && i < size) { 930 Map.Entry<String, ArrayList<String>> ent = it.next(); 931 packages[i] = ent.getKey(); 932 components[i] = ent.getValue(); 933 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 934 uids[i] = (ps != null) 935 ? UserHandle.getUid(packageUserId, ps.appId) 936 : -1; 937 i++; 938 } 939 } 940 size = i; 941 mPendingBroadcasts.clear(); 942 } 943 // Send broadcasts 944 for (int i = 0; i < size; i++) { 945 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 946 } 947 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 948 break; 949 } 950 case START_CLEANING_PACKAGE: { 951 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 952 final String packageName = (String)msg.obj; 953 final int userId = msg.arg1; 954 final boolean andCode = msg.arg2 != 0; 955 synchronized (mPackages) { 956 if (userId == UserHandle.USER_ALL) { 957 int[] users = sUserManager.getUserIds(); 958 for (int user : users) { 959 mSettings.addPackageToCleanLPw( 960 new PackageCleanItem(user, packageName, andCode)); 961 } 962 } else { 963 mSettings.addPackageToCleanLPw( 964 new PackageCleanItem(userId, packageName, andCode)); 965 } 966 } 967 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 968 startCleaningPackages(); 969 } break; 970 case POST_INSTALL: { 971 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 972 PostInstallData data = mRunningInstalls.get(msg.arg1); 973 mRunningInstalls.delete(msg.arg1); 974 boolean deleteOld = false; 975 976 if (data != null) { 977 InstallArgs args = data.args; 978 PackageInstalledInfo res = data.res; 979 980 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 981 res.removedInfo.sendBroadcast(false, true, false); 982 Bundle extras = new Bundle(1); 983 extras.putInt(Intent.EXTRA_UID, res.uid); 984 // Determine the set of users who are adding this 985 // package for the first time vs. those who are seeing 986 // an update. 987 int[] firstUsers; 988 int[] updateUsers = new int[0]; 989 if (res.origUsers == null || res.origUsers.length == 0) { 990 firstUsers = res.newUsers; 991 } else { 992 firstUsers = new int[0]; 993 for (int i=0; i<res.newUsers.length; i++) { 994 int user = res.newUsers[i]; 995 boolean isNew = true; 996 for (int j=0; j<res.origUsers.length; j++) { 997 if (res.origUsers[j] == user) { 998 isNew = false; 999 break; 1000 } 1001 } 1002 if (isNew) { 1003 int[] newFirst = new int[firstUsers.length+1]; 1004 System.arraycopy(firstUsers, 0, newFirst, 0, 1005 firstUsers.length); 1006 newFirst[firstUsers.length] = user; 1007 firstUsers = newFirst; 1008 } else { 1009 int[] newUpdate = new int[updateUsers.length+1]; 1010 System.arraycopy(updateUsers, 0, newUpdate, 0, 1011 updateUsers.length); 1012 newUpdate[updateUsers.length] = user; 1013 updateUsers = newUpdate; 1014 } 1015 } 1016 } 1017 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1018 res.pkg.applicationInfo.packageName, 1019 extras, null, null, firstUsers); 1020 final boolean update = res.removedInfo.removedPackage != null; 1021 if (update) { 1022 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1023 } 1024 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1025 res.pkg.applicationInfo.packageName, 1026 extras, null, null, updateUsers); 1027 if (update) { 1028 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1029 res.pkg.applicationInfo.packageName, 1030 extras, null, null, updateUsers); 1031 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1032 null, null, 1033 res.pkg.applicationInfo.packageName, null, updateUsers); 1034 1035 // treat asec-hosted packages like removable media on upgrade 1036 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1037 if (DEBUG_INSTALL) { 1038 Slog.i(TAG, "upgrading pkg " + res.pkg 1039 + " is ASEC-hosted -> AVAILABLE"); 1040 } 1041 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1042 ArrayList<String> pkgList = new ArrayList<String>(1); 1043 pkgList.add(res.pkg.applicationInfo.packageName); 1044 sendResourcesChangedBroadcast(true, true, 1045 pkgList,uidArray, null); 1046 } 1047 } 1048 if (res.removedInfo.args != null) { 1049 // Remove the replaced package's older resources safely now 1050 deleteOld = true; 1051 } 1052 1053 // Log current value of "unknown sources" setting 1054 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1055 getUnknownSourcesSettings()); 1056 } 1057 // Force a gc to clear up things 1058 Runtime.getRuntime().gc(); 1059 // We delete after a gc for applications on sdcard. 1060 if (deleteOld) { 1061 synchronized (mInstallLock) { 1062 res.removedInfo.args.doPostDeleteLI(true); 1063 } 1064 } 1065 if (args.observer != null) { 1066 try { 1067 Bundle extras = extrasForInstallResult(res); 1068 args.observer.onPackageInstalled(res.name, res.returnCode, 1069 res.returnMsg, extras); 1070 } catch (RemoteException e) { 1071 Slog.i(TAG, "Observer no longer exists."); 1072 } 1073 } 1074 } else { 1075 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1076 } 1077 } break; 1078 case UPDATED_MEDIA_STATUS: { 1079 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1080 boolean reportStatus = msg.arg1 == 1; 1081 boolean doGc = msg.arg2 == 1; 1082 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1083 if (doGc) { 1084 // Force a gc to clear up stale containers. 1085 Runtime.getRuntime().gc(); 1086 } 1087 if (msg.obj != null) { 1088 @SuppressWarnings("unchecked") 1089 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1090 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1091 // Unload containers 1092 unloadAllContainers(args); 1093 } 1094 if (reportStatus) { 1095 try { 1096 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1097 PackageHelper.getMountService().finishMediaUpdate(); 1098 } catch (RemoteException e) { 1099 Log.e(TAG, "MountService not running?"); 1100 } 1101 } 1102 } break; 1103 case WRITE_SETTINGS: { 1104 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1105 synchronized (mPackages) { 1106 removeMessages(WRITE_SETTINGS); 1107 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1108 mSettings.writeLPr(); 1109 mDirtyUsers.clear(); 1110 } 1111 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1112 } break; 1113 case WRITE_PACKAGE_RESTRICTIONS: { 1114 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1115 synchronized (mPackages) { 1116 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1117 for (int userId : mDirtyUsers) { 1118 mSettings.writePackageRestrictionsLPr(userId); 1119 } 1120 mDirtyUsers.clear(); 1121 } 1122 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1123 } break; 1124 case CHECK_PENDING_VERIFICATION: { 1125 final int verificationId = msg.arg1; 1126 final PackageVerificationState state = mPendingVerification.get(verificationId); 1127 1128 if ((state != null) && !state.timeoutExtended()) { 1129 final InstallArgs args = state.getInstallArgs(); 1130 final Uri originUri = Uri.fromFile(args.originFile); 1131 1132 Slog.i(TAG, "Verification timed out for " + originUri); 1133 mPendingVerification.remove(verificationId); 1134 1135 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1136 1137 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1138 Slog.i(TAG, "Continuing with installation of " + originUri); 1139 state.setVerifierResponse(Binder.getCallingUid(), 1140 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1141 broadcastPackageVerified(verificationId, originUri, 1142 PackageManager.VERIFICATION_ALLOW, 1143 state.getInstallArgs().getUser()); 1144 try { 1145 ret = args.copyApk(mContainerService, true); 1146 } catch (RemoteException e) { 1147 Slog.e(TAG, "Could not contact the ContainerService"); 1148 } 1149 } else { 1150 broadcastPackageVerified(verificationId, originUri, 1151 PackageManager.VERIFICATION_REJECT, 1152 state.getInstallArgs().getUser()); 1153 } 1154 1155 processPendingInstall(args, ret); 1156 mHandler.sendEmptyMessage(MCS_UNBIND); 1157 } 1158 break; 1159 } 1160 case PACKAGE_VERIFIED: { 1161 final int verificationId = msg.arg1; 1162 1163 final PackageVerificationState state = mPendingVerification.get(verificationId); 1164 if (state == null) { 1165 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1166 break; 1167 } 1168 1169 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1170 1171 state.setVerifierResponse(response.callerUid, response.code); 1172 1173 if (state.isVerificationComplete()) { 1174 mPendingVerification.remove(verificationId); 1175 1176 final InstallArgs args = state.getInstallArgs(); 1177 final Uri originUri = Uri.fromFile(args.originFile); 1178 1179 int ret; 1180 if (state.isInstallAllowed()) { 1181 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1182 broadcastPackageVerified(verificationId, originUri, 1183 response.code, state.getInstallArgs().getUser()); 1184 try { 1185 ret = args.copyApk(mContainerService, true); 1186 } catch (RemoteException e) { 1187 Slog.e(TAG, "Could not contact the ContainerService"); 1188 } 1189 } else { 1190 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1191 } 1192 1193 processPendingInstall(args, ret); 1194 1195 mHandler.sendEmptyMessage(MCS_UNBIND); 1196 } 1197 1198 break; 1199 } 1200 } 1201 } 1202 } 1203 1204 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1205 Bundle extras = null; 1206 switch (res.returnCode) { 1207 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1208 extras = new Bundle(); 1209 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1210 res.origPermission); 1211 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1212 res.origPackage); 1213 break; 1214 } 1215 } 1216 return extras; 1217 } 1218 1219 void scheduleWriteSettingsLocked() { 1220 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1221 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1222 } 1223 } 1224 1225 void scheduleWritePackageRestrictionsLocked(int userId) { 1226 if (!sUserManager.exists(userId)) return; 1227 mDirtyUsers.add(userId); 1228 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1229 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1230 } 1231 } 1232 1233 public static final PackageManagerService main(Context context, Installer installer, 1234 boolean factoryTest, boolean onlyCore) { 1235 PackageManagerService m = new PackageManagerService(context, installer, 1236 factoryTest, onlyCore); 1237 ServiceManager.addService("package", m); 1238 return m; 1239 } 1240 1241 static String[] splitString(String str, char sep) { 1242 int count = 1; 1243 int i = 0; 1244 while ((i=str.indexOf(sep, i)) >= 0) { 1245 count++; 1246 i++; 1247 } 1248 1249 String[] res = new String[count]; 1250 i=0; 1251 count = 0; 1252 int lastI=0; 1253 while ((i=str.indexOf(sep, i)) >= 0) { 1254 res[count] = str.substring(lastI, i); 1255 count++; 1256 i++; 1257 lastI = i; 1258 } 1259 res[count] = str.substring(lastI, str.length()); 1260 return res; 1261 } 1262 1263 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1264 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1265 Context.DISPLAY_SERVICE); 1266 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1267 } 1268 1269 public PackageManagerService(Context context, Installer installer, 1270 boolean factoryTest, boolean onlyCore) { 1271 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1272 SystemClock.uptimeMillis()); 1273 1274 if (mSdkVersion <= 0) { 1275 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1276 } 1277 1278 mContext = context; 1279 mFactoryTest = factoryTest; 1280 mOnlyCore = onlyCore; 1281 mMetrics = new DisplayMetrics(); 1282 mSettings = new Settings(context); 1283 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1284 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1285 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1286 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1287 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1288 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1289 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1290 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1291 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1292 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1293 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1294 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1295 1296 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1297 if (separateProcesses != null && separateProcesses.length() > 0) { 1298 if ("*".equals(separateProcesses)) { 1299 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1300 mSeparateProcesses = null; 1301 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1302 } else { 1303 mDefParseFlags = 0; 1304 mSeparateProcesses = separateProcesses.split(","); 1305 Slog.w(TAG, "Running with debug.separate_processes: " 1306 + separateProcesses); 1307 } 1308 } else { 1309 mDefParseFlags = 0; 1310 mSeparateProcesses = null; 1311 } 1312 1313 mInstaller = installer; 1314 1315 getDefaultDisplayMetrics(context, mMetrics); 1316 1317 SystemConfig systemConfig = SystemConfig.getInstance(); 1318 mGlobalGids = systemConfig.getGlobalGids(); 1319 mSystemPermissions = systemConfig.getSystemPermissions(); 1320 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1321 1322 synchronized (mInstallLock) { 1323 // writer 1324 synchronized (mPackages) { 1325 mHandlerThread = new ServiceThread(TAG, 1326 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1327 mHandlerThread.start(); 1328 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1329 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1330 1331 File dataDir = Environment.getDataDirectory(); 1332 mAppDataDir = new File(dataDir, "data"); 1333 mAppInstallDir = new File(dataDir, "app"); 1334 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1335 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1336 mUserAppDataDir = new File(dataDir, "user"); 1337 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1338 1339 sUserManager = new UserManagerService(context, this, 1340 mInstallLock, mPackages); 1341 1342 // Propagate permission configuration in to package manager. 1343 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1344 = systemConfig.getPermissions(); 1345 for (int i=0; i<permConfig.size(); i++) { 1346 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1347 BasePermission bp = mSettings.mPermissions.get(perm.name); 1348 if (bp == null) { 1349 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1350 mSettings.mPermissions.put(perm.name, bp); 1351 } 1352 if (perm.gids != null) { 1353 bp.gids = appendInts(bp.gids, perm.gids); 1354 } 1355 } 1356 1357 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1358 for (int i=0; i<libConfig.size(); i++) { 1359 mSharedLibraries.put(libConfig.keyAt(i), 1360 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1361 } 1362 1363 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1364 1365 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1366 mSdkVersion, mOnlyCore); 1367 1368 String customResolverActivity = Resources.getSystem().getString( 1369 R.string.config_customResolverActivity); 1370 if (TextUtils.isEmpty(customResolverActivity)) { 1371 customResolverActivity = null; 1372 } else { 1373 mCustomResolverComponentName = ComponentName.unflattenFromString( 1374 customResolverActivity); 1375 } 1376 1377 long startTime = SystemClock.uptimeMillis(); 1378 1379 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1380 startTime); 1381 1382 // Set flag to monitor and not change apk file paths when 1383 // scanning install directories. 1384 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1385 1386 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1387 1388 /** 1389 * Add everything in the in the boot class path to the 1390 * list of process files because dexopt will have been run 1391 * if necessary during zygote startup. 1392 */ 1393 String bootClassPath = System.getProperty("java.boot.class.path"); 1394 if (bootClassPath != null) { 1395 String[] paths = splitString(bootClassPath, ':'); 1396 for (int i=0; i<paths.length; i++) { 1397 alreadyDexOpted.add(paths[i]); 1398 } 1399 } else { 1400 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1401 } 1402 1403 boolean didDexOptLibraryOrTool = false; 1404 1405 final List<String> allInstructionSets = getAllInstructionSets(); 1406 final String[] dexCodeInstructionSets = 1407 getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()])); 1408 1409 /** 1410 * Ensure all external libraries have had dexopt run on them. 1411 */ 1412 if (mSharedLibraries.size() > 0) { 1413 // NOTE: For now, we're compiling these system "shared libraries" 1414 // (and framework jars) into all available architectures. It's possible 1415 // to compile them only when we come across an app that uses them (there's 1416 // already logic for that in scanPackageLI) but that adds some complexity. 1417 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1418 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1419 final String lib = libEntry.path; 1420 if (lib == null) { 1421 continue; 1422 } 1423 1424 try { 1425 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1426 dexCodeInstructionSet, 1427 false); 1428 if (dexoptRequired != DexFile.UP_TO_DATE) { 1429 alreadyDexOpted.add(lib); 1430 1431 // The list of "shared libraries" we have at this point is 1432 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1433 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1434 } else { 1435 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1436 } 1437 didDexOptLibraryOrTool = true; 1438 } 1439 } catch (FileNotFoundException e) { 1440 Slog.w(TAG, "Library not found: " + lib); 1441 } catch (IOException e) { 1442 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1443 + e.getMessage()); 1444 } 1445 } 1446 } 1447 } 1448 1449 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1450 1451 // Gross hack for now: we know this file doesn't contain any 1452 // code, so don't dexopt it to avoid the resulting log spew. 1453 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1454 1455 // Gross hack for now: we know this file is only part of 1456 // the boot class path for art, so don't dexopt it to 1457 // avoid the resulting log spew. 1458 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1459 1460 /** 1461 * And there are a number of commands implemented in Java, which 1462 * we currently need to do the dexopt on so that they can be 1463 * run from a non-root shell. 1464 */ 1465 String[] frameworkFiles = frameworkDir.list(); 1466 if (frameworkFiles != null) { 1467 // TODO: We could compile these only for the most preferred ABI. We should 1468 // first double check that the dex files for these commands are not referenced 1469 // by other system apps. 1470 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1471 for (int i=0; i<frameworkFiles.length; i++) { 1472 File libPath = new File(frameworkDir, frameworkFiles[i]); 1473 String path = libPath.getPath(); 1474 // Skip the file if we already did it. 1475 if (alreadyDexOpted.contains(path)) { 1476 continue; 1477 } 1478 // Skip the file if it is not a type we want to dexopt. 1479 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1480 continue; 1481 } 1482 try { 1483 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1484 dexCodeInstructionSet, 1485 false); 1486 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1487 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1488 didDexOptLibraryOrTool = true; 1489 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1490 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1491 didDexOptLibraryOrTool = true; 1492 } 1493 } catch (FileNotFoundException e) { 1494 Slog.w(TAG, "Jar not found: " + path); 1495 } catch (IOException e) { 1496 Slog.w(TAG, "Exception reading jar: " + path, e); 1497 } 1498 } 1499 } 1500 } 1501 1502 if (didDexOptLibraryOrTool) { 1503 // If we dexopted a library or tool, then something on the system has 1504 // changed. Consider this significant, and wipe away all other 1505 // existing dexopt files to ensure we don't leave any dangling around. 1506 // 1507 // TODO: This should be revisited because it isn't as good an indicator 1508 // as it used to be. It used to include the boot classpath but at some point 1509 // DexFile.isDexOptNeeded started returning false for the boot 1510 // class path files in all cases. It is very possible in a 1511 // small maintenance release update that the library and tool 1512 // jars may be unchanged but APK could be removed resulting in 1513 // unused dalvik-cache files. 1514 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1515 mInstaller.pruneDexCache(dexCodeInstructionSet); 1516 } 1517 1518 // Additionally, delete all dex files from the root directory 1519 // since there shouldn't be any there anyway, unless we're upgrading 1520 // from an older OS version or a build that contained the "old" style 1521 // flat scheme. 1522 mInstaller.pruneDexCache("."); 1523 } 1524 1525 // Collect vendor overlay packages. 1526 // (Do this before scanning any apps.) 1527 // For security and version matching reason, only consider 1528 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1529 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1530 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1531 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1532 1533 // Find base frameworks (resource packages without code). 1534 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1535 | PackageParser.PARSE_IS_SYSTEM_DIR 1536 | PackageParser.PARSE_IS_PRIVILEGED, 1537 scanMode | SCAN_NO_DEX, 0); 1538 1539 // Collected privileged system packages. 1540 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1541 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1542 | PackageParser.PARSE_IS_SYSTEM_DIR 1543 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1544 1545 // Collect ordinary system packages. 1546 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1547 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1548 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1549 1550 // Collect all vendor packages. 1551 File vendorAppDir = new File("/vendor/app"); 1552 try { 1553 vendorAppDir = vendorAppDir.getCanonicalFile(); 1554 } catch (IOException e) { 1555 // failed to look up canonical path, continue with original one 1556 } 1557 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1558 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1559 1560 // Collect all OEM packages. 1561 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1562 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1563 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1564 1565 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1566 mInstaller.moveFiles(); 1567 1568 // Prune any system packages that no longer exist. 1569 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1570 if (!mOnlyCore) { 1571 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1572 while (psit.hasNext()) { 1573 PackageSetting ps = psit.next(); 1574 1575 /* 1576 * If this is not a system app, it can't be a 1577 * disable system app. 1578 */ 1579 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1580 continue; 1581 } 1582 1583 /* 1584 * If the package is scanned, it's not erased. 1585 */ 1586 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1587 if (scannedPkg != null) { 1588 /* 1589 * If the system app is both scanned and in the 1590 * disabled packages list, then it must have been 1591 * added via OTA. Remove it from the currently 1592 * scanned package so the previously user-installed 1593 * application can be scanned. 1594 */ 1595 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1596 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1597 + "; removing system app"); 1598 removePackageLI(ps, true); 1599 } 1600 1601 continue; 1602 } 1603 1604 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1605 psit.remove(); 1606 String msg = "System package " + ps.name 1607 + " no longer exists; wiping its data"; 1608 reportSettingsProblem(Log.WARN, msg); 1609 removeDataDirsLI(ps.name); 1610 } else { 1611 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1612 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1613 possiblyDeletedUpdatedSystemApps.add(ps.name); 1614 } 1615 } 1616 } 1617 } 1618 1619 //look for any incomplete package installations 1620 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1621 //clean up list 1622 for(int i = 0; i < deletePkgsList.size(); i++) { 1623 //clean up here 1624 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1625 } 1626 //delete tmp files 1627 deleteTempPackageFiles(); 1628 1629 // Remove any shared userIDs that have no associated packages 1630 mSettings.pruneSharedUsersLPw(); 1631 1632 if (!mOnlyCore) { 1633 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1634 SystemClock.uptimeMillis()); 1635 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1636 1637 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1638 scanMode, 0); 1639 1640 /** 1641 * Remove disable package settings for any updated system 1642 * apps that were removed via an OTA. If they're not a 1643 * previously-updated app, remove them completely. 1644 * Otherwise, just revoke their system-level permissions. 1645 */ 1646 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1647 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1648 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1649 1650 String msg; 1651 if (deletedPkg == null) { 1652 msg = "Updated system package " + deletedAppName 1653 + " no longer exists; wiping its data"; 1654 removeDataDirsLI(deletedAppName); 1655 } else { 1656 msg = "Updated system app + " + deletedAppName 1657 + " no longer present; removing system privileges for " 1658 + deletedAppName; 1659 1660 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1661 1662 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1663 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1664 } 1665 reportSettingsProblem(Log.WARN, msg); 1666 } 1667 } 1668 1669 // Now that we know all of the shared libraries, update all clients to have 1670 // the correct library paths. 1671 updateAllSharedLibrariesLPw(); 1672 1673 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1674 // NOTE: We ignore potential failures here during a system scan (like 1675 // the rest of the commands above) because there's precious little we 1676 // can do about it. A settings error is reported, though. 1677 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1678 false /* force dexopt */, false /* defer dexopt */); 1679 } 1680 1681 // Now that we know all the packages we are keeping, 1682 // read and update their last usage times. 1683 mPackageUsage.readLP(); 1684 1685 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1686 SystemClock.uptimeMillis()); 1687 Slog.i(TAG, "Time to scan packages: " 1688 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1689 + " seconds"); 1690 1691 // If the platform SDK has changed since the last time we booted, 1692 // we need to re-grant app permission to catch any new ones that 1693 // appear. This is really a hack, and means that apps can in some 1694 // cases get permissions that the user didn't initially explicitly 1695 // allow... it would be nice to have some better way to handle 1696 // this situation. 1697 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1698 != mSdkVersion; 1699 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1700 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1701 + "; regranting permissions for internal storage"); 1702 mSettings.mInternalSdkPlatform = mSdkVersion; 1703 1704 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1705 | (regrantPermissions 1706 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1707 : 0)); 1708 1709 // If this is the first boot, and it is a normal boot, then 1710 // we need to initialize the default preferred apps. 1711 if (!mRestoredSettings && !onlyCore) { 1712 mSettings.readDefaultPreferredAppsLPw(this, 0); 1713 } 1714 1715 // If this is first boot after an OTA, and a normal boot, then 1716 // we need to clear code cache directories. 1717 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1718 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1719 for (String pkgName : mSettings.mPackages.keySet()) { 1720 deleteCodeCacheDirsLI(pkgName); 1721 } 1722 mSettings.mFingerprint = Build.FINGERPRINT; 1723 } 1724 1725 // All the changes are done during package scanning. 1726 mSettings.updateInternalDatabaseVersion(); 1727 1728 // can downgrade to reader 1729 mSettings.writeLPr(); 1730 1731 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1732 SystemClock.uptimeMillis()); 1733 1734 1735 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1736 } // synchronized (mPackages) 1737 } // synchronized (mInstallLock) 1738 1739 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1740 1741 // Now after opening every single application zip, make sure they 1742 // are all flushed. Not really needed, but keeps things nice and 1743 // tidy. 1744 Runtime.getRuntime().gc(); 1745 } 1746 1747 @Override 1748 public boolean isFirstBoot() { 1749 return !mRestoredSettings; 1750 } 1751 1752 @Override 1753 public boolean isOnlyCoreApps() { 1754 return mOnlyCore; 1755 } 1756 1757 private String getRequiredVerifierLPr() { 1758 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1759 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1760 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1761 1762 String requiredVerifier = null; 1763 1764 final int N = receivers.size(); 1765 for (int i = 0; i < N; i++) { 1766 final ResolveInfo info = receivers.get(i); 1767 1768 if (info.activityInfo == null) { 1769 continue; 1770 } 1771 1772 final String packageName = info.activityInfo.packageName; 1773 1774 final PackageSetting ps = mSettings.mPackages.get(packageName); 1775 if (ps == null) { 1776 continue; 1777 } 1778 1779 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1780 if (!gp.grantedPermissions 1781 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1782 continue; 1783 } 1784 1785 if (requiredVerifier != null) { 1786 throw new RuntimeException("There can be only one required verifier"); 1787 } 1788 1789 requiredVerifier = packageName; 1790 } 1791 1792 return requiredVerifier; 1793 } 1794 1795 @Override 1796 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1797 throws RemoteException { 1798 try { 1799 return super.onTransact(code, data, reply, flags); 1800 } catch (RuntimeException e) { 1801 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1802 Slog.wtf(TAG, "Package Manager Crash", e); 1803 } 1804 throw e; 1805 } 1806 } 1807 1808 void cleanupInstallFailedPackage(PackageSetting ps) { 1809 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1810 removeDataDirsLI(ps.name); 1811 1812 // TODO: try cleaning up codePath directory contents first, since it 1813 // might be a cluster 1814 1815 if (ps.codePath != null) { 1816 if (!ps.codePath.delete()) { 1817 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1818 } 1819 } 1820 if (ps.resourcePath != null) { 1821 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1822 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1823 } 1824 } 1825 mSettings.removePackageLPw(ps.name); 1826 } 1827 1828 static int[] appendInts(int[] cur, int[] add) { 1829 if (add == null) return cur; 1830 if (cur == null) return add; 1831 final int N = add.length; 1832 for (int i=0; i<N; i++) { 1833 cur = appendInt(cur, add[i]); 1834 } 1835 return cur; 1836 } 1837 1838 static int[] removeInts(int[] cur, int[] rem) { 1839 if (rem == null) return cur; 1840 if (cur == null) return cur; 1841 final int N = rem.length; 1842 for (int i=0; i<N; i++) { 1843 cur = removeInt(cur, rem[i]); 1844 } 1845 return cur; 1846 } 1847 1848 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1849 if (!sUserManager.exists(userId)) return null; 1850 final PackageSetting ps = (PackageSetting) p.mExtras; 1851 if (ps == null) { 1852 return null; 1853 } 1854 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1855 final PackageUserState state = ps.readUserState(userId); 1856 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1857 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1858 state, userId); 1859 } 1860 1861 @Override 1862 public boolean isPackageAvailable(String packageName, int userId) { 1863 if (!sUserManager.exists(userId)) return false; 1864 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1865 synchronized (mPackages) { 1866 PackageParser.Package p = mPackages.get(packageName); 1867 if (p != null) { 1868 final PackageSetting ps = (PackageSetting) p.mExtras; 1869 if (ps != null) { 1870 final PackageUserState state = ps.readUserState(userId); 1871 if (state != null) { 1872 return PackageParser.isAvailable(state); 1873 } 1874 } 1875 } 1876 } 1877 return false; 1878 } 1879 1880 @Override 1881 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1882 if (!sUserManager.exists(userId)) return null; 1883 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1884 // reader 1885 synchronized (mPackages) { 1886 PackageParser.Package p = mPackages.get(packageName); 1887 if (DEBUG_PACKAGE_INFO) 1888 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1889 if (p != null) { 1890 return generatePackageInfo(p, flags, userId); 1891 } 1892 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1893 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1894 } 1895 } 1896 return null; 1897 } 1898 1899 @Override 1900 public String[] currentToCanonicalPackageNames(String[] names) { 1901 String[] out = new String[names.length]; 1902 // reader 1903 synchronized (mPackages) { 1904 for (int i=names.length-1; i>=0; i--) { 1905 PackageSetting ps = mSettings.mPackages.get(names[i]); 1906 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1907 } 1908 } 1909 return out; 1910 } 1911 1912 @Override 1913 public String[] canonicalToCurrentPackageNames(String[] names) { 1914 String[] out = new String[names.length]; 1915 // reader 1916 synchronized (mPackages) { 1917 for (int i=names.length-1; i>=0; i--) { 1918 String cur = mSettings.mRenamedPackages.get(names[i]); 1919 out[i] = cur != null ? cur : names[i]; 1920 } 1921 } 1922 return out; 1923 } 1924 1925 @Override 1926 public int getPackageUid(String packageName, int userId) { 1927 if (!sUserManager.exists(userId)) return -1; 1928 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1929 // reader 1930 synchronized (mPackages) { 1931 PackageParser.Package p = mPackages.get(packageName); 1932 if(p != null) { 1933 return UserHandle.getUid(userId, p.applicationInfo.uid); 1934 } 1935 PackageSetting ps = mSettings.mPackages.get(packageName); 1936 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1937 return -1; 1938 } 1939 p = ps.pkg; 1940 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1941 } 1942 } 1943 1944 @Override 1945 public int[] getPackageGids(String packageName) { 1946 // reader 1947 synchronized (mPackages) { 1948 PackageParser.Package p = mPackages.get(packageName); 1949 if (DEBUG_PACKAGE_INFO) 1950 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1951 if (p != null) { 1952 final PackageSetting ps = (PackageSetting)p.mExtras; 1953 return ps.getGids(); 1954 } 1955 } 1956 // stupid thing to indicate an error. 1957 return new int[0]; 1958 } 1959 1960 static final PermissionInfo generatePermissionInfo( 1961 BasePermission bp, int flags) { 1962 if (bp.perm != null) { 1963 return PackageParser.generatePermissionInfo(bp.perm, flags); 1964 } 1965 PermissionInfo pi = new PermissionInfo(); 1966 pi.name = bp.name; 1967 pi.packageName = bp.sourcePackage; 1968 pi.nonLocalizedLabel = bp.name; 1969 pi.protectionLevel = bp.protectionLevel; 1970 return pi; 1971 } 1972 1973 @Override 1974 public PermissionInfo getPermissionInfo(String name, int flags) { 1975 // reader 1976 synchronized (mPackages) { 1977 final BasePermission p = mSettings.mPermissions.get(name); 1978 if (p != null) { 1979 return generatePermissionInfo(p, flags); 1980 } 1981 return null; 1982 } 1983 } 1984 1985 @Override 1986 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 1987 // reader 1988 synchronized (mPackages) { 1989 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 1990 for (BasePermission p : mSettings.mPermissions.values()) { 1991 if (group == null) { 1992 if (p.perm == null || p.perm.info.group == null) { 1993 out.add(generatePermissionInfo(p, flags)); 1994 } 1995 } else { 1996 if (p.perm != null && group.equals(p.perm.info.group)) { 1997 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 1998 } 1999 } 2000 } 2001 2002 if (out.size() > 0) { 2003 return out; 2004 } 2005 return mPermissionGroups.containsKey(group) ? out : null; 2006 } 2007 } 2008 2009 @Override 2010 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2011 // reader 2012 synchronized (mPackages) { 2013 return PackageParser.generatePermissionGroupInfo( 2014 mPermissionGroups.get(name), flags); 2015 } 2016 } 2017 2018 @Override 2019 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2020 // reader 2021 synchronized (mPackages) { 2022 final int N = mPermissionGroups.size(); 2023 ArrayList<PermissionGroupInfo> out 2024 = new ArrayList<PermissionGroupInfo>(N); 2025 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2026 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2027 } 2028 return out; 2029 } 2030 } 2031 2032 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2033 int userId) { 2034 if (!sUserManager.exists(userId)) return null; 2035 PackageSetting ps = mSettings.mPackages.get(packageName); 2036 if (ps != null) { 2037 if (ps.pkg == null) { 2038 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2039 flags, userId); 2040 if (pInfo != null) { 2041 return pInfo.applicationInfo; 2042 } 2043 return null; 2044 } 2045 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2046 ps.readUserState(userId), userId); 2047 } 2048 return null; 2049 } 2050 2051 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2052 int userId) { 2053 if (!sUserManager.exists(userId)) return null; 2054 PackageSetting ps = mSettings.mPackages.get(packageName); 2055 if (ps != null) { 2056 PackageParser.Package pkg = ps.pkg; 2057 if (pkg == null) { 2058 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2059 return null; 2060 } 2061 // Only data remains, so we aren't worried about code paths 2062 pkg = new PackageParser.Package(packageName); 2063 pkg.applicationInfo.packageName = packageName; 2064 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2065 pkg.applicationInfo.dataDir = 2066 getDataPathForPackage(packageName, 0).getPath(); 2067 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2068 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2069 } 2070 return generatePackageInfo(pkg, flags, userId); 2071 } 2072 return null; 2073 } 2074 2075 @Override 2076 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2077 if (!sUserManager.exists(userId)) return null; 2078 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2079 // writer 2080 synchronized (mPackages) { 2081 PackageParser.Package p = mPackages.get(packageName); 2082 if (DEBUG_PACKAGE_INFO) Log.v( 2083 TAG, "getApplicationInfo " + packageName 2084 + ": " + p); 2085 if (p != null) { 2086 PackageSetting ps = mSettings.mPackages.get(packageName); 2087 if (ps == null) return null; 2088 // Note: isEnabledLP() does not apply here - always return info 2089 return PackageParser.generateApplicationInfo( 2090 p, flags, ps.readUserState(userId), userId); 2091 } 2092 if ("android".equals(packageName)||"system".equals(packageName)) { 2093 return mAndroidApplication; 2094 } 2095 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2096 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2097 } 2098 } 2099 return null; 2100 } 2101 2102 2103 @Override 2104 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2105 mContext.enforceCallingOrSelfPermission( 2106 android.Manifest.permission.CLEAR_APP_CACHE, null); 2107 // Queue up an async operation since clearing cache may take a little while. 2108 mHandler.post(new Runnable() { 2109 public void run() { 2110 mHandler.removeCallbacks(this); 2111 int retCode = -1; 2112 synchronized (mInstallLock) { 2113 retCode = mInstaller.freeCache(freeStorageSize); 2114 if (retCode < 0) { 2115 Slog.w(TAG, "Couldn't clear application caches"); 2116 } 2117 } 2118 if (observer != null) { 2119 try { 2120 observer.onRemoveCompleted(null, (retCode >= 0)); 2121 } catch (RemoteException e) { 2122 Slog.w(TAG, "RemoveException when invoking call back"); 2123 } 2124 } 2125 } 2126 }); 2127 } 2128 2129 @Override 2130 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2131 mContext.enforceCallingOrSelfPermission( 2132 android.Manifest.permission.CLEAR_APP_CACHE, null); 2133 // Queue up an async operation since clearing cache may take a little while. 2134 mHandler.post(new Runnable() { 2135 public void run() { 2136 mHandler.removeCallbacks(this); 2137 int retCode = -1; 2138 synchronized (mInstallLock) { 2139 retCode = mInstaller.freeCache(freeStorageSize); 2140 if (retCode < 0) { 2141 Slog.w(TAG, "Couldn't clear application caches"); 2142 } 2143 } 2144 if(pi != null) { 2145 try { 2146 // Callback via pending intent 2147 int code = (retCode >= 0) ? 1 : 0; 2148 pi.sendIntent(null, code, null, 2149 null, null); 2150 } catch (SendIntentException e1) { 2151 Slog.i(TAG, "Failed to send pending intent"); 2152 } 2153 } 2154 } 2155 }); 2156 } 2157 2158 void freeStorage(long freeStorageSize) throws IOException { 2159 synchronized (mInstallLock) { 2160 if (mInstaller.freeCache(freeStorageSize) < 0) { 2161 throw new IOException("Failed to free enough space"); 2162 } 2163 } 2164 } 2165 2166 @Override 2167 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2168 if (!sUserManager.exists(userId)) return null; 2169 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2170 synchronized (mPackages) { 2171 PackageParser.Activity a = mActivities.mActivities.get(component); 2172 2173 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2174 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2175 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2176 if (ps == null) return null; 2177 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2178 userId); 2179 } 2180 if (mResolveComponentName.equals(component)) { 2181 return mResolveActivity; 2182 } 2183 } 2184 return null; 2185 } 2186 2187 @Override 2188 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2189 String resolvedType) { 2190 synchronized (mPackages) { 2191 PackageParser.Activity a = mActivities.mActivities.get(component); 2192 if (a == null) { 2193 return false; 2194 } 2195 for (int i=0; i<a.intents.size(); i++) { 2196 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2197 intent.getData(), intent.getCategories(), TAG) >= 0) { 2198 return true; 2199 } 2200 } 2201 return false; 2202 } 2203 } 2204 2205 @Override 2206 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2207 if (!sUserManager.exists(userId)) return null; 2208 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2209 synchronized (mPackages) { 2210 PackageParser.Activity a = mReceivers.mActivities.get(component); 2211 if (DEBUG_PACKAGE_INFO) Log.v( 2212 TAG, "getReceiverInfo " + component + ": " + a); 2213 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2214 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2215 if (ps == null) return null; 2216 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2217 userId); 2218 } 2219 } 2220 return null; 2221 } 2222 2223 @Override 2224 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2225 if (!sUserManager.exists(userId)) return null; 2226 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2227 synchronized (mPackages) { 2228 PackageParser.Service s = mServices.mServices.get(component); 2229 if (DEBUG_PACKAGE_INFO) Log.v( 2230 TAG, "getServiceInfo " + component + ": " + s); 2231 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2232 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2233 if (ps == null) return null; 2234 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2235 userId); 2236 } 2237 } 2238 return null; 2239 } 2240 2241 @Override 2242 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2243 if (!sUserManager.exists(userId)) return null; 2244 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2245 synchronized (mPackages) { 2246 PackageParser.Provider p = mProviders.mProviders.get(component); 2247 if (DEBUG_PACKAGE_INFO) Log.v( 2248 TAG, "getProviderInfo " + component + ": " + p); 2249 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2250 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2251 if (ps == null) return null; 2252 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2253 userId); 2254 } 2255 } 2256 return null; 2257 } 2258 2259 @Override 2260 public String[] getSystemSharedLibraryNames() { 2261 Set<String> libSet; 2262 synchronized (mPackages) { 2263 libSet = mSharedLibraries.keySet(); 2264 int size = libSet.size(); 2265 if (size > 0) { 2266 String[] libs = new String[size]; 2267 libSet.toArray(libs); 2268 return libs; 2269 } 2270 } 2271 return null; 2272 } 2273 2274 @Override 2275 public FeatureInfo[] getSystemAvailableFeatures() { 2276 Collection<FeatureInfo> featSet; 2277 synchronized (mPackages) { 2278 featSet = mAvailableFeatures.values(); 2279 int size = featSet.size(); 2280 if (size > 0) { 2281 FeatureInfo[] features = new FeatureInfo[size+1]; 2282 featSet.toArray(features); 2283 FeatureInfo fi = new FeatureInfo(); 2284 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2285 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2286 features[size] = fi; 2287 return features; 2288 } 2289 } 2290 return null; 2291 } 2292 2293 @Override 2294 public boolean hasSystemFeature(String name) { 2295 synchronized (mPackages) { 2296 return mAvailableFeatures.containsKey(name); 2297 } 2298 } 2299 2300 private void checkValidCaller(int uid, int userId) { 2301 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2302 return; 2303 2304 throw new SecurityException("Caller uid=" + uid 2305 + " is not privileged to communicate with user=" + userId); 2306 } 2307 2308 @Override 2309 public int checkPermission(String permName, String pkgName) { 2310 synchronized (mPackages) { 2311 PackageParser.Package p = mPackages.get(pkgName); 2312 if (p != null && p.mExtras != null) { 2313 PackageSetting ps = (PackageSetting)p.mExtras; 2314 if (ps.sharedUser != null) { 2315 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2316 return PackageManager.PERMISSION_GRANTED; 2317 } 2318 } else if (ps.grantedPermissions.contains(permName)) { 2319 return PackageManager.PERMISSION_GRANTED; 2320 } 2321 } 2322 } 2323 return PackageManager.PERMISSION_DENIED; 2324 } 2325 2326 @Override 2327 public int checkUidPermission(String permName, int uid) { 2328 synchronized (mPackages) { 2329 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2330 if (obj != null) { 2331 GrantedPermissions gp = (GrantedPermissions)obj; 2332 if (gp.grantedPermissions.contains(permName)) { 2333 return PackageManager.PERMISSION_GRANTED; 2334 } 2335 } else { 2336 HashSet<String> perms = mSystemPermissions.get(uid); 2337 if (perms != null && perms.contains(permName)) { 2338 return PackageManager.PERMISSION_GRANTED; 2339 } 2340 } 2341 } 2342 return PackageManager.PERMISSION_DENIED; 2343 } 2344 2345 /** 2346 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2347 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2348 * @param message the message to log on security exception 2349 */ 2350 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2351 String message) { 2352 if (userId < 0) { 2353 throw new IllegalArgumentException("Invalid userId " + userId); 2354 } 2355 if (userId == UserHandle.getUserId(callingUid)) return; 2356 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2357 if (requireFullPermission) { 2358 mContext.enforceCallingOrSelfPermission( 2359 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2360 } else { 2361 try { 2362 mContext.enforceCallingOrSelfPermission( 2363 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2364 } catch (SecurityException se) { 2365 mContext.enforceCallingOrSelfPermission( 2366 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2367 } 2368 } 2369 } 2370 } 2371 2372 private BasePermission findPermissionTreeLP(String permName) { 2373 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2374 if (permName.startsWith(bp.name) && 2375 permName.length() > bp.name.length() && 2376 permName.charAt(bp.name.length()) == '.') { 2377 return bp; 2378 } 2379 } 2380 return null; 2381 } 2382 2383 private BasePermission checkPermissionTreeLP(String permName) { 2384 if (permName != null) { 2385 BasePermission bp = findPermissionTreeLP(permName); 2386 if (bp != null) { 2387 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2388 return bp; 2389 } 2390 throw new SecurityException("Calling uid " 2391 + Binder.getCallingUid() 2392 + " is not allowed to add to permission tree " 2393 + bp.name + " owned by uid " + bp.uid); 2394 } 2395 } 2396 throw new SecurityException("No permission tree found for " + permName); 2397 } 2398 2399 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2400 if (s1 == null) { 2401 return s2 == null; 2402 } 2403 if (s2 == null) { 2404 return false; 2405 } 2406 if (s1.getClass() != s2.getClass()) { 2407 return false; 2408 } 2409 return s1.equals(s2); 2410 } 2411 2412 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2413 if (pi1.icon != pi2.icon) return false; 2414 if (pi1.logo != pi2.logo) return false; 2415 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2416 if (!compareStrings(pi1.name, pi2.name)) return false; 2417 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2418 // We'll take care of setting this one. 2419 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2420 // These are not currently stored in settings. 2421 //if (!compareStrings(pi1.group, pi2.group)) return false; 2422 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2423 //if (pi1.labelRes != pi2.labelRes) return false; 2424 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2425 return true; 2426 } 2427 2428 int permissionInfoFootprint(PermissionInfo info) { 2429 int size = info.name.length(); 2430 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2431 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2432 return size; 2433 } 2434 2435 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2436 int size = 0; 2437 for (BasePermission perm : mSettings.mPermissions.values()) { 2438 if (perm.uid == tree.uid) { 2439 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2440 } 2441 } 2442 return size; 2443 } 2444 2445 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2446 // We calculate the max size of permissions defined by this uid and throw 2447 // if that plus the size of 'info' would exceed our stated maximum. 2448 if (tree.uid != Process.SYSTEM_UID) { 2449 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2450 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2451 throw new SecurityException("Permission tree size cap exceeded"); 2452 } 2453 } 2454 } 2455 2456 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2457 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2458 throw new SecurityException("Label must be specified in permission"); 2459 } 2460 BasePermission tree = checkPermissionTreeLP(info.name); 2461 BasePermission bp = mSettings.mPermissions.get(info.name); 2462 boolean added = bp == null; 2463 boolean changed = true; 2464 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2465 if (added) { 2466 enforcePermissionCapLocked(info, tree); 2467 bp = new BasePermission(info.name, tree.sourcePackage, 2468 BasePermission.TYPE_DYNAMIC); 2469 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2470 throw new SecurityException( 2471 "Not allowed to modify non-dynamic permission " 2472 + info.name); 2473 } else { 2474 if (bp.protectionLevel == fixedLevel 2475 && bp.perm.owner.equals(tree.perm.owner) 2476 && bp.uid == tree.uid 2477 && comparePermissionInfos(bp.perm.info, info)) { 2478 changed = false; 2479 } 2480 } 2481 bp.protectionLevel = fixedLevel; 2482 info = new PermissionInfo(info); 2483 info.protectionLevel = fixedLevel; 2484 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2485 bp.perm.info.packageName = tree.perm.info.packageName; 2486 bp.uid = tree.uid; 2487 if (added) { 2488 mSettings.mPermissions.put(info.name, bp); 2489 } 2490 if (changed) { 2491 if (!async) { 2492 mSettings.writeLPr(); 2493 } else { 2494 scheduleWriteSettingsLocked(); 2495 } 2496 } 2497 return added; 2498 } 2499 2500 @Override 2501 public boolean addPermission(PermissionInfo info) { 2502 synchronized (mPackages) { 2503 return addPermissionLocked(info, false); 2504 } 2505 } 2506 2507 @Override 2508 public boolean addPermissionAsync(PermissionInfo info) { 2509 synchronized (mPackages) { 2510 return addPermissionLocked(info, true); 2511 } 2512 } 2513 2514 @Override 2515 public void removePermission(String name) { 2516 synchronized (mPackages) { 2517 checkPermissionTreeLP(name); 2518 BasePermission bp = mSettings.mPermissions.get(name); 2519 if (bp != null) { 2520 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2521 throw new SecurityException( 2522 "Not allowed to modify non-dynamic permission " 2523 + name); 2524 } 2525 mSettings.mPermissions.remove(name); 2526 mSettings.writeLPr(); 2527 } 2528 } 2529 } 2530 2531 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2532 int index = pkg.requestedPermissions.indexOf(bp.name); 2533 if (index == -1) { 2534 throw new SecurityException("Package " + pkg.packageName 2535 + " has not requested permission " + bp.name); 2536 } 2537 boolean isNormal = 2538 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2539 == PermissionInfo.PROTECTION_NORMAL); 2540 boolean isDangerous = 2541 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2542 == PermissionInfo.PROTECTION_DANGEROUS); 2543 boolean isDevelopment = 2544 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2545 2546 if (!isNormal && !isDangerous && !isDevelopment) { 2547 throw new SecurityException("Permission " + bp.name 2548 + " is not a changeable permission type"); 2549 } 2550 2551 if (isNormal || isDangerous) { 2552 if (pkg.requestedPermissionsRequired.get(index)) { 2553 throw new SecurityException("Can't change " + bp.name 2554 + ". It is required by the application"); 2555 } 2556 } 2557 } 2558 2559 @Override 2560 public void grantPermission(String packageName, String permissionName) { 2561 mContext.enforceCallingOrSelfPermission( 2562 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2563 synchronized (mPackages) { 2564 final PackageParser.Package pkg = mPackages.get(packageName); 2565 if (pkg == null) { 2566 throw new IllegalArgumentException("Unknown package: " + packageName); 2567 } 2568 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2569 if (bp == null) { 2570 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2571 } 2572 2573 checkGrantRevokePermissions(pkg, bp); 2574 2575 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2576 if (ps == null) { 2577 return; 2578 } 2579 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2580 if (gp.grantedPermissions.add(permissionName)) { 2581 if (ps.haveGids) { 2582 gp.gids = appendInts(gp.gids, bp.gids); 2583 } 2584 mSettings.writeLPr(); 2585 } 2586 } 2587 } 2588 2589 @Override 2590 public void revokePermission(String packageName, String permissionName) { 2591 int changedAppId = -1; 2592 2593 synchronized (mPackages) { 2594 final PackageParser.Package pkg = mPackages.get(packageName); 2595 if (pkg == null) { 2596 throw new IllegalArgumentException("Unknown package: " + packageName); 2597 } 2598 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2599 mContext.enforceCallingOrSelfPermission( 2600 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2601 } 2602 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2603 if (bp == null) { 2604 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2605 } 2606 2607 checkGrantRevokePermissions(pkg, bp); 2608 2609 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2610 if (ps == null) { 2611 return; 2612 } 2613 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2614 if (gp.grantedPermissions.remove(permissionName)) { 2615 gp.grantedPermissions.remove(permissionName); 2616 if (ps.haveGids) { 2617 gp.gids = removeInts(gp.gids, bp.gids); 2618 } 2619 mSettings.writeLPr(); 2620 changedAppId = ps.appId; 2621 } 2622 } 2623 2624 if (changedAppId >= 0) { 2625 // We changed the perm on someone, kill its processes. 2626 IActivityManager am = ActivityManagerNative.getDefault(); 2627 if (am != null) { 2628 final int callingUserId = UserHandle.getCallingUserId(); 2629 final long ident = Binder.clearCallingIdentity(); 2630 try { 2631 //XXX we should only revoke for the calling user's app permissions, 2632 // but for now we impact all users. 2633 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2634 // "revoke " + permissionName); 2635 int[] users = sUserManager.getUserIds(); 2636 for (int user : users) { 2637 am.killUid(UserHandle.getUid(user, changedAppId), 2638 "revoke " + permissionName); 2639 } 2640 } catch (RemoteException e) { 2641 } finally { 2642 Binder.restoreCallingIdentity(ident); 2643 } 2644 } 2645 } 2646 } 2647 2648 @Override 2649 public boolean isProtectedBroadcast(String actionName) { 2650 synchronized (mPackages) { 2651 return mProtectedBroadcasts.contains(actionName); 2652 } 2653 } 2654 2655 @Override 2656 public int checkSignatures(String pkg1, String pkg2) { 2657 synchronized (mPackages) { 2658 final PackageParser.Package p1 = mPackages.get(pkg1); 2659 final PackageParser.Package p2 = mPackages.get(pkg2); 2660 if (p1 == null || p1.mExtras == null 2661 || p2 == null || p2.mExtras == null) { 2662 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2663 } 2664 return compareSignatures(p1.mSignatures, p2.mSignatures); 2665 } 2666 } 2667 2668 @Override 2669 public int checkUidSignatures(int uid1, int uid2) { 2670 // Map to base uids. 2671 uid1 = UserHandle.getAppId(uid1); 2672 uid2 = UserHandle.getAppId(uid2); 2673 // reader 2674 synchronized (mPackages) { 2675 Signature[] s1; 2676 Signature[] s2; 2677 Object obj = mSettings.getUserIdLPr(uid1); 2678 if (obj != null) { 2679 if (obj instanceof SharedUserSetting) { 2680 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2681 } else if (obj instanceof PackageSetting) { 2682 s1 = ((PackageSetting)obj).signatures.mSignatures; 2683 } else { 2684 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2685 } 2686 } else { 2687 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2688 } 2689 obj = mSettings.getUserIdLPr(uid2); 2690 if (obj != null) { 2691 if (obj instanceof SharedUserSetting) { 2692 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2693 } else if (obj instanceof PackageSetting) { 2694 s2 = ((PackageSetting)obj).signatures.mSignatures; 2695 } else { 2696 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2697 } 2698 } else { 2699 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2700 } 2701 return compareSignatures(s1, s2); 2702 } 2703 } 2704 2705 /** 2706 * Compares two sets of signatures. Returns: 2707 * <br /> 2708 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2709 * <br /> 2710 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2711 * <br /> 2712 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2713 * <br /> 2714 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2715 * <br /> 2716 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2717 */ 2718 static int compareSignatures(Signature[] s1, Signature[] s2) { 2719 if (s1 == null) { 2720 return s2 == null 2721 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2722 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2723 } 2724 2725 if (s2 == null) { 2726 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2727 } 2728 2729 if (s1.length != s2.length) { 2730 return PackageManager.SIGNATURE_NO_MATCH; 2731 } 2732 2733 // Since both signature sets are of size 1, we can compare without HashSets. 2734 if (s1.length == 1) { 2735 return s1[0].equals(s2[0]) ? 2736 PackageManager.SIGNATURE_MATCH : 2737 PackageManager.SIGNATURE_NO_MATCH; 2738 } 2739 2740 HashSet<Signature> set1 = new HashSet<Signature>(); 2741 for (Signature sig : s1) { 2742 set1.add(sig); 2743 } 2744 HashSet<Signature> set2 = new HashSet<Signature>(); 2745 for (Signature sig : s2) { 2746 set2.add(sig); 2747 } 2748 // Make sure s2 contains all signatures in s1. 2749 if (set1.equals(set2)) { 2750 return PackageManager.SIGNATURE_MATCH; 2751 } 2752 return PackageManager.SIGNATURE_NO_MATCH; 2753 } 2754 2755 /** 2756 * If the database version for this type of package (internal storage or 2757 * external storage) is less than the version where package signatures 2758 * were updated, return true. 2759 */ 2760 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2761 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2762 DatabaseVersion.SIGNATURE_END_ENTITY)) 2763 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2764 DatabaseVersion.SIGNATURE_END_ENTITY)); 2765 } 2766 2767 /** 2768 * Used for backward compatibility to make sure any packages with 2769 * certificate chains get upgraded to the new style. {@code existingSigs} 2770 * will be in the old format (since they were stored on disk from before the 2771 * system upgrade) and {@code scannedSigs} will be in the newer format. 2772 */ 2773 private int compareSignaturesCompat(PackageSignatures existingSigs, 2774 PackageParser.Package scannedPkg) { 2775 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2776 return PackageManager.SIGNATURE_NO_MATCH; 2777 } 2778 2779 HashSet<Signature> existingSet = new HashSet<Signature>(); 2780 for (Signature sig : existingSigs.mSignatures) { 2781 existingSet.add(sig); 2782 } 2783 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2784 for (Signature sig : scannedPkg.mSignatures) { 2785 try { 2786 Signature[] chainSignatures = sig.getChainSignatures(); 2787 for (Signature chainSig : chainSignatures) { 2788 scannedCompatSet.add(chainSig); 2789 } 2790 } catch (CertificateEncodingException e) { 2791 scannedCompatSet.add(sig); 2792 } 2793 } 2794 /* 2795 * Make sure the expanded scanned set contains all signatures in the 2796 * existing one. 2797 */ 2798 if (scannedCompatSet.equals(existingSet)) { 2799 // Migrate the old signatures to the new scheme. 2800 existingSigs.assignSignatures(scannedPkg.mSignatures); 2801 // The new KeySets will be re-added later in the scanning process. 2802 synchronized (mPackages) { 2803 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2804 } 2805 return PackageManager.SIGNATURE_MATCH; 2806 } 2807 return PackageManager.SIGNATURE_NO_MATCH; 2808 } 2809 2810 @Override 2811 public String[] getPackagesForUid(int uid) { 2812 uid = UserHandle.getAppId(uid); 2813 // reader 2814 synchronized (mPackages) { 2815 Object obj = mSettings.getUserIdLPr(uid); 2816 if (obj instanceof SharedUserSetting) { 2817 final SharedUserSetting sus = (SharedUserSetting) obj; 2818 final int N = sus.packages.size(); 2819 final String[] res = new String[N]; 2820 final Iterator<PackageSetting> it = sus.packages.iterator(); 2821 int i = 0; 2822 while (it.hasNext()) { 2823 res[i++] = it.next().name; 2824 } 2825 return res; 2826 } else if (obj instanceof PackageSetting) { 2827 final PackageSetting ps = (PackageSetting) obj; 2828 return new String[] { ps.name }; 2829 } 2830 } 2831 return null; 2832 } 2833 2834 @Override 2835 public String getNameForUid(int uid) { 2836 // reader 2837 synchronized (mPackages) { 2838 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2839 if (obj instanceof SharedUserSetting) { 2840 final SharedUserSetting sus = (SharedUserSetting) obj; 2841 return sus.name + ":" + sus.userId; 2842 } else if (obj instanceof PackageSetting) { 2843 final PackageSetting ps = (PackageSetting) obj; 2844 return ps.name; 2845 } 2846 } 2847 return null; 2848 } 2849 2850 @Override 2851 public int getUidForSharedUser(String sharedUserName) { 2852 if(sharedUserName == null) { 2853 return -1; 2854 } 2855 // reader 2856 synchronized (mPackages) { 2857 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2858 if (suid == null) { 2859 return -1; 2860 } 2861 return suid.userId; 2862 } 2863 } 2864 2865 @Override 2866 public int getFlagsForUid(int uid) { 2867 synchronized (mPackages) { 2868 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2869 if (obj instanceof SharedUserSetting) { 2870 final SharedUserSetting sus = (SharedUserSetting) obj; 2871 return sus.pkgFlags; 2872 } else if (obj instanceof PackageSetting) { 2873 final PackageSetting ps = (PackageSetting) obj; 2874 return ps.pkgFlags; 2875 } 2876 } 2877 return 0; 2878 } 2879 2880 @Override 2881 public String[] getAppOpPermissionPackages(String permissionName) { 2882 synchronized (mPackages) { 2883 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 2884 if (pkgs == null) { 2885 return null; 2886 } 2887 return pkgs.toArray(new String[pkgs.size()]); 2888 } 2889 } 2890 2891 @Override 2892 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2893 int flags, int userId) { 2894 if (!sUserManager.exists(userId)) return null; 2895 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2896 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2897 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2898 } 2899 2900 @Override 2901 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2902 IntentFilter filter, int match, ComponentName activity) { 2903 final int userId = UserHandle.getCallingUserId(); 2904 if (DEBUG_PREFERRED) { 2905 Log.v(TAG, "setLastChosenActivity intent=" + intent 2906 + " resolvedType=" + resolvedType 2907 + " flags=" + flags 2908 + " filter=" + filter 2909 + " match=" + match 2910 + " activity=" + activity); 2911 filter.dump(new PrintStreamPrinter(System.out), " "); 2912 } 2913 intent.setComponent(null); 2914 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2915 // Find any earlier preferred or last chosen entries and nuke them 2916 findPreferredActivity(intent, resolvedType, 2917 flags, query, 0, false, true, false, userId); 2918 // Add the new activity as the last chosen for this filter 2919 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2920 } 2921 2922 @Override 2923 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2924 final int userId = UserHandle.getCallingUserId(); 2925 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2926 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2927 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2928 false, false, false, userId); 2929 } 2930 2931 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2932 int flags, List<ResolveInfo> query, int userId) { 2933 if (query != null) { 2934 final int N = query.size(); 2935 if (N == 1) { 2936 return query.get(0); 2937 } else if (N > 1) { 2938 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2939 // If there is more than one activity with the same priority, 2940 // then let the user decide between them. 2941 ResolveInfo r0 = query.get(0); 2942 ResolveInfo r1 = query.get(1); 2943 if (DEBUG_INTENT_MATCHING || debug) { 2944 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2945 + r1.activityInfo.name + "=" + r1.priority); 2946 } 2947 // If the first activity has a higher priority, or a different 2948 // default, then it is always desireable to pick it. 2949 if (r0.priority != r1.priority 2950 || r0.preferredOrder != r1.preferredOrder 2951 || r0.isDefault != r1.isDefault) { 2952 return query.get(0); 2953 } 2954 // If we have saved a preference for a preferred activity for 2955 // this Intent, use that. 2956 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2957 flags, query, r0.priority, true, false, debug, userId); 2958 if (ri != null) { 2959 return ri; 2960 } 2961 if (userId != 0) { 2962 ri = new ResolveInfo(mResolveInfo); 2963 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2964 ri.activityInfo.applicationInfo = new ApplicationInfo( 2965 ri.activityInfo.applicationInfo); 2966 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2967 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2968 return ri; 2969 } 2970 return mResolveInfo; 2971 } 2972 } 2973 return null; 2974 } 2975 2976 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2977 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2978 final int N = query.size(); 2979 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2980 .get(userId); 2981 // Get the list of persistent preferred activities that handle the intent 2982 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2983 List<PersistentPreferredActivity> pprefs = ppir != null 2984 ? ppir.queryIntent(intent, resolvedType, 2985 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2986 : null; 2987 if (pprefs != null && pprefs.size() > 0) { 2988 final int M = pprefs.size(); 2989 for (int i=0; i<M; i++) { 2990 final PersistentPreferredActivity ppa = pprefs.get(i); 2991 if (DEBUG_PREFERRED || debug) { 2992 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2993 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 2994 + "\n component=" + ppa.mComponent); 2995 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2996 } 2997 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 2998 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 2999 if (DEBUG_PREFERRED || debug) { 3000 Slog.v(TAG, "Found persistent preferred activity:"); 3001 if (ai != null) { 3002 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3003 } else { 3004 Slog.v(TAG, " null"); 3005 } 3006 } 3007 if (ai == null) { 3008 // This previously registered persistent preferred activity 3009 // component is no longer known. Ignore it and do NOT remove it. 3010 continue; 3011 } 3012 for (int j=0; j<N; j++) { 3013 final ResolveInfo ri = query.get(j); 3014 if (!ri.activityInfo.applicationInfo.packageName 3015 .equals(ai.applicationInfo.packageName)) { 3016 continue; 3017 } 3018 if (!ri.activityInfo.name.equals(ai.name)) { 3019 continue; 3020 } 3021 // Found a persistent preference that can handle the intent. 3022 if (DEBUG_PREFERRED || debug) { 3023 Slog.v(TAG, "Returning persistent preferred activity: " + 3024 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3025 } 3026 return ri; 3027 } 3028 } 3029 } 3030 return null; 3031 } 3032 3033 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3034 List<ResolveInfo> query, int priority, boolean always, 3035 boolean removeMatches, boolean debug, int userId) { 3036 if (!sUserManager.exists(userId)) return null; 3037 // writer 3038 synchronized (mPackages) { 3039 if (intent.getSelector() != null) { 3040 intent = intent.getSelector(); 3041 } 3042 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3043 3044 // Try to find a matching persistent preferred activity. 3045 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3046 debug, userId); 3047 3048 // If a persistent preferred activity matched, use it. 3049 if (pri != null) { 3050 return pri; 3051 } 3052 3053 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3054 // Get the list of preferred activities that handle the intent 3055 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3056 List<PreferredActivity> prefs = pir != null 3057 ? pir.queryIntent(intent, resolvedType, 3058 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3059 : null; 3060 if (prefs != null && prefs.size() > 0) { 3061 // First figure out how good the original match set is. 3062 // We will only allow preferred activities that came 3063 // from the same match quality. 3064 int match = 0; 3065 3066 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3067 3068 final int N = query.size(); 3069 for (int j=0; j<N; j++) { 3070 final ResolveInfo ri = query.get(j); 3071 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3072 + ": 0x" + Integer.toHexString(match)); 3073 if (ri.match > match) { 3074 match = ri.match; 3075 } 3076 } 3077 3078 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3079 + Integer.toHexString(match)); 3080 3081 match &= IntentFilter.MATCH_CATEGORY_MASK; 3082 final int M = prefs.size(); 3083 for (int i=0; i<M; i++) { 3084 final PreferredActivity pa = prefs.get(i); 3085 if (DEBUG_PREFERRED || debug) { 3086 Slog.v(TAG, "Checking PreferredActivity ds=" 3087 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3088 + "\n component=" + pa.mPref.mComponent); 3089 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3090 } 3091 if (pa.mPref.mMatch != match) { 3092 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3093 + Integer.toHexString(pa.mPref.mMatch)); 3094 continue; 3095 } 3096 // If it's not an "always" type preferred activity and that's what we're 3097 // looking for, skip it. 3098 if (always && !pa.mPref.mAlways) { 3099 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3100 continue; 3101 } 3102 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3103 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3104 if (DEBUG_PREFERRED || debug) { 3105 Slog.v(TAG, "Found preferred activity:"); 3106 if (ai != null) { 3107 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3108 } else { 3109 Slog.v(TAG, " null"); 3110 } 3111 } 3112 if (ai == null) { 3113 // This previously registered preferred activity 3114 // component is no longer known. Most likely an update 3115 // to the app was installed and in the new version this 3116 // component no longer exists. Clean it up by removing 3117 // it from the preferred activities list, and skip it. 3118 Slog.w(TAG, "Removing dangling preferred activity: " 3119 + pa.mPref.mComponent); 3120 pir.removeFilter(pa); 3121 continue; 3122 } 3123 for (int j=0; j<N; j++) { 3124 final ResolveInfo ri = query.get(j); 3125 if (!ri.activityInfo.applicationInfo.packageName 3126 .equals(ai.applicationInfo.packageName)) { 3127 continue; 3128 } 3129 if (!ri.activityInfo.name.equals(ai.name)) { 3130 continue; 3131 } 3132 3133 if (removeMatches) { 3134 pir.removeFilter(pa); 3135 if (DEBUG_PREFERRED) { 3136 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3137 } 3138 break; 3139 } 3140 3141 // Okay we found a previously set preferred or last chosen app. 3142 // If the result set is different from when this 3143 // was created, we need to clear it and re-ask the 3144 // user their preference, if we're looking for an "always" type entry. 3145 if (always && !pa.mPref.sameSet(query, priority)) { 3146 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3147 + intent + " type " + resolvedType); 3148 if (DEBUG_PREFERRED) { 3149 Slog.v(TAG, "Removing preferred activity since set changed " 3150 + pa.mPref.mComponent); 3151 } 3152 pir.removeFilter(pa); 3153 // Re-add the filter as a "last chosen" entry (!always) 3154 PreferredActivity lastChosen = new PreferredActivity( 3155 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3156 pir.addFilter(lastChosen); 3157 mSettings.writePackageRestrictionsLPr(userId); 3158 return null; 3159 } 3160 3161 // Yay! Either the set matched or we're looking for the last chosen 3162 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3163 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3164 mSettings.writePackageRestrictionsLPr(userId); 3165 return ri; 3166 } 3167 } 3168 } 3169 mSettings.writePackageRestrictionsLPr(userId); 3170 } 3171 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3172 return null; 3173 } 3174 3175 /* 3176 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3177 */ 3178 @Override 3179 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3180 int targetUserId) { 3181 mContext.enforceCallingOrSelfPermission( 3182 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3183 List<CrossProfileIntentFilter> matches = 3184 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3185 if (matches != null) { 3186 int size = matches.size(); 3187 for (int i = 0; i < size; i++) { 3188 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3189 } 3190 } 3191 3192 ArrayList<String> packageNames = null; 3193 SparseArray<ArrayList<String>> fromSource = 3194 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3195 if (fromSource != null) { 3196 packageNames = fromSource.get(targetUserId); 3197 } 3198 if (packageNames != null && packageNames.contains(intent.getPackage())) { 3199 return true; 3200 } 3201 // We need the package name, so we try to resolve with the loosest flags possible 3202 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3203 intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3204 int count = resolveInfos.size(); 3205 for (int i = 0; i < count; i++) { 3206 ResolveInfo resolveInfo = resolveInfos.get(i); 3207 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3208 return true; 3209 } 3210 } 3211 return false; 3212 } 3213 3214 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3215 String resolvedType, int userId) { 3216 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3217 if (resolver != null) { 3218 return resolver.queryIntent(intent, resolvedType, false, userId); 3219 } 3220 return null; 3221 } 3222 3223 @Override 3224 public List<ResolveInfo> queryIntentActivities(Intent intent, 3225 String resolvedType, int flags, int userId) { 3226 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3227 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3228 ComponentName comp = intent.getComponent(); 3229 if (comp == null) { 3230 if (intent.getSelector() != null) { 3231 intent = intent.getSelector(); 3232 comp = intent.getComponent(); 3233 } 3234 } 3235 3236 if (comp != null) { 3237 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3238 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3239 if (ai != null) { 3240 final ResolveInfo ri = new ResolveInfo(); 3241 ri.activityInfo = ai; 3242 list.add(ri); 3243 } 3244 return list; 3245 } 3246 3247 // reader 3248 synchronized (mPackages) { 3249 final String pkgName = intent.getPackage(); 3250 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3251 if (pkgName == null) { 3252 ResolveInfo resolveInfo = null; 3253 if (queryCrossProfile) { 3254 // Check if the intent needs to be forwarded to another user for this package 3255 ArrayList<ResolveInfo> crossProfileResult = 3256 queryIntentActivitiesCrossProfilePackage( 3257 intent, resolvedType, flags, userId); 3258 if (!crossProfileResult.isEmpty()) { 3259 // Skip the current profile 3260 return crossProfileResult; 3261 } 3262 List<CrossProfileIntentFilter> matchingFilters = 3263 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3264 // Check for results that need to skip the current profile. 3265 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3266 resolvedType, flags, userId); 3267 if (resolveInfo != null) { 3268 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3269 result.add(resolveInfo); 3270 return result; 3271 } 3272 // Check for cross profile results. 3273 resolveInfo = queryCrossProfileIntents( 3274 matchingFilters, intent, resolvedType, flags, userId); 3275 } 3276 // Check for results in the current profile. 3277 List<ResolveInfo> result = mActivities.queryIntent( 3278 intent, resolvedType, flags, userId); 3279 if (resolveInfo != null) { 3280 result.add(resolveInfo); 3281 } 3282 return result; 3283 } 3284 final PackageParser.Package pkg = mPackages.get(pkgName); 3285 if (pkg != null) { 3286 if (queryCrossProfile) { 3287 ArrayList<ResolveInfo> crossProfileResult = 3288 queryIntentActivitiesCrossProfilePackage( 3289 intent, resolvedType, flags, userId, pkg, pkgName); 3290 if (!crossProfileResult.isEmpty()) { 3291 // Skip the current profile 3292 return crossProfileResult; 3293 } 3294 } 3295 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3296 pkg.activities, userId); 3297 } 3298 return new ArrayList<ResolveInfo>(); 3299 } 3300 } 3301 3302 private ResolveInfo querySkipCurrentProfileIntents( 3303 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3304 int flags, int sourceUserId) { 3305 if (matchingFilters != null) { 3306 int size = matchingFilters.size(); 3307 for (int i = 0; i < size; i ++) { 3308 CrossProfileIntentFilter filter = matchingFilters.get(i); 3309 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3310 // Checking if there are activities in the target user that can handle the 3311 // intent. 3312 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3313 flags, sourceUserId); 3314 if (resolveInfo != null) { 3315 return resolveInfo; 3316 } 3317 } 3318 } 3319 } 3320 return null; 3321 } 3322 3323 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3324 Intent intent, String resolvedType, int flags, int userId) { 3325 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3326 SparseArray<ArrayList<String>> sourceForwardingInfo = 3327 mSettings.mCrossProfilePackageInfo.get(userId); 3328 if (sourceForwardingInfo != null) { 3329 int NI = sourceForwardingInfo.size(); 3330 for (int i = 0; i < NI; i++) { 3331 int targetUserId = sourceForwardingInfo.keyAt(i); 3332 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3333 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3334 intent, resolvedType, flags, targetUserId); 3335 int NJ = resolveInfos.size(); 3336 for (int j = 0; j < NJ; j++) { 3337 ResolveInfo resolveInfo = resolveInfos.get(j); 3338 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3339 matchingResolveInfos.add(createForwardingResolveInfo( 3340 resolveInfo.filter, userId, targetUserId)); 3341 } 3342 } 3343 } 3344 } 3345 return matchingResolveInfos; 3346 } 3347 3348 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3349 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3350 String packageName) { 3351 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3352 SparseArray<ArrayList<String>> sourceForwardingInfo = 3353 mSettings.mCrossProfilePackageInfo.get(userId); 3354 if (sourceForwardingInfo != null) { 3355 int NI = sourceForwardingInfo.size(); 3356 for (int i = 0; i < NI; i++) { 3357 int targetUserId = sourceForwardingInfo.keyAt(i); 3358 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3359 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3360 intent, resolvedType, flags, pkg.activities, targetUserId); 3361 int NJ = resolveInfos.size(); 3362 for (int j = 0; j < NJ; j++) { 3363 ResolveInfo resolveInfo = resolveInfos.get(j); 3364 matchingResolveInfos.add(createForwardingResolveInfo( 3365 resolveInfo.filter, userId, targetUserId)); 3366 } 3367 } 3368 } 3369 } 3370 return matchingResolveInfos; 3371 } 3372 3373 // Return matching ResolveInfo if any for skip current profile intent filters. 3374 private ResolveInfo queryCrossProfileIntents( 3375 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3376 int flags, int sourceUserId) { 3377 if (matchingFilters != null) { 3378 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3379 // match the same intent. For performance reasons, it is better not to 3380 // run queryIntent twice for the same userId 3381 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3382 int size = matchingFilters.size(); 3383 for (int i = 0; i < size; i++) { 3384 CrossProfileIntentFilter filter = matchingFilters.get(i); 3385 int targetUserId = filter.getTargetUserId(); 3386 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3387 && !alreadyTriedUserIds.get(targetUserId)) { 3388 // Checking if there are activities in the target user that can handle the 3389 // intent. 3390 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3391 flags, sourceUserId); 3392 if (resolveInfo != null) return resolveInfo; 3393 alreadyTriedUserIds.put(targetUserId, true); 3394 } 3395 } 3396 } 3397 return null; 3398 } 3399 3400 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3401 String resolvedType, int flags, int sourceUserId) { 3402 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3403 resolvedType, flags, filter.getTargetUserId()); 3404 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3405 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3406 } 3407 return null; 3408 } 3409 3410 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3411 int sourceUserId, int targetUserId) { 3412 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3413 String className; 3414 if (targetUserId == UserHandle.USER_OWNER) { 3415 className = FORWARD_INTENT_TO_USER_OWNER; 3416 } else { 3417 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3418 } 3419 ComponentName forwardingActivityComponentName = new ComponentName( 3420 mAndroidApplication.packageName, className); 3421 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3422 sourceUserId); 3423 if (targetUserId == UserHandle.USER_OWNER) { 3424 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3425 forwardingResolveInfo.noResourceId = true; 3426 } 3427 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3428 forwardingResolveInfo.priority = 0; 3429 forwardingResolveInfo.preferredOrder = 0; 3430 forwardingResolveInfo.match = 0; 3431 forwardingResolveInfo.isDefault = true; 3432 forwardingResolveInfo.filter = filter; 3433 forwardingResolveInfo.targetUserId = targetUserId; 3434 return forwardingResolveInfo; 3435 } 3436 3437 @Override 3438 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3439 Intent[] specifics, String[] specificTypes, Intent intent, 3440 String resolvedType, int flags, int userId) { 3441 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3442 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3443 "query intent activity options"); 3444 final String resultsAction = intent.getAction(); 3445 3446 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3447 | PackageManager.GET_RESOLVED_FILTER, userId); 3448 3449 if (DEBUG_INTENT_MATCHING) { 3450 Log.v(TAG, "Query " + intent + ": " + results); 3451 } 3452 3453 int specificsPos = 0; 3454 int N; 3455 3456 // todo: note that the algorithm used here is O(N^2). This 3457 // isn't a problem in our current environment, but if we start running 3458 // into situations where we have more than 5 or 10 matches then this 3459 // should probably be changed to something smarter... 3460 3461 // First we go through and resolve each of the specific items 3462 // that were supplied, taking care of removing any corresponding 3463 // duplicate items in the generic resolve list. 3464 if (specifics != null) { 3465 for (int i=0; i<specifics.length; i++) { 3466 final Intent sintent = specifics[i]; 3467 if (sintent == null) { 3468 continue; 3469 } 3470 3471 if (DEBUG_INTENT_MATCHING) { 3472 Log.v(TAG, "Specific #" + i + ": " + sintent); 3473 } 3474 3475 String action = sintent.getAction(); 3476 if (resultsAction != null && resultsAction.equals(action)) { 3477 // If this action was explicitly requested, then don't 3478 // remove things that have it. 3479 action = null; 3480 } 3481 3482 ResolveInfo ri = null; 3483 ActivityInfo ai = null; 3484 3485 ComponentName comp = sintent.getComponent(); 3486 if (comp == null) { 3487 ri = resolveIntent( 3488 sintent, 3489 specificTypes != null ? specificTypes[i] : null, 3490 flags, userId); 3491 if (ri == null) { 3492 continue; 3493 } 3494 if (ri == mResolveInfo) { 3495 // ACK! Must do something better with this. 3496 } 3497 ai = ri.activityInfo; 3498 comp = new ComponentName(ai.applicationInfo.packageName, 3499 ai.name); 3500 } else { 3501 ai = getActivityInfo(comp, flags, userId); 3502 if (ai == null) { 3503 continue; 3504 } 3505 } 3506 3507 // Look for any generic query activities that are duplicates 3508 // of this specific one, and remove them from the results. 3509 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3510 N = results.size(); 3511 int j; 3512 for (j=specificsPos; j<N; j++) { 3513 ResolveInfo sri = results.get(j); 3514 if ((sri.activityInfo.name.equals(comp.getClassName()) 3515 && sri.activityInfo.applicationInfo.packageName.equals( 3516 comp.getPackageName())) 3517 || (action != null && sri.filter.matchAction(action))) { 3518 results.remove(j); 3519 if (DEBUG_INTENT_MATCHING) Log.v( 3520 TAG, "Removing duplicate item from " + j 3521 + " due to specific " + specificsPos); 3522 if (ri == null) { 3523 ri = sri; 3524 } 3525 j--; 3526 N--; 3527 } 3528 } 3529 3530 // Add this specific item to its proper place. 3531 if (ri == null) { 3532 ri = new ResolveInfo(); 3533 ri.activityInfo = ai; 3534 } 3535 results.add(specificsPos, ri); 3536 ri.specificIndex = i; 3537 specificsPos++; 3538 } 3539 } 3540 3541 // Now we go through the remaining generic results and remove any 3542 // duplicate actions that are found here. 3543 N = results.size(); 3544 for (int i=specificsPos; i<N-1; i++) { 3545 final ResolveInfo rii = results.get(i); 3546 if (rii.filter == null) { 3547 continue; 3548 } 3549 3550 // Iterate over all of the actions of this result's intent 3551 // filter... typically this should be just one. 3552 final Iterator<String> it = rii.filter.actionsIterator(); 3553 if (it == null) { 3554 continue; 3555 } 3556 while (it.hasNext()) { 3557 final String action = it.next(); 3558 if (resultsAction != null && resultsAction.equals(action)) { 3559 // If this action was explicitly requested, then don't 3560 // remove things that have it. 3561 continue; 3562 } 3563 for (int j=i+1; j<N; j++) { 3564 final ResolveInfo rij = results.get(j); 3565 if (rij.filter != null && rij.filter.hasAction(action)) { 3566 results.remove(j); 3567 if (DEBUG_INTENT_MATCHING) Log.v( 3568 TAG, "Removing duplicate item from " + j 3569 + " due to action " + action + " at " + i); 3570 j--; 3571 N--; 3572 } 3573 } 3574 } 3575 3576 // If the caller didn't request filter information, drop it now 3577 // so we don't have to marshall/unmarshall it. 3578 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3579 rii.filter = null; 3580 } 3581 } 3582 3583 // Filter out the caller activity if so requested. 3584 if (caller != null) { 3585 N = results.size(); 3586 for (int i=0; i<N; i++) { 3587 ActivityInfo ainfo = results.get(i).activityInfo; 3588 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3589 && caller.getClassName().equals(ainfo.name)) { 3590 results.remove(i); 3591 break; 3592 } 3593 } 3594 } 3595 3596 // If the caller didn't request filter information, 3597 // drop them now so we don't have to 3598 // marshall/unmarshall it. 3599 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3600 N = results.size(); 3601 for (int i=0; i<N; i++) { 3602 results.get(i).filter = null; 3603 } 3604 } 3605 3606 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3607 return results; 3608 } 3609 3610 @Override 3611 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3612 int userId) { 3613 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3614 ComponentName comp = intent.getComponent(); 3615 if (comp == null) { 3616 if (intent.getSelector() != null) { 3617 intent = intent.getSelector(); 3618 comp = intent.getComponent(); 3619 } 3620 } 3621 if (comp != null) { 3622 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3623 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3624 if (ai != null) { 3625 ResolveInfo ri = new ResolveInfo(); 3626 ri.activityInfo = ai; 3627 list.add(ri); 3628 } 3629 return list; 3630 } 3631 3632 // reader 3633 synchronized (mPackages) { 3634 String pkgName = intent.getPackage(); 3635 if (pkgName == null) { 3636 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3637 } 3638 final PackageParser.Package pkg = mPackages.get(pkgName); 3639 if (pkg != null) { 3640 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3641 userId); 3642 } 3643 return null; 3644 } 3645 } 3646 3647 @Override 3648 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3649 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3650 if (!sUserManager.exists(userId)) return null; 3651 if (query != null) { 3652 if (query.size() >= 1) { 3653 // If there is more than one service with the same priority, 3654 // just arbitrarily pick the first one. 3655 return query.get(0); 3656 } 3657 } 3658 return null; 3659 } 3660 3661 @Override 3662 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3663 int userId) { 3664 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3665 ComponentName comp = intent.getComponent(); 3666 if (comp == null) { 3667 if (intent.getSelector() != null) { 3668 intent = intent.getSelector(); 3669 comp = intent.getComponent(); 3670 } 3671 } 3672 if (comp != null) { 3673 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3674 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3675 if (si != null) { 3676 final ResolveInfo ri = new ResolveInfo(); 3677 ri.serviceInfo = si; 3678 list.add(ri); 3679 } 3680 return list; 3681 } 3682 3683 // reader 3684 synchronized (mPackages) { 3685 String pkgName = intent.getPackage(); 3686 if (pkgName == null) { 3687 return mServices.queryIntent(intent, resolvedType, flags, userId); 3688 } 3689 final PackageParser.Package pkg = mPackages.get(pkgName); 3690 if (pkg != null) { 3691 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3692 userId); 3693 } 3694 return null; 3695 } 3696 } 3697 3698 @Override 3699 public List<ResolveInfo> queryIntentContentProviders( 3700 Intent intent, String resolvedType, int flags, int userId) { 3701 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3702 ComponentName comp = intent.getComponent(); 3703 if (comp == null) { 3704 if (intent.getSelector() != null) { 3705 intent = intent.getSelector(); 3706 comp = intent.getComponent(); 3707 } 3708 } 3709 if (comp != null) { 3710 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3711 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3712 if (pi != null) { 3713 final ResolveInfo ri = new ResolveInfo(); 3714 ri.providerInfo = pi; 3715 list.add(ri); 3716 } 3717 return list; 3718 } 3719 3720 // reader 3721 synchronized (mPackages) { 3722 String pkgName = intent.getPackage(); 3723 if (pkgName == null) { 3724 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3725 } 3726 final PackageParser.Package pkg = mPackages.get(pkgName); 3727 if (pkg != null) { 3728 return mProviders.queryIntentForPackage( 3729 intent, resolvedType, flags, pkg.providers, userId); 3730 } 3731 return null; 3732 } 3733 } 3734 3735 @Override 3736 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3737 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3738 3739 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3740 3741 // writer 3742 synchronized (mPackages) { 3743 ArrayList<PackageInfo> list; 3744 if (listUninstalled) { 3745 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3746 for (PackageSetting ps : mSettings.mPackages.values()) { 3747 PackageInfo pi; 3748 if (ps.pkg != null) { 3749 pi = generatePackageInfo(ps.pkg, flags, userId); 3750 } else { 3751 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3752 } 3753 if (pi != null) { 3754 list.add(pi); 3755 } 3756 } 3757 } else { 3758 list = new ArrayList<PackageInfo>(mPackages.size()); 3759 for (PackageParser.Package p : mPackages.values()) { 3760 PackageInfo pi = generatePackageInfo(p, flags, userId); 3761 if (pi != null) { 3762 list.add(pi); 3763 } 3764 } 3765 } 3766 3767 return new ParceledListSlice<PackageInfo>(list); 3768 } 3769 } 3770 3771 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3772 String[] permissions, boolean[] tmp, int flags, int userId) { 3773 int numMatch = 0; 3774 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3775 for (int i=0; i<permissions.length; i++) { 3776 if (gp.grantedPermissions.contains(permissions[i])) { 3777 tmp[i] = true; 3778 numMatch++; 3779 } else { 3780 tmp[i] = false; 3781 } 3782 } 3783 if (numMatch == 0) { 3784 return; 3785 } 3786 PackageInfo pi; 3787 if (ps.pkg != null) { 3788 pi = generatePackageInfo(ps.pkg, flags, userId); 3789 } else { 3790 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3791 } 3792 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3793 if (numMatch == permissions.length) { 3794 pi.requestedPermissions = permissions; 3795 } else { 3796 pi.requestedPermissions = new String[numMatch]; 3797 numMatch = 0; 3798 for (int i=0; i<permissions.length; i++) { 3799 if (tmp[i]) { 3800 pi.requestedPermissions[numMatch] = permissions[i]; 3801 numMatch++; 3802 } 3803 } 3804 } 3805 } 3806 list.add(pi); 3807 } 3808 3809 @Override 3810 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3811 String[] permissions, int flags, int userId) { 3812 if (!sUserManager.exists(userId)) return null; 3813 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3814 3815 // writer 3816 synchronized (mPackages) { 3817 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3818 boolean[] tmpBools = new boolean[permissions.length]; 3819 if (listUninstalled) { 3820 for (PackageSetting ps : mSettings.mPackages.values()) { 3821 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3822 } 3823 } else { 3824 for (PackageParser.Package pkg : mPackages.values()) { 3825 PackageSetting ps = (PackageSetting)pkg.mExtras; 3826 if (ps != null) { 3827 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3828 userId); 3829 } 3830 } 3831 } 3832 3833 return new ParceledListSlice<PackageInfo>(list); 3834 } 3835 } 3836 3837 @Override 3838 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3839 if (!sUserManager.exists(userId)) return null; 3840 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3841 3842 // writer 3843 synchronized (mPackages) { 3844 ArrayList<ApplicationInfo> list; 3845 if (listUninstalled) { 3846 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3847 for (PackageSetting ps : mSettings.mPackages.values()) { 3848 ApplicationInfo ai; 3849 if (ps.pkg != null) { 3850 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3851 ps.readUserState(userId), userId); 3852 } else { 3853 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3854 } 3855 if (ai != null) { 3856 list.add(ai); 3857 } 3858 } 3859 } else { 3860 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3861 for (PackageParser.Package p : mPackages.values()) { 3862 if (p.mExtras != null) { 3863 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3864 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3865 if (ai != null) { 3866 list.add(ai); 3867 } 3868 } 3869 } 3870 } 3871 3872 return new ParceledListSlice<ApplicationInfo>(list); 3873 } 3874 } 3875 3876 public List<ApplicationInfo> getPersistentApplications(int flags) { 3877 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3878 3879 // reader 3880 synchronized (mPackages) { 3881 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3882 final int userId = UserHandle.getCallingUserId(); 3883 while (i.hasNext()) { 3884 final PackageParser.Package p = i.next(); 3885 if (p.applicationInfo != null 3886 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3887 && (!mSafeMode || isSystemApp(p))) { 3888 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3889 if (ps != null) { 3890 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3891 ps.readUserState(userId), userId); 3892 if (ai != null) { 3893 finalList.add(ai); 3894 } 3895 } 3896 } 3897 } 3898 } 3899 3900 return finalList; 3901 } 3902 3903 @Override 3904 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3905 if (!sUserManager.exists(userId)) return null; 3906 // reader 3907 synchronized (mPackages) { 3908 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3909 PackageSetting ps = provider != null 3910 ? mSettings.mPackages.get(provider.owner.packageName) 3911 : null; 3912 return ps != null 3913 && mSettings.isEnabledLPr(provider.info, flags, userId) 3914 && (!mSafeMode || (provider.info.applicationInfo.flags 3915 &ApplicationInfo.FLAG_SYSTEM) != 0) 3916 ? PackageParser.generateProviderInfo(provider, flags, 3917 ps.readUserState(userId), userId) 3918 : null; 3919 } 3920 } 3921 3922 /** 3923 * @deprecated 3924 */ 3925 @Deprecated 3926 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3927 // reader 3928 synchronized (mPackages) { 3929 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3930 .entrySet().iterator(); 3931 final int userId = UserHandle.getCallingUserId(); 3932 while (i.hasNext()) { 3933 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3934 PackageParser.Provider p = entry.getValue(); 3935 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3936 3937 if (ps != null && p.syncable 3938 && (!mSafeMode || (p.info.applicationInfo.flags 3939 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3940 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3941 ps.readUserState(userId), userId); 3942 if (info != null) { 3943 outNames.add(entry.getKey()); 3944 outInfo.add(info); 3945 } 3946 } 3947 } 3948 } 3949 } 3950 3951 @Override 3952 public List<ProviderInfo> queryContentProviders(String processName, 3953 int uid, int flags) { 3954 ArrayList<ProviderInfo> finalList = null; 3955 // reader 3956 synchronized (mPackages) { 3957 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3958 final int userId = processName != null ? 3959 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3960 while (i.hasNext()) { 3961 final PackageParser.Provider p = i.next(); 3962 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3963 if (ps != null && p.info.authority != null 3964 && (processName == null 3965 || (p.info.processName.equals(processName) 3966 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3967 && mSettings.isEnabledLPr(p.info, flags, userId) 3968 && (!mSafeMode 3969 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3970 if (finalList == null) { 3971 finalList = new ArrayList<ProviderInfo>(3); 3972 } 3973 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3974 ps.readUserState(userId), userId); 3975 if (info != null) { 3976 finalList.add(info); 3977 } 3978 } 3979 } 3980 } 3981 3982 if (finalList != null) { 3983 Collections.sort(finalList, mProviderInitOrderSorter); 3984 } 3985 3986 return finalList; 3987 } 3988 3989 @Override 3990 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3991 int flags) { 3992 // reader 3993 synchronized (mPackages) { 3994 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3995 return PackageParser.generateInstrumentationInfo(i, flags); 3996 } 3997 } 3998 3999 @Override 4000 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4001 int flags) { 4002 ArrayList<InstrumentationInfo> finalList = 4003 new ArrayList<InstrumentationInfo>(); 4004 4005 // reader 4006 synchronized (mPackages) { 4007 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4008 while (i.hasNext()) { 4009 final PackageParser.Instrumentation p = i.next(); 4010 if (targetPackage == null 4011 || targetPackage.equals(p.info.targetPackage)) { 4012 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4013 flags); 4014 if (ii != null) { 4015 finalList.add(ii); 4016 } 4017 } 4018 } 4019 } 4020 4021 return finalList; 4022 } 4023 4024 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4025 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4026 if (overlays == null) { 4027 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4028 return; 4029 } 4030 for (PackageParser.Package opkg : overlays.values()) { 4031 // Not much to do if idmap fails: we already logged the error 4032 // and we certainly don't want to abort installation of pkg simply 4033 // because an overlay didn't fit properly. For these reasons, 4034 // ignore the return value of createIdmapForPackagePairLI. 4035 createIdmapForPackagePairLI(pkg, opkg); 4036 } 4037 } 4038 4039 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4040 PackageParser.Package opkg) { 4041 if (!opkg.mTrustedOverlay) { 4042 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4043 opkg.baseCodePath + ": overlay not trusted"); 4044 return false; 4045 } 4046 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4047 if (overlaySet == null) { 4048 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4049 opkg.baseCodePath + " but target package has no known overlays"); 4050 return false; 4051 } 4052 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4053 // TODO: generate idmap for split APKs 4054 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4055 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4056 + opkg.baseCodePath); 4057 return false; 4058 } 4059 PackageParser.Package[] overlayArray = 4060 overlaySet.values().toArray(new PackageParser.Package[0]); 4061 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4062 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4063 return p1.mOverlayPriority - p2.mOverlayPriority; 4064 } 4065 }; 4066 Arrays.sort(overlayArray, cmp); 4067 4068 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4069 int i = 0; 4070 for (PackageParser.Package p : overlayArray) { 4071 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4072 } 4073 return true; 4074 } 4075 4076 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4077 final File[] files = dir.listFiles(); 4078 if (ArrayUtils.isEmpty(files)) { 4079 Log.d(TAG, "No files in app dir " + dir); 4080 return; 4081 } 4082 4083 if (DEBUG_PACKAGE_SCANNING) { 4084 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4085 + " flags=0x" + Integer.toHexString(flags)); 4086 } 4087 4088 for (File file : files) { 4089 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4090 && !PackageInstallerService.isStageFile(file); 4091 if (!isPackage) { 4092 // Ignore entries which are not apk's 4093 continue; 4094 } 4095 try { 4096 scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, 4097 null, null); 4098 } catch (PackageManagerException e) { 4099 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4100 4101 // Don't mess around with apps in system partition. 4102 if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4103 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4104 // Delete the apk 4105 Slog.w(TAG, "Cleaning up failed install of " + file); 4106 file.delete(); 4107 } 4108 } 4109 } 4110 } 4111 4112 private static File getSettingsProblemFile() { 4113 File dataDir = Environment.getDataDirectory(); 4114 File systemDir = new File(dataDir, "system"); 4115 File fname = new File(systemDir, "uiderrors.txt"); 4116 return fname; 4117 } 4118 4119 static void reportSettingsProblem(int priority, String msg) { 4120 try { 4121 File fname = getSettingsProblemFile(); 4122 FileOutputStream out = new FileOutputStream(fname, true); 4123 PrintWriter pw = new FastPrintWriter(out); 4124 SimpleDateFormat formatter = new SimpleDateFormat(); 4125 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4126 pw.println(dateString + ": " + msg); 4127 pw.close(); 4128 FileUtils.setPermissions( 4129 fname.toString(), 4130 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4131 -1, -1); 4132 } catch (java.io.IOException e) { 4133 } 4134 Slog.println(priority, TAG, msg); 4135 } 4136 4137 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4138 PackageParser.Package pkg, File srcFile, int parseFlags) 4139 throws PackageManagerException { 4140 if (ps != null 4141 && ps.codePath.equals(srcFile) 4142 && ps.timeStamp == srcFile.lastModified() 4143 && !isCompatSignatureUpdateNeeded(pkg)) { 4144 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4145 if (ps.signatures.mSignatures != null 4146 && ps.signatures.mSignatures.length != 0 4147 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4148 // Optimization: reuse the existing cached certificates 4149 // if the package appears to be unchanged. 4150 pkg.mSignatures = ps.signatures.mSignatures; 4151 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4152 synchronized (mPackages) { 4153 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4154 } 4155 return; 4156 } 4157 4158 Slog.w(TAG, "PackageSetting for " + ps.name 4159 + " is missing signatures. Collecting certs again to recover them."); 4160 } else { 4161 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4162 } 4163 4164 try { 4165 pp.collectCertificates(pkg, parseFlags); 4166 pp.collectManifestDigest(pkg); 4167 } catch (PackageParserException e) { 4168 throw new PackageManagerException(e.error, "Failed to collect certificates for " 4169 + pkg.packageName + ": " + e.getMessage()); 4170 } 4171 } 4172 4173 /* 4174 * Scan a package and return the newly parsed package. 4175 * Returns null in case of errors and the error code is stored in mLastScanError 4176 */ 4177 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode, 4178 long currentTime, UserHandle user, String abiOverride) throws PackageManagerException { 4179 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4180 parseFlags |= mDefParseFlags; 4181 PackageParser pp = new PackageParser(); 4182 pp.setSeparateProcesses(mSeparateProcesses); 4183 pp.setOnlyCoreApps(mOnlyCore); 4184 pp.setDisplayMetrics(mMetrics); 4185 4186 if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) { 4187 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4188 } 4189 4190 final PackageParser.Package pkg; 4191 try { 4192 pkg = pp.parsePackage(scanFile, parseFlags); 4193 } catch (PackageParserException e) { 4194 throw new PackageManagerException(e.error, 4195 "Failed to scan " + scanFile + ": " + e.getMessage()); 4196 } 4197 4198 PackageSetting ps = null; 4199 PackageSetting updatedPkg; 4200 // reader 4201 synchronized (mPackages) { 4202 // Look to see if we already know about this package. 4203 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4204 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4205 // This package has been renamed to its original name. Let's 4206 // use that. 4207 ps = mSettings.peekPackageLPr(oldName); 4208 } 4209 // If there was no original package, see one for the real package name. 4210 if (ps == null) { 4211 ps = mSettings.peekPackageLPr(pkg.packageName); 4212 } 4213 // Check to see if this package could be hiding/updating a system 4214 // package. Must look for it either under the original or real 4215 // package name depending on our state. 4216 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4217 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4218 } 4219 boolean updatedPkgBetter = false; 4220 // First check if this is a system package that may involve an update 4221 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4222 if (ps != null && !ps.codePath.equals(scanFile)) { 4223 // The path has changed from what was last scanned... check the 4224 // version of the new path against what we have stored to determine 4225 // what to do. 4226 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4227 if (pkg.mVersionCode < ps.versionCode) { 4228 // The system package has been updated and the code path does not match 4229 // Ignore entry. Skip it. 4230 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4231 + " ignored: updated version " + ps.versionCode 4232 + " better than this " + pkg.mVersionCode); 4233 if (!updatedPkg.codePath.equals(scanFile)) { 4234 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4235 + ps.name + " changing from " + updatedPkg.codePathString 4236 + " to " + scanFile); 4237 updatedPkg.codePath = scanFile; 4238 updatedPkg.codePathString = scanFile.toString(); 4239 // This is the point at which we know that the system-disk APK 4240 // for this package has moved during a reboot (e.g. due to an OTA), 4241 // so we need to reevaluate it for privilege policy. 4242 if (locationIsPrivileged(scanFile)) { 4243 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4244 } 4245 } 4246 updatedPkg.pkg = pkg; 4247 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4248 } else { 4249 // The current app on the system partition is better than 4250 // what we have updated to on the data partition; switch 4251 // back to the system partition version. 4252 // At this point, its safely assumed that package installation for 4253 // apps in system partition will go through. If not there won't be a working 4254 // version of the app 4255 // writer 4256 synchronized (mPackages) { 4257 // Just remove the loaded entries from package lists. 4258 mPackages.remove(ps.name); 4259 } 4260 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4261 + "reverting from " + ps.codePathString 4262 + ": new version " + pkg.mVersionCode 4263 + " better than installed " + ps.versionCode); 4264 4265 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4266 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4267 getAppDexInstructionSets(ps), isMultiArch(ps)); 4268 synchronized (mInstallLock) { 4269 args.cleanUpResourcesLI(); 4270 } 4271 synchronized (mPackages) { 4272 mSettings.enableSystemPackageLPw(ps.name); 4273 } 4274 updatedPkgBetter = true; 4275 } 4276 } 4277 } 4278 4279 if (updatedPkg != null) { 4280 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4281 // initially 4282 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4283 4284 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4285 // flag set initially 4286 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4287 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4288 } 4289 } 4290 4291 // Verify certificates against what was last scanned 4292 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4293 4294 /* 4295 * A new system app appeared, but we already had a non-system one of the 4296 * same name installed earlier. 4297 */ 4298 boolean shouldHideSystemApp = false; 4299 if (updatedPkg == null && ps != null 4300 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4301 /* 4302 * Check to make sure the signatures match first. If they don't, 4303 * wipe the installed application and its data. 4304 */ 4305 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4306 != PackageManager.SIGNATURE_MATCH) { 4307 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4308 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4309 ps = null; 4310 } else { 4311 /* 4312 * If the newly-added system app is an older version than the 4313 * already installed version, hide it. It will be scanned later 4314 * and re-added like an update. 4315 */ 4316 if (pkg.mVersionCode < ps.versionCode) { 4317 shouldHideSystemApp = true; 4318 } else { 4319 /* 4320 * The newly found system app is a newer version that the 4321 * one previously installed. Simply remove the 4322 * already-installed application and replace it with our own 4323 * while keeping the application data. 4324 */ 4325 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4326 + ps.codePathString + ": new version " + pkg.mVersionCode 4327 + " better than installed " + ps.versionCode); 4328 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4329 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4330 getAppDexInstructionSets(ps), isMultiArch(ps)); 4331 synchronized (mInstallLock) { 4332 args.cleanUpResourcesLI(); 4333 } 4334 } 4335 } 4336 } 4337 4338 // The apk is forward locked (not public) if its code and resources 4339 // are kept in different files. (except for app in either system or 4340 // vendor path). 4341 // TODO grab this value from PackageSettings 4342 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4343 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4344 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4345 } 4346 } 4347 4348 // TODO: extend to support forward-locked splits 4349 String resourcePath = null; 4350 String baseResourcePath = null; 4351 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4352 if (ps != null && ps.resourcePathString != null) { 4353 resourcePath = ps.resourcePathString; 4354 baseResourcePath = ps.resourcePathString; 4355 } else { 4356 // Should not happen at all. Just log an error. 4357 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4358 } 4359 } else { 4360 resourcePath = pkg.codePath; 4361 baseResourcePath = pkg.baseCodePath; 4362 } 4363 4364 // Set application objects path explicitly. 4365 pkg.applicationInfo.setCodePath(pkg.codePath); 4366 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4367 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4368 pkg.applicationInfo.setResourcePath(resourcePath); 4369 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4370 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4371 4372 // Note that we invoke the following method only if we are about to unpack an application 4373 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4374 | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride); 4375 4376 /* 4377 * If the system app should be overridden by a previously installed 4378 * data, hide the system app now and let the /data/app scan pick it up 4379 * again. 4380 */ 4381 if (shouldHideSystemApp) { 4382 synchronized (mPackages) { 4383 /* 4384 * We have to grant systems permissions before we hide, because 4385 * grantPermissions will assume the package update is trying to 4386 * expand its permissions. 4387 */ 4388 grantPermissionsLPw(pkg, true); 4389 mSettings.disableSystemPackageLPw(pkg.packageName); 4390 } 4391 } 4392 4393 return scannedPkg; 4394 } 4395 4396 private static String fixProcessName(String defProcessName, 4397 String processName, int uid) { 4398 if (processName == null) { 4399 return defProcessName; 4400 } 4401 return processName; 4402 } 4403 4404 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4405 throws PackageManagerException { 4406 if (pkgSetting.signatures.mSignatures != null) { 4407 // Already existing package. Make sure signatures match 4408 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4409 == PackageManager.SIGNATURE_MATCH; 4410 if (!match) { 4411 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4412 == PackageManager.SIGNATURE_MATCH; 4413 } 4414 if (!match) { 4415 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4416 + pkg.packageName + " signatures do not match the " 4417 + "previously installed version; ignoring!"); 4418 } 4419 } 4420 4421 // Check for shared user signatures 4422 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4423 // Already existing package. Make sure signatures match 4424 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4425 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4426 if (!match) { 4427 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4428 == PackageManager.SIGNATURE_MATCH; 4429 } 4430 if (!match) { 4431 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4432 "Package " + pkg.packageName 4433 + " has no signatures that match those in shared user " 4434 + pkgSetting.sharedUser.name + "; ignoring!"); 4435 } 4436 } 4437 } 4438 4439 /** 4440 * Enforces that only the system UID or root's UID can call a method exposed 4441 * via Binder. 4442 * 4443 * @param message used as message if SecurityException is thrown 4444 * @throws SecurityException if the caller is not system or root 4445 */ 4446 private static final void enforceSystemOrRoot(String message) { 4447 final int uid = Binder.getCallingUid(); 4448 if (uid != Process.SYSTEM_UID && uid != 0) { 4449 throw new SecurityException(message); 4450 } 4451 } 4452 4453 @Override 4454 public void performBootDexOpt() { 4455 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4456 4457 final HashSet<PackageParser.Package> pkgs; 4458 synchronized (mPackages) { 4459 pkgs = mDeferredDexOpt; 4460 mDeferredDexOpt = null; 4461 } 4462 4463 if (pkgs != null) { 4464 // Filter out packages that aren't recently used. 4465 // 4466 // The exception is first boot of a non-eng device, which 4467 // should do a full dexopt. 4468 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4469 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4470 // TODO: add a property to control this? 4471 long dexOptLRUThresholdInMinutes; 4472 if (eng) { 4473 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4474 } else { 4475 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4476 } 4477 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4478 4479 int total = pkgs.size(); 4480 int skipped = 0; 4481 long now = System.currentTimeMillis(); 4482 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4483 PackageParser.Package pkg = i.next(); 4484 long then = pkg.mLastPackageUsageTimeInMills; 4485 if (then + dexOptLRUThresholdInMills < now) { 4486 if (DEBUG_DEXOPT) { 4487 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4488 ((then == 0) ? "never" : new Date(then))); 4489 } 4490 i.remove(); 4491 skipped++; 4492 } 4493 } 4494 if (DEBUG_DEXOPT) { 4495 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4496 } 4497 } 4498 4499 int i = 0; 4500 for (PackageParser.Package pkg : pkgs) { 4501 i++; 4502 if (DEBUG_DEXOPT) { 4503 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4504 + ": " + pkg.packageName); 4505 } 4506 if (!isFirstBoot()) { 4507 try { 4508 ActivityManagerNative.getDefault().showBootMessage( 4509 mContext.getResources().getString( 4510 R.string.android_upgrading_apk, 4511 i, pkgs.size()), true); 4512 } catch (RemoteException e) { 4513 } 4514 } 4515 PackageParser.Package p = pkg; 4516 synchronized (mInstallLock) { 4517 performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */, 4518 true /* include dependencies */); 4519 } 4520 } 4521 } 4522 } 4523 4524 @Override 4525 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4526 return performDexOpt(packageName, instructionSet, true); 4527 } 4528 4529 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4530 if (info.primaryCpuAbi == null) { 4531 return getPreferredInstructionSet(); 4532 } 4533 4534 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4535 } 4536 4537 public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) { 4538 PackageParser.Package p; 4539 final String targetInstructionSet; 4540 synchronized (mPackages) { 4541 p = mPackages.get(packageName); 4542 if (p == null) { 4543 return false; 4544 } 4545 if (updateUsage) { 4546 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4547 } 4548 mPackageUsage.write(false); 4549 4550 targetInstructionSet = instructionSet != null ? instructionSet : 4551 getPrimaryInstructionSet(p.applicationInfo); 4552 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4553 return false; 4554 } 4555 } 4556 4557 synchronized (mInstallLock) { 4558 final String[] instructionSets = new String[] { targetInstructionSet }; 4559 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4560 true /* include dependencies */) == DEX_OPT_PERFORMED; 4561 } 4562 } 4563 4564 public HashSet<String> getPackagesThatNeedDexOpt() { 4565 HashSet<String> pkgs = null; 4566 synchronized (mPackages) { 4567 for (PackageParser.Package p : mPackages.values()) { 4568 if (DEBUG_DEXOPT) { 4569 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4570 } 4571 if (!p.mDexOptPerformed.isEmpty()) { 4572 continue; 4573 } 4574 if (pkgs == null) { 4575 pkgs = new HashSet<String>(); 4576 } 4577 pkgs.add(p.packageName); 4578 } 4579 } 4580 return pkgs; 4581 } 4582 4583 public void shutdown() { 4584 mPackageUsage.write(true); 4585 } 4586 4587 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4588 boolean forceDex, boolean defer, HashSet<String> done) { 4589 for (int i=0; i<libs.size(); i++) { 4590 PackageParser.Package libPkg; 4591 String libName; 4592 synchronized (mPackages) { 4593 libName = libs.get(i); 4594 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4595 if (lib != null && lib.apk != null) { 4596 libPkg = mPackages.get(lib.apk); 4597 } else { 4598 libPkg = null; 4599 } 4600 } 4601 if (libPkg != null && !done.contains(libName)) { 4602 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4603 } 4604 } 4605 } 4606 4607 static final int DEX_OPT_SKIPPED = 0; 4608 static final int DEX_OPT_PERFORMED = 1; 4609 static final int DEX_OPT_DEFERRED = 2; 4610 static final int DEX_OPT_FAILED = -1; 4611 4612 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4613 boolean forceDex, boolean defer, HashSet<String> done) { 4614 final String[] instructionSets = targetInstructionSets != null ? 4615 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4616 4617 if (done != null) { 4618 done.add(pkg.packageName); 4619 if (pkg.usesLibraries != null) { 4620 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4621 } 4622 if (pkg.usesOptionalLibraries != null) { 4623 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4624 } 4625 } 4626 4627 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4628 return DEX_OPT_SKIPPED; 4629 } 4630 4631 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4632 boolean performedDexOpt = false; 4633 // There are three basic cases here: 4634 // 1.) we need to dexopt, either because we are forced or it is needed 4635 // 2.) we are defering a needed dexopt 4636 // 3.) we are skipping an unneeded dexopt 4637 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4638 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4639 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4640 continue; 4641 } 4642 4643 for (String path : paths) { 4644 try { 4645 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4646 // patckage or the one we find does not match the image checksum (i.e. it was 4647 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4648 // odex file and it matches the checksum of the image but not its base address, 4649 // meaning we need to move it. 4650 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4651 pkg.packageName, dexCodeInstructionSet, defer); 4652 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4653 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4654 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet); 4655 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4656 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4657 pkg.packageName, dexCodeInstructionSet); 4658 4659 if (ret < 0) { 4660 // Don't bother running dexopt again if we failed, it will probably 4661 // just result in an error again. Also, don't bother dexopting for other 4662 // paths & ISAs. 4663 return DEX_OPT_FAILED; 4664 } 4665 4666 performedDexOpt = true; 4667 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4668 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4669 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4670 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4671 pkg.packageName, dexCodeInstructionSet); 4672 4673 if (ret < 0) { 4674 // Don't bother running patchoat again if we failed, it will probably 4675 // just result in an error again. Also, don't bother dexopting for other 4676 // paths & ISAs. 4677 return DEX_OPT_FAILED; 4678 } 4679 4680 performedDexOpt = true; 4681 } 4682 4683 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4684 // paths and instruction sets. We'll deal with them all together when we process 4685 // our list of deferred dexopts. 4686 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4687 if (mDeferredDexOpt == null) { 4688 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4689 } 4690 mDeferredDexOpt.add(pkg); 4691 return DEX_OPT_DEFERRED; 4692 } 4693 } catch (FileNotFoundException e) { 4694 Slog.w(TAG, "Apk not found for dexopt: " + path); 4695 return DEX_OPT_FAILED; 4696 } catch (IOException e) { 4697 Slog.w(TAG, "IOException reading apk: " + path, e); 4698 return DEX_OPT_FAILED; 4699 } catch (StaleDexCacheError e) { 4700 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4701 return DEX_OPT_FAILED; 4702 } catch (Exception e) { 4703 Slog.w(TAG, "Exception when doing dexopt : ", e); 4704 return DEX_OPT_FAILED; 4705 } 4706 } 4707 4708 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4709 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4710 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4711 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4712 // it. 4713 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4714 } 4715 4716 // If we've gotten here, we're sure that no error occurred and that we haven't 4717 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4718 // we've skipped all of them because they are up to date. In both cases this 4719 // package doesn't need dexopt any longer. 4720 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4721 } 4722 4723 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4724 if (info.primaryCpuAbi != null) { 4725 if (info.secondaryCpuAbi != null) { 4726 return new String[] { 4727 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4728 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4729 } else { 4730 return new String[] { 4731 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4732 } 4733 } 4734 4735 return new String[] { getPreferredInstructionSet() }; 4736 } 4737 4738 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4739 if (ps.primaryCpuAbiString != null) { 4740 if (ps.secondaryCpuAbiString != null) { 4741 return new String[] { 4742 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4743 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4744 } else { 4745 return new String[] { 4746 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4747 } 4748 } 4749 4750 return new String[] { getPreferredInstructionSet() }; 4751 } 4752 4753 private static String getPreferredInstructionSet() { 4754 if (sPreferredInstructionSet == null) { 4755 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4756 } 4757 4758 return sPreferredInstructionSet; 4759 } 4760 4761 private static List<String> getAllInstructionSets() { 4762 final String[] allAbis = Build.SUPPORTED_ABIS; 4763 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4764 4765 for (String abi : allAbis) { 4766 final String instructionSet = VMRuntime.getInstructionSet(abi); 4767 if (!allInstructionSets.contains(instructionSet)) { 4768 allInstructionSets.add(instructionSet); 4769 } 4770 } 4771 4772 return allInstructionSets; 4773 } 4774 4775 /** 4776 * Returns the instruction set that should be used to compile dex code. In the presence of 4777 * a native bridge this might be different than the one shared libraries use. 4778 */ 4779 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4780 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4781 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4782 } 4783 4784 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4785 HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length); 4786 for (String instructionSet : instructionSets) { 4787 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4788 } 4789 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4790 } 4791 4792 @Override 4793 public void forceDexOpt(String packageName) { 4794 enforceSystemOrRoot("forceDexOpt"); 4795 4796 PackageParser.Package pkg; 4797 synchronized (mPackages) { 4798 pkg = mPackages.get(packageName); 4799 if (pkg == null) { 4800 throw new IllegalArgumentException("Missing package: " + packageName); 4801 } 4802 } 4803 4804 synchronized (mInstallLock) { 4805 final String[] instructionSets = new String[] { 4806 getPrimaryInstructionSet(pkg.applicationInfo) }; 4807 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4808 if (res != DEX_OPT_PERFORMED) { 4809 throw new IllegalStateException("Failed to dexopt: " + res); 4810 } 4811 } 4812 } 4813 4814 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4815 boolean forceDex, boolean defer, boolean inclDependencies) { 4816 HashSet<String> done; 4817 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4818 done = new HashSet<String>(); 4819 done.add(pkg.packageName); 4820 } else { 4821 done = null; 4822 } 4823 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4824 } 4825 4826 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4827 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4828 Slog.w(TAG, "Unable to update from " + oldPkg.name 4829 + " to " + newPkg.packageName 4830 + ": old package not in system partition"); 4831 return false; 4832 } else if (mPackages.get(oldPkg.name) != null) { 4833 Slog.w(TAG, "Unable to update from " + oldPkg.name 4834 + " to " + newPkg.packageName 4835 + ": old package still exists"); 4836 return false; 4837 } 4838 return true; 4839 } 4840 4841 File getDataPathForUser(int userId) { 4842 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4843 } 4844 4845 private File getDataPathForPackage(String packageName, int userId) { 4846 /* 4847 * Until we fully support multiple users, return the directory we 4848 * previously would have. The PackageManagerTests will need to be 4849 * revised when this is changed back.. 4850 */ 4851 if (userId == 0) { 4852 return new File(mAppDataDir, packageName); 4853 } else { 4854 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4855 + File.separator + packageName); 4856 } 4857 } 4858 4859 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4860 int[] users = sUserManager.getUserIds(); 4861 int res = mInstaller.install(packageName, uid, uid, seinfo); 4862 if (res < 0) { 4863 return res; 4864 } 4865 for (int user : users) { 4866 if (user != 0) { 4867 res = mInstaller.createUserData(packageName, 4868 UserHandle.getUid(user, uid), user, seinfo); 4869 if (res < 0) { 4870 return res; 4871 } 4872 } 4873 } 4874 return res; 4875 } 4876 4877 private int removeDataDirsLI(String packageName) { 4878 int[] users = sUserManager.getUserIds(); 4879 int res = 0; 4880 for (int user : users) { 4881 int resInner = mInstaller.remove(packageName, user); 4882 if (resInner < 0) { 4883 res = resInner; 4884 } 4885 } 4886 4887 return res; 4888 } 4889 4890 private int deleteCodeCacheDirsLI(String packageName) { 4891 int[] users = sUserManager.getUserIds(); 4892 int res = 0; 4893 for (int user : users) { 4894 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4895 if (resInner < 0) { 4896 res = resInner; 4897 } 4898 } 4899 return res; 4900 } 4901 4902 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4903 PackageParser.Package changingLib) { 4904 if (file.path != null) { 4905 usesLibraryFiles.add(file.path); 4906 return; 4907 } 4908 PackageParser.Package p = mPackages.get(file.apk); 4909 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4910 // If we are doing this while in the middle of updating a library apk, 4911 // then we need to make sure to use that new apk for determining the 4912 // dependencies here. (We haven't yet finished committing the new apk 4913 // to the package manager state.) 4914 if (p == null || p.packageName.equals(changingLib.packageName)) { 4915 p = changingLib; 4916 } 4917 } 4918 if (p != null) { 4919 usesLibraryFiles.addAll(p.getAllCodePaths()); 4920 } 4921 } 4922 4923 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4924 PackageParser.Package changingLib) throws PackageManagerException { 4925 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4926 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4927 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4928 for (int i=0; i<N; i++) { 4929 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4930 if (file == null) { 4931 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4932 "Package " + pkg.packageName + " requires unavailable shared library " 4933 + pkg.usesLibraries.get(i) + "; failing!"); 4934 } 4935 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4936 } 4937 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4938 for (int i=0; i<N; i++) { 4939 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4940 if (file == null) { 4941 Slog.w(TAG, "Package " + pkg.packageName 4942 + " desires unavailable shared library " 4943 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4944 } else { 4945 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4946 } 4947 } 4948 N = usesLibraryFiles.size(); 4949 if (N > 0) { 4950 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4951 } else { 4952 pkg.usesLibraryFiles = null; 4953 } 4954 } 4955 } 4956 4957 private static boolean hasString(List<String> list, List<String> which) { 4958 if (list == null) { 4959 return false; 4960 } 4961 for (int i=list.size()-1; i>=0; i--) { 4962 for (int j=which.size()-1; j>=0; j--) { 4963 if (which.get(j).equals(list.get(i))) { 4964 return true; 4965 } 4966 } 4967 } 4968 return false; 4969 } 4970 4971 private void updateAllSharedLibrariesLPw() { 4972 for (PackageParser.Package pkg : mPackages.values()) { 4973 try { 4974 updateSharedLibrariesLPw(pkg, null); 4975 } catch (PackageManagerException e) { 4976 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4977 } 4978 } 4979 } 4980 4981 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4982 PackageParser.Package changingPkg) { 4983 ArrayList<PackageParser.Package> res = null; 4984 for (PackageParser.Package pkg : mPackages.values()) { 4985 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4986 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4987 if (res == null) { 4988 res = new ArrayList<PackageParser.Package>(); 4989 } 4990 res.add(pkg); 4991 try { 4992 updateSharedLibrariesLPw(pkg, changingPkg); 4993 } catch (PackageManagerException e) { 4994 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4995 } 4996 } 4997 } 4998 return res; 4999 } 5000 5001 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5002 int scanMode, long currentTime, UserHandle user, String abiOverride) 5003 throws PackageManagerException { 5004 final File scanFile = new File(pkg.codePath); 5005 if (pkg.applicationInfo.getCodePath() == null || 5006 pkg.applicationInfo.getResourcePath() == null) { 5007 // Bail out. The resource and code paths haven't been set. 5008 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5009 "Code and resource paths haven't been set correctly"); 5010 } 5011 5012 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5013 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5014 } 5015 5016 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5017 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5018 } 5019 5020 if (mCustomResolverComponentName != null && 5021 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5022 setUpCustomResolverActivity(pkg); 5023 } 5024 5025 if (pkg.packageName.equals("android")) { 5026 synchronized (mPackages) { 5027 if (mAndroidApplication != null) { 5028 Slog.w(TAG, "*************************************************"); 5029 Slog.w(TAG, "Core android package being redefined. Skipping."); 5030 Slog.w(TAG, " file=" + scanFile); 5031 Slog.w(TAG, "*************************************************"); 5032 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5033 "Core android package being redefined. Skipping."); 5034 } 5035 5036 // Set up information for our fall-back user intent resolution activity. 5037 mPlatformPackage = pkg; 5038 pkg.mVersionCode = mSdkVersion; 5039 mAndroidApplication = pkg.applicationInfo; 5040 5041 if (!mResolverReplaced) { 5042 mResolveActivity.applicationInfo = mAndroidApplication; 5043 mResolveActivity.name = ResolverActivity.class.getName(); 5044 mResolveActivity.packageName = mAndroidApplication.packageName; 5045 mResolveActivity.processName = "system:ui"; 5046 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5047 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5048 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5049 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5050 mResolveActivity.exported = true; 5051 mResolveActivity.enabled = true; 5052 mResolveInfo.activityInfo = mResolveActivity; 5053 mResolveInfo.priority = 0; 5054 mResolveInfo.preferredOrder = 0; 5055 mResolveInfo.match = 0; 5056 mResolveComponentName = new ComponentName( 5057 mAndroidApplication.packageName, mResolveActivity.name); 5058 } 5059 } 5060 } 5061 5062 if (DEBUG_PACKAGE_SCANNING) { 5063 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5064 Log.d(TAG, "Scanning package " + pkg.packageName); 5065 } 5066 5067 if (mPackages.containsKey(pkg.packageName) 5068 || mSharedLibraries.containsKey(pkg.packageName)) { 5069 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5070 "Application package " + pkg.packageName 5071 + " already installed. Skipping duplicate."); 5072 } 5073 5074 // Initialize package source and resource directories 5075 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5076 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5077 5078 SharedUserSetting suid = null; 5079 PackageSetting pkgSetting = null; 5080 5081 if (!isSystemApp(pkg)) { 5082 // Only system apps can use these features. 5083 pkg.mOriginalPackages = null; 5084 pkg.mRealPackage = null; 5085 pkg.mAdoptPermissions = null; 5086 } 5087 5088 // writer 5089 synchronized (mPackages) { 5090 if (pkg.mSharedUserId != null) { 5091 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5092 if (suid == null) { 5093 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5094 "Creating application package " + pkg.packageName 5095 + " for shared user failed"); 5096 } 5097 if (DEBUG_PACKAGE_SCANNING) { 5098 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5099 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5100 + "): packages=" + suid.packages); 5101 } 5102 } 5103 5104 // Check if we are renaming from an original package name. 5105 PackageSetting origPackage = null; 5106 String realName = null; 5107 if (pkg.mOriginalPackages != null) { 5108 // This package may need to be renamed to a previously 5109 // installed name. Let's check on that... 5110 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5111 if (pkg.mOriginalPackages.contains(renamed)) { 5112 // This package had originally been installed as the 5113 // original name, and we have already taken care of 5114 // transitioning to the new one. Just update the new 5115 // one to continue using the old name. 5116 realName = pkg.mRealPackage; 5117 if (!pkg.packageName.equals(renamed)) { 5118 // Callers into this function may have already taken 5119 // care of renaming the package; only do it here if 5120 // it is not already done. 5121 pkg.setPackageName(renamed); 5122 } 5123 5124 } else { 5125 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5126 if ((origPackage = mSettings.peekPackageLPr( 5127 pkg.mOriginalPackages.get(i))) != null) { 5128 // We do have the package already installed under its 5129 // original name... should we use it? 5130 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5131 // New package is not compatible with original. 5132 origPackage = null; 5133 continue; 5134 } else if (origPackage.sharedUser != null) { 5135 // Make sure uid is compatible between packages. 5136 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5137 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5138 + " to " + pkg.packageName + ": old uid " 5139 + origPackage.sharedUser.name 5140 + " differs from " + pkg.mSharedUserId); 5141 origPackage = null; 5142 continue; 5143 } 5144 } else { 5145 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5146 + pkg.packageName + " to old name " + origPackage.name); 5147 } 5148 break; 5149 } 5150 } 5151 } 5152 } 5153 5154 if (mTransferedPackages.contains(pkg.packageName)) { 5155 Slog.w(TAG, "Package " + pkg.packageName 5156 + " was transferred to another, but its .apk remains"); 5157 } 5158 5159 // Just create the setting, don't add it yet. For already existing packages 5160 // the PkgSetting exists already and doesn't have to be created. 5161 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5162 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5163 pkg.applicationInfo.primaryCpuAbi, 5164 pkg.applicationInfo.secondaryCpuAbi, 5165 pkg.applicationInfo.flags, user, false); 5166 if (pkgSetting == null) { 5167 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5168 "Creating application package " + pkg.packageName + " failed"); 5169 } 5170 5171 if (pkgSetting.origPackage != null) { 5172 // If we are first transitioning from an original package, 5173 // fix up the new package's name now. We need to do this after 5174 // looking up the package under its new name, so getPackageLP 5175 // can take care of fiddling things correctly. 5176 pkg.setPackageName(origPackage.name); 5177 5178 // File a report about this. 5179 String msg = "New package " + pkgSetting.realName 5180 + " renamed to replace old package " + pkgSetting.name; 5181 reportSettingsProblem(Log.WARN, msg); 5182 5183 // Make a note of it. 5184 mTransferedPackages.add(origPackage.name); 5185 5186 // No longer need to retain this. 5187 pkgSetting.origPackage = null; 5188 } 5189 5190 if (realName != null) { 5191 // Make a note of it. 5192 mTransferedPackages.add(pkg.packageName); 5193 } 5194 5195 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5196 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5197 } 5198 5199 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5200 // Check all shared libraries and map to their actual file path. 5201 // We only do this here for apps not on a system dir, because those 5202 // are the only ones that can fail an install due to this. We 5203 // will take care of the system apps by updating all of their 5204 // library paths after the scan is done. 5205 updateSharedLibrariesLPw(pkg, null); 5206 } 5207 5208 if (mFoundPolicyFile) { 5209 SELinuxMMAC.assignSeinfoValue(pkg); 5210 } 5211 5212 pkg.applicationInfo.uid = pkgSetting.appId; 5213 pkg.mExtras = pkgSetting; 5214 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5215 try { 5216 verifySignaturesLP(pkgSetting, pkg); 5217 } catch (PackageManagerException e) { 5218 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5219 throw e; 5220 } 5221 // The signature has changed, but this package is in the system 5222 // image... let's recover! 5223 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5224 // However... if this package is part of a shared user, but it 5225 // doesn't match the signature of the shared user, let's fail. 5226 // What this means is that you can't change the signatures 5227 // associated with an overall shared user, which doesn't seem all 5228 // that unreasonable. 5229 if (pkgSetting.sharedUser != null) { 5230 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5231 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5232 throw new PackageManagerException( 5233 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5234 "Signature mismatch for shared user : " 5235 + pkgSetting.sharedUser); 5236 } 5237 } 5238 // File a report about this. 5239 String msg = "System package " + pkg.packageName 5240 + " signature changed; retaining data."; 5241 reportSettingsProblem(Log.WARN, msg); 5242 } 5243 } else { 5244 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5245 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5246 + pkg.packageName + " upgrade keys do not match the " 5247 + "previously installed version"); 5248 } else { 5249 // signatures may have changed as result of upgrade 5250 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5251 } 5252 } 5253 // Verify that this new package doesn't have any content providers 5254 // that conflict with existing packages. Only do this if the 5255 // package isn't already installed, since we don't want to break 5256 // things that are installed. 5257 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5258 final int N = pkg.providers.size(); 5259 int i; 5260 for (i=0; i<N; i++) { 5261 PackageParser.Provider p = pkg.providers.get(i); 5262 if (p.info.authority != null) { 5263 String names[] = p.info.authority.split(";"); 5264 for (int j = 0; j < names.length; j++) { 5265 if (mProvidersByAuthority.containsKey(names[j])) { 5266 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5267 final String otherPackageName = 5268 ((other != null && other.getComponentName() != null) ? 5269 other.getComponentName().getPackageName() : "?"); 5270 throw new PackageManagerException( 5271 INSTALL_FAILED_CONFLICTING_PROVIDER, 5272 "Can't install because provider name " + names[j] 5273 + " (in package " + pkg.applicationInfo.packageName 5274 + ") is already used by " + otherPackageName); 5275 } 5276 } 5277 } 5278 } 5279 } 5280 5281 if (pkg.mAdoptPermissions != null) { 5282 // This package wants to adopt ownership of permissions from 5283 // another package. 5284 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5285 final String origName = pkg.mAdoptPermissions.get(i); 5286 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5287 if (orig != null) { 5288 if (verifyPackageUpdateLPr(orig, pkg)) { 5289 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5290 + pkg.packageName); 5291 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5292 } 5293 } 5294 } 5295 } 5296 } 5297 5298 final String pkgName = pkg.packageName; 5299 5300 final long scanFileTime = scanFile.lastModified(); 5301 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5302 pkg.applicationInfo.processName = fixProcessName( 5303 pkg.applicationInfo.packageName, 5304 pkg.applicationInfo.processName, 5305 pkg.applicationInfo.uid); 5306 5307 File dataPath; 5308 if (mPlatformPackage == pkg) { 5309 // The system package is special. 5310 dataPath = new File (Environment.getDataDirectory(), "system"); 5311 pkg.applicationInfo.dataDir = dataPath.getPath(); 5312 5313 } else { 5314 // This is a normal package, need to make its data directory. 5315 dataPath = getDataPathForPackage(pkg.packageName, 0); 5316 5317 boolean uidError = false; 5318 5319 if (dataPath.exists()) { 5320 int currentUid = 0; 5321 try { 5322 StructStat stat = Os.stat(dataPath.getPath()); 5323 currentUid = stat.st_uid; 5324 } catch (ErrnoException e) { 5325 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5326 } 5327 5328 // If we have mismatched owners for the data path, we have a problem. 5329 if (currentUid != pkg.applicationInfo.uid) { 5330 boolean recovered = false; 5331 if (currentUid == 0) { 5332 // The directory somehow became owned by root. Wow. 5333 // This is probably because the system was stopped while 5334 // installd was in the middle of messing with its libs 5335 // directory. Ask installd to fix that. 5336 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5337 pkg.applicationInfo.uid); 5338 if (ret >= 0) { 5339 recovered = true; 5340 String msg = "Package " + pkg.packageName 5341 + " unexpectedly changed to uid 0; recovered to " + 5342 + pkg.applicationInfo.uid; 5343 reportSettingsProblem(Log.WARN, msg); 5344 } 5345 } 5346 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5347 || (scanMode&SCAN_BOOTING) != 0)) { 5348 // If this is a system app, we can at least delete its 5349 // current data so the application will still work. 5350 int ret = removeDataDirsLI(pkgName); 5351 if (ret >= 0) { 5352 // TODO: Kill the processes first 5353 // Old data gone! 5354 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5355 ? "System package " : "Third party package "; 5356 String msg = prefix + pkg.packageName 5357 + " has changed from uid: " 5358 + currentUid + " to " 5359 + pkg.applicationInfo.uid + "; old data erased"; 5360 reportSettingsProblem(Log.WARN, msg); 5361 recovered = true; 5362 5363 // And now re-install the app. 5364 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5365 pkg.applicationInfo.seinfo); 5366 if (ret == -1) { 5367 // Ack should not happen! 5368 msg = prefix + pkg.packageName 5369 + " could not have data directory re-created after delete."; 5370 reportSettingsProblem(Log.WARN, msg); 5371 throw new PackageManagerException( 5372 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5373 } 5374 } 5375 if (!recovered) { 5376 mHasSystemUidErrors = true; 5377 } 5378 } else if (!recovered) { 5379 // If we allow this install to proceed, we will be broken. 5380 // Abort, abort! 5381 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5382 "scanPackageLI"); 5383 } 5384 if (!recovered) { 5385 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5386 + pkg.applicationInfo.uid + "/fs_" 5387 + currentUid; 5388 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5389 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5390 String msg = "Package " + pkg.packageName 5391 + " has mismatched uid: " 5392 + currentUid + " on disk, " 5393 + pkg.applicationInfo.uid + " in settings"; 5394 // writer 5395 synchronized (mPackages) { 5396 mSettings.mReadMessages.append(msg); 5397 mSettings.mReadMessages.append('\n'); 5398 uidError = true; 5399 if (!pkgSetting.uidError) { 5400 reportSettingsProblem(Log.ERROR, msg); 5401 } 5402 } 5403 } 5404 } 5405 pkg.applicationInfo.dataDir = dataPath.getPath(); 5406 if (mShouldRestoreconData) { 5407 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5408 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5409 pkg.applicationInfo.uid); 5410 } 5411 } else { 5412 if (DEBUG_PACKAGE_SCANNING) { 5413 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5414 Log.v(TAG, "Want this data dir: " + dataPath); 5415 } 5416 //invoke installer to do the actual installation 5417 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5418 pkg.applicationInfo.seinfo); 5419 if (ret < 0) { 5420 // Error from installer 5421 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5422 "Unable to create data dirs [errorCode=" + ret + "]"); 5423 } 5424 5425 if (dataPath.exists()) { 5426 pkg.applicationInfo.dataDir = dataPath.getPath(); 5427 } else { 5428 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5429 pkg.applicationInfo.dataDir = null; 5430 } 5431 } 5432 5433 pkgSetting.uidError = uidError; 5434 } 5435 5436 final String path = scanFile.getPath(); 5437 final String codePath = pkg.applicationInfo.getCodePath(); 5438 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5439 // For the case where we had previously uninstalled an update, get rid 5440 // of any native binaries we might have unpackaged. Note that this assumes 5441 // that system app updates were not installed via ASEC. 5442 // 5443 // TODO(multiArch): Is this cleanup really necessary ? 5444 NativeLibraryHelper.removeNativeBinariesFromDirLI( 5445 new File(codePath, LIB_DIR_NAME), false /* delete dirs */); 5446 setBundledAppAbisAndRoots(pkg, pkgSetting); 5447 5448 // If we haven't found any native libraries for the app, check if it has 5449 // renderscript code. We'll need to force the app to 32 bit if it has 5450 // renderscript bitcode. 5451 if (pkg.applicationInfo.primaryCpuAbi == null 5452 && pkg.applicationInfo.secondaryCpuAbi == null 5453 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5454 NativeLibraryHelper.Handle handle = null; 5455 try { 5456 handle = NativeLibraryHelper.Handle.create(scanFile); 5457 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5458 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5459 } 5460 } catch (IOException ioe) { 5461 Slog.w(TAG, "Error scanning system app : " + ioe); 5462 } finally { 5463 IoUtils.closeQuietly(handle); 5464 } 5465 } 5466 5467 setNativeLibraryPaths(pkg); 5468 } else { 5469 // TODO: We can probably be smarter about this stuff. For installed apps, 5470 // we can calculate this information at install time once and for all. For 5471 // system apps, we can probably assume that this information doesn't change 5472 // after the first boot scan. As things stand, we do lots of unnecessary work. 5473 5474 // Give ourselves some initial paths; we'll come back for another 5475 // pass once we've determined ABI below. 5476 setNativeLibraryPaths(pkg); 5477 5478 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5479 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5480 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5481 5482 NativeLibraryHelper.Handle handle = null; 5483 try { 5484 handle = NativeLibraryHelper.Handle.create(scanFile); 5485 // TODO(multiArch): This can be null for apps that didn't go through the 5486 // usual installation process. We can calculate it again, like we 5487 // do during install time. 5488 // 5489 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5490 // unnecessary. 5491 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5492 5493 // Null out the abis so that they can be recalculated. 5494 pkg.applicationInfo.primaryCpuAbi = null; 5495 pkg.applicationInfo.secondaryCpuAbi = null; 5496 if (isMultiArch(pkg.applicationInfo)) { 5497 // Warn if we've set an abiOverride for multi-lib packages.. 5498 // By definition, we need to copy both 32 and 64 bit libraries for 5499 // such packages. 5500 if (abiOverride != null) { 5501 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5502 } 5503 5504 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5505 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5506 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5507 if (isAsec) { 5508 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5509 } else { 5510 abi32 = copyNativeLibrariesForInternalApp(handle, 5511 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs); 5512 } 5513 } 5514 5515 maybeThrowExceptionForMultiArchCopy( 5516 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5517 5518 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5519 if (isAsec) { 5520 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5521 } else { 5522 abi64 = copyNativeLibrariesForInternalApp(handle, 5523 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs); 5524 } 5525 } 5526 5527 maybeThrowExceptionForMultiArchCopy( 5528 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5529 5530 if (abi64 >= 0) { 5531 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5532 } 5533 5534 if (abi32 >= 0) { 5535 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5536 if (abi64 >= 0) { 5537 pkg.applicationInfo.secondaryCpuAbi = abi; 5538 } else { 5539 pkg.applicationInfo.primaryCpuAbi = abi; 5540 } 5541 } 5542 } else { 5543 String[] abiList = (abiOverride != null) ? 5544 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 5545 5546 // Enable gross and lame hacks for apps that are built with old 5547 // SDK tools. We must scan their APKs for renderscript bitcode and 5548 // not launch them if it's present. Don't bother checking on devices 5549 // that don't have 64 bit support. 5550 boolean needsRenderScriptOverride = false; 5551 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null && 5552 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5553 abiList = Build.SUPPORTED_32_BIT_ABIS; 5554 needsRenderScriptOverride = true; 5555 } 5556 5557 final int copyRet; 5558 if (isAsec) { 5559 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5560 } else { 5561 copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryRoot, abiList, 5562 useIsaSpecificSubdirs); 5563 } 5564 5565 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5566 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5567 "Error unpackaging native libs for app, errorCode=" + copyRet); 5568 } 5569 5570 if (copyRet >= 0) { 5571 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5572 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && abiOverride != null) { 5573 pkg.applicationInfo.primaryCpuAbi = abiOverride; 5574 } else if (needsRenderScriptOverride) { 5575 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5576 } 5577 } 5578 } catch (IOException ioe) { 5579 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5580 } finally { 5581 IoUtils.closeQuietly(handle); 5582 } 5583 5584 // Now that we've calculated the ABIs and determined if it's an internal app, 5585 // we will go ahead and populate the nativeLibraryPath. 5586 setNativeLibraryPaths(pkg); 5587 5588 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5589 final int[] userIds = sUserManager.getUserIds(); 5590 synchronized (mInstallLock) { 5591 // Create a native library symlink only if we have native libraries 5592 // and if the native libraries are 32 bit libraries. We do not provide 5593 // this symlink for 64 bit libraries. 5594 if (pkg.applicationInfo.primaryCpuAbi != null && 5595 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5596 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5597 for (int userId : userIds) { 5598 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5599 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5600 "Failed linking native library dir (user=" + userId + ")"); 5601 } 5602 } 5603 } 5604 } 5605 } 5606 5607 // This is a special case for the "system" package, where the ABI is 5608 // dictated by the zygote configuration (and init.rc). We should keep track 5609 // of this ABI so that we can deal with "normal" applications that run under 5610 // the same UID correctly. 5611 if (mPlatformPackage == pkg) { 5612 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5613 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5614 } 5615 5616 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5617 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5618 5619 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5620 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5621 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5622 5623 // Push the derived path down into PackageSettings so we know what to 5624 // clean up at uninstall time. 5625 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5626 5627 if (DEBUG_ABI_SELECTION) { 5628 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5629 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5630 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5631 } 5632 5633 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5634 // We don't do this here during boot because we can do it all 5635 // at once after scanning all existing packages. 5636 // 5637 // We also do this *before* we perform dexopt on this package, so that 5638 // we can avoid redundant dexopts, and also to make sure we've got the 5639 // code and package path correct. 5640 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5641 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0); 5642 } 5643 5644 if ((scanMode&SCAN_NO_DEX) == 0) { 5645 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5646 == DEX_OPT_FAILED) { 5647 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5648 removeDataDirsLI(pkg.packageName); 5649 } 5650 5651 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5652 } 5653 } 5654 5655 if (mFactoryTest && pkg.requestedPermissions.contains( 5656 android.Manifest.permission.FACTORY_TEST)) { 5657 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5658 } 5659 5660 ArrayList<PackageParser.Package> clientLibPkgs = null; 5661 5662 // writer 5663 synchronized (mPackages) { 5664 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5665 // Only system apps can add new shared libraries. 5666 if (pkg.libraryNames != null) { 5667 for (int i=0; i<pkg.libraryNames.size(); i++) { 5668 String name = pkg.libraryNames.get(i); 5669 boolean allowed = false; 5670 if (isUpdatedSystemApp(pkg)) { 5671 // New library entries can only be added through the 5672 // system image. This is important to get rid of a lot 5673 // of nasty edge cases: for example if we allowed a non- 5674 // system update of the app to add a library, then uninstalling 5675 // the update would make the library go away, and assumptions 5676 // we made such as through app install filtering would now 5677 // have allowed apps on the device which aren't compatible 5678 // with it. Better to just have the restriction here, be 5679 // conservative, and create many fewer cases that can negatively 5680 // impact the user experience. 5681 final PackageSetting sysPs = mSettings 5682 .getDisabledSystemPkgLPr(pkg.packageName); 5683 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5684 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5685 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5686 allowed = true; 5687 allowed = true; 5688 break; 5689 } 5690 } 5691 } 5692 } else { 5693 allowed = true; 5694 } 5695 if (allowed) { 5696 if (!mSharedLibraries.containsKey(name)) { 5697 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5698 } else if (!name.equals(pkg.packageName)) { 5699 Slog.w(TAG, "Package " + pkg.packageName + " library " 5700 + name + " already exists; skipping"); 5701 } 5702 } else { 5703 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5704 + name + " that is not declared on system image; skipping"); 5705 } 5706 } 5707 if ((scanMode&SCAN_BOOTING) == 0) { 5708 // If we are not booting, we need to update any applications 5709 // that are clients of our shared library. If we are booting, 5710 // this will all be done once the scan is complete. 5711 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5712 } 5713 } 5714 } 5715 } 5716 5717 // We also need to dexopt any apps that are dependent on this library. Note that 5718 // if these fail, we should abort the install since installing the library will 5719 // result in some apps being broken. 5720 if (clientLibPkgs != null) { 5721 if ((scanMode&SCAN_NO_DEX) == 0) { 5722 for (int i=0; i<clientLibPkgs.size(); i++) { 5723 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5724 if (performDexOptLI(clientPkg, null /* instruction sets */, 5725 forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5726 == DEX_OPT_FAILED) { 5727 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5728 removeDataDirsLI(pkg.packageName); 5729 } 5730 5731 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5732 "scanPackageLI failed to dexopt clientLibPkgs"); 5733 } 5734 } 5735 } 5736 } 5737 5738 // Request the ActivityManager to kill the process(only for existing packages) 5739 // so that we do not end up in a confused state while the user is still using the older 5740 // version of the application while the new one gets installed. 5741 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5742 // If the package lives in an asec, tell everyone that the container is going 5743 // away so they can clean up any references to its resources (which would prevent 5744 // vold from being able to unmount the asec) 5745 if (isForwardLocked(pkg) || isExternal(pkg)) { 5746 if (DEBUG_INSTALL) { 5747 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5748 } 5749 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5750 final ArrayList<String> pkgList = new ArrayList<String>(1); 5751 pkgList.add(pkg.applicationInfo.packageName); 5752 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5753 } 5754 5755 // Post the request that it be killed now that the going-away broadcast is en route 5756 killApplication(pkg.applicationInfo.packageName, 5757 pkg.applicationInfo.uid, "update pkg"); 5758 } 5759 5760 // Also need to kill any apps that are dependent on the library. 5761 if (clientLibPkgs != null) { 5762 for (int i=0; i<clientLibPkgs.size(); i++) { 5763 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5764 killApplication(clientPkg.applicationInfo.packageName, 5765 clientPkg.applicationInfo.uid, "update lib"); 5766 } 5767 } 5768 5769 // writer 5770 synchronized (mPackages) { 5771 // We don't expect installation to fail beyond this point, 5772 if ((scanMode&SCAN_MONITOR) != 0) { 5773 mAppDirs.put(pkg.codePath, pkg); 5774 } 5775 // Add the new setting to mSettings 5776 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5777 // Add the new setting to mPackages 5778 mPackages.put(pkg.applicationInfo.packageName, pkg); 5779 // Make sure we don't accidentally delete its data. 5780 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5781 while (iter.hasNext()) { 5782 PackageCleanItem item = iter.next(); 5783 if (pkgName.equals(item.packageName)) { 5784 iter.remove(); 5785 } 5786 } 5787 5788 // Take care of first install / last update times. 5789 if (currentTime != 0) { 5790 if (pkgSetting.firstInstallTime == 0) { 5791 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5792 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5793 pkgSetting.lastUpdateTime = currentTime; 5794 } 5795 } else if (pkgSetting.firstInstallTime == 0) { 5796 // We need *something*. Take time time stamp of the file. 5797 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5798 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5799 if (scanFileTime != pkgSetting.timeStamp) { 5800 // A package on the system image has changed; consider this 5801 // to be an update. 5802 pkgSetting.lastUpdateTime = scanFileTime; 5803 } 5804 } 5805 5806 // Add the package's KeySets to the global KeySetManagerService 5807 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5808 try { 5809 // Old KeySetData no longer valid. 5810 ksms.removeAppKeySetDataLPw(pkg.packageName); 5811 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5812 if (pkg.mKeySetMapping != null) { 5813 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5814 pkg.mKeySetMapping.entrySet()) { 5815 if (entry.getValue() != null) { 5816 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5817 entry.getValue(), entry.getKey()); 5818 } 5819 } 5820 if (pkg.mUpgradeKeySets != null) { 5821 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5822 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5823 } 5824 } 5825 } 5826 } catch (NullPointerException e) { 5827 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5828 } catch (IllegalArgumentException e) { 5829 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5830 } 5831 5832 int N = pkg.providers.size(); 5833 StringBuilder r = null; 5834 int i; 5835 for (i=0; i<N; i++) { 5836 PackageParser.Provider p = pkg.providers.get(i); 5837 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5838 p.info.processName, pkg.applicationInfo.uid); 5839 mProviders.addProvider(p); 5840 p.syncable = p.info.isSyncable; 5841 if (p.info.authority != null) { 5842 String names[] = p.info.authority.split(";"); 5843 p.info.authority = null; 5844 for (int j = 0; j < names.length; j++) { 5845 if (j == 1 && p.syncable) { 5846 // We only want the first authority for a provider to possibly be 5847 // syncable, so if we already added this provider using a different 5848 // authority clear the syncable flag. We copy the provider before 5849 // changing it because the mProviders object contains a reference 5850 // to a provider that we don't want to change. 5851 // Only do this for the second authority since the resulting provider 5852 // object can be the same for all future authorities for this provider. 5853 p = new PackageParser.Provider(p); 5854 p.syncable = false; 5855 } 5856 if (!mProvidersByAuthority.containsKey(names[j])) { 5857 mProvidersByAuthority.put(names[j], p); 5858 if (p.info.authority == null) { 5859 p.info.authority = names[j]; 5860 } else { 5861 p.info.authority = p.info.authority + ";" + names[j]; 5862 } 5863 if (DEBUG_PACKAGE_SCANNING) { 5864 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5865 Log.d(TAG, "Registered content provider: " + names[j] 5866 + ", className = " + p.info.name + ", isSyncable = " 5867 + p.info.isSyncable); 5868 } 5869 } else { 5870 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5871 Slog.w(TAG, "Skipping provider name " + names[j] + 5872 " (in package " + pkg.applicationInfo.packageName + 5873 "): name already used by " 5874 + ((other != null && other.getComponentName() != null) 5875 ? other.getComponentName().getPackageName() : "?")); 5876 } 5877 } 5878 } 5879 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5880 if (r == null) { 5881 r = new StringBuilder(256); 5882 } else { 5883 r.append(' '); 5884 } 5885 r.append(p.info.name); 5886 } 5887 } 5888 if (r != null) { 5889 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5890 } 5891 5892 N = pkg.services.size(); 5893 r = null; 5894 for (i=0; i<N; i++) { 5895 PackageParser.Service s = pkg.services.get(i); 5896 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5897 s.info.processName, pkg.applicationInfo.uid); 5898 mServices.addService(s); 5899 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5900 if (r == null) { 5901 r = new StringBuilder(256); 5902 } else { 5903 r.append(' '); 5904 } 5905 r.append(s.info.name); 5906 } 5907 } 5908 if (r != null) { 5909 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5910 } 5911 5912 N = pkg.receivers.size(); 5913 r = null; 5914 for (i=0; i<N; i++) { 5915 PackageParser.Activity a = pkg.receivers.get(i); 5916 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5917 a.info.processName, pkg.applicationInfo.uid); 5918 mReceivers.addActivity(a, "receiver"); 5919 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5920 if (r == null) { 5921 r = new StringBuilder(256); 5922 } else { 5923 r.append(' '); 5924 } 5925 r.append(a.info.name); 5926 } 5927 } 5928 if (r != null) { 5929 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5930 } 5931 5932 N = pkg.activities.size(); 5933 r = null; 5934 for (i=0; i<N; i++) { 5935 PackageParser.Activity a = pkg.activities.get(i); 5936 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5937 a.info.processName, pkg.applicationInfo.uid); 5938 mActivities.addActivity(a, "activity"); 5939 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5940 if (r == null) { 5941 r = new StringBuilder(256); 5942 } else { 5943 r.append(' '); 5944 } 5945 r.append(a.info.name); 5946 } 5947 } 5948 if (r != null) { 5949 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5950 } 5951 5952 N = pkg.permissionGroups.size(); 5953 r = null; 5954 for (i=0; i<N; i++) { 5955 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5956 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5957 if (cur == null) { 5958 mPermissionGroups.put(pg.info.name, pg); 5959 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5960 if (r == null) { 5961 r = new StringBuilder(256); 5962 } else { 5963 r.append(' '); 5964 } 5965 r.append(pg.info.name); 5966 } 5967 } else { 5968 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5969 + pg.info.packageName + " ignored: original from " 5970 + cur.info.packageName); 5971 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5972 if (r == null) { 5973 r = new StringBuilder(256); 5974 } else { 5975 r.append(' '); 5976 } 5977 r.append("DUP:"); 5978 r.append(pg.info.name); 5979 } 5980 } 5981 } 5982 if (r != null) { 5983 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5984 } 5985 5986 N = pkg.permissions.size(); 5987 r = null; 5988 for (i=0; i<N; i++) { 5989 PackageParser.Permission p = pkg.permissions.get(i); 5990 HashMap<String, BasePermission> permissionMap = 5991 p.tree ? mSettings.mPermissionTrees 5992 : mSettings.mPermissions; 5993 p.group = mPermissionGroups.get(p.info.group); 5994 if (p.info.group == null || p.group != null) { 5995 BasePermission bp = permissionMap.get(p.info.name); 5996 if (bp == null) { 5997 bp = new BasePermission(p.info.name, p.info.packageName, 5998 BasePermission.TYPE_NORMAL); 5999 permissionMap.put(p.info.name, bp); 6000 } 6001 if (bp.perm == null) { 6002 if (bp.sourcePackage != null 6003 && !bp.sourcePackage.equals(p.info.packageName)) { 6004 // If this is a permission that was formerly defined by a non-system 6005 // app, but is now defined by a system app (following an upgrade), 6006 // discard the previous declaration and consider the system's to be 6007 // canonical. 6008 if (isSystemApp(p.owner)) { 6009 String msg = "New decl " + p.owner + " of permission " 6010 + p.info.name + " is system"; 6011 reportSettingsProblem(Log.WARN, msg); 6012 bp.sourcePackage = null; 6013 } 6014 } 6015 if (bp.sourcePackage == null 6016 || bp.sourcePackage.equals(p.info.packageName)) { 6017 BasePermission tree = findPermissionTreeLP(p.info.name); 6018 if (tree == null 6019 || tree.sourcePackage.equals(p.info.packageName)) { 6020 bp.packageSetting = pkgSetting; 6021 bp.perm = p; 6022 bp.uid = pkg.applicationInfo.uid; 6023 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6024 if (r == null) { 6025 r = new StringBuilder(256); 6026 } else { 6027 r.append(' '); 6028 } 6029 r.append(p.info.name); 6030 } 6031 } else { 6032 Slog.w(TAG, "Permission " + p.info.name + " from package " 6033 + p.info.packageName + " ignored: base tree " 6034 + tree.name + " is from package " 6035 + tree.sourcePackage); 6036 } 6037 } else { 6038 Slog.w(TAG, "Permission " + p.info.name + " from package " 6039 + p.info.packageName + " ignored: original from " 6040 + bp.sourcePackage); 6041 } 6042 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6043 if (r == null) { 6044 r = new StringBuilder(256); 6045 } else { 6046 r.append(' '); 6047 } 6048 r.append("DUP:"); 6049 r.append(p.info.name); 6050 } 6051 if (bp.perm == p) { 6052 bp.protectionLevel = p.info.protectionLevel; 6053 } 6054 } else { 6055 Slog.w(TAG, "Permission " + p.info.name + " from package " 6056 + p.info.packageName + " ignored: no group " 6057 + p.group); 6058 } 6059 } 6060 if (r != null) { 6061 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6062 } 6063 6064 N = pkg.instrumentation.size(); 6065 r = null; 6066 for (i=0; i<N; i++) { 6067 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6068 a.info.packageName = pkg.applicationInfo.packageName; 6069 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6070 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6071 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6072 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6073 a.info.dataDir = pkg.applicationInfo.dataDir; 6074 6075 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6076 // need other information about the application, like the ABI and what not ? 6077 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6078 mInstrumentation.put(a.getComponentName(), a); 6079 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6080 if (r == null) { 6081 r = new StringBuilder(256); 6082 } else { 6083 r.append(' '); 6084 } 6085 r.append(a.info.name); 6086 } 6087 } 6088 if (r != null) { 6089 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6090 } 6091 6092 if (pkg.protectedBroadcasts != null) { 6093 N = pkg.protectedBroadcasts.size(); 6094 for (i=0; i<N; i++) { 6095 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6096 } 6097 } 6098 6099 pkgSetting.setTimeStamp(scanFileTime); 6100 6101 // Create idmap files for pairs of (packages, overlay packages). 6102 // Note: "android", ie framework-res.apk, is handled by native layers. 6103 if (pkg.mOverlayTarget != null) { 6104 // This is an overlay package. 6105 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6106 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6107 mOverlays.put(pkg.mOverlayTarget, 6108 new HashMap<String, PackageParser.Package>()); 6109 } 6110 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6111 map.put(pkg.packageName, pkg); 6112 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6113 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6114 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6115 "scanPackageLI failed to createIdmap"); 6116 } 6117 } 6118 } else if (mOverlays.containsKey(pkg.packageName) && 6119 !pkg.packageName.equals("android")) { 6120 // This is a regular package, with one or more known overlay packages. 6121 createIdmapsForPackageLI(pkg); 6122 } 6123 } 6124 6125 return pkg; 6126 } 6127 6128 /** 6129 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6130 * i.e, so that all packages can be run inside a single process if required. 6131 * 6132 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6133 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6134 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6135 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6136 * updating a package that belongs to a shared user. 6137 * 6138 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6139 * adds unnecessary complexity. 6140 */ 6141 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6142 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6143 String requiredInstructionSet = null; 6144 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6145 requiredInstructionSet = VMRuntime.getInstructionSet( 6146 scannedPackage.applicationInfo.primaryCpuAbi); 6147 } 6148 6149 PackageSetting requirer = null; 6150 for (PackageSetting ps : packagesForUser) { 6151 // If packagesForUser contains scannedPackage, we skip it. This will happen 6152 // when scannedPackage is an update of an existing package. Without this check, 6153 // we will never be able to change the ABI of any package belonging to a shared 6154 // user, even if it's compatible with other packages. 6155 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6156 if (ps.primaryCpuAbiString == null) { 6157 continue; 6158 } 6159 6160 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6161 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6162 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6163 // this but there's not much we can do. 6164 String errorMessage = "Instruction set mismatch, " 6165 + ((requirer == null) ? "[caller]" : requirer) 6166 + " requires " + requiredInstructionSet + " whereas " + ps 6167 + " requires " + instructionSet; 6168 Slog.w(TAG, errorMessage); 6169 } 6170 6171 if (requiredInstructionSet == null) { 6172 requiredInstructionSet = instructionSet; 6173 requirer = ps; 6174 } 6175 } 6176 } 6177 6178 if (requiredInstructionSet != null) { 6179 String adjustedAbi; 6180 if (requirer != null) { 6181 // requirer != null implies that either scannedPackage was null or that scannedPackage 6182 // did not require an ABI, in which case we have to adjust scannedPackage to match 6183 // the ABI of the set (which is the same as requirer's ABI) 6184 adjustedAbi = requirer.primaryCpuAbiString; 6185 if (scannedPackage != null) { 6186 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6187 } 6188 } else { 6189 // requirer == null implies that we're updating all ABIs in the set to 6190 // match scannedPackage. 6191 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6192 } 6193 6194 for (PackageSetting ps : packagesForUser) { 6195 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6196 if (ps.primaryCpuAbiString != null) { 6197 continue; 6198 } 6199 6200 ps.primaryCpuAbiString = adjustedAbi; 6201 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6202 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6203 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6204 6205 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6206 deferDexOpt, true) == DEX_OPT_FAILED) { 6207 ps.primaryCpuAbiString = null; 6208 ps.pkg.applicationInfo.primaryCpuAbi = null; 6209 return; 6210 } else { 6211 mInstaller.rmdex(ps.codePathString, 6212 getDexCodeInstructionSet(getPreferredInstructionSet())); 6213 } 6214 } 6215 } 6216 } 6217 } 6218 } 6219 6220 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6221 synchronized (mPackages) { 6222 mResolverReplaced = true; 6223 // Set up information for custom user intent resolution activity. 6224 mResolveActivity.applicationInfo = pkg.applicationInfo; 6225 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6226 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6227 mResolveActivity.processName = null; 6228 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6229 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6230 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6231 mResolveActivity.theme = 0; 6232 mResolveActivity.exported = true; 6233 mResolveActivity.enabled = true; 6234 mResolveInfo.activityInfo = mResolveActivity; 6235 mResolveInfo.priority = 0; 6236 mResolveInfo.preferredOrder = 0; 6237 mResolveInfo.match = 0; 6238 mResolveComponentName = mCustomResolverComponentName; 6239 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6240 mResolveComponentName); 6241 } 6242 } 6243 6244 private static String calculateApkRoot(final String codePathString) { 6245 final File codePath = new File(codePathString); 6246 final File codeRoot; 6247 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6248 codeRoot = Environment.getRootDirectory(); 6249 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6250 codeRoot = Environment.getOemDirectory(); 6251 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6252 codeRoot = Environment.getVendorDirectory(); 6253 } else { 6254 // Unrecognized code path; take its top real segment as the apk root: 6255 // e.g. /something/app/blah.apk => /something 6256 try { 6257 File f = codePath.getCanonicalFile(); 6258 File parent = f.getParentFile(); // non-null because codePath is a file 6259 File tmp; 6260 while ((tmp = parent.getParentFile()) != null) { 6261 f = parent; 6262 parent = tmp; 6263 } 6264 codeRoot = f; 6265 Slog.w(TAG, "Unrecognized code path " 6266 + codePath + " - using " + codeRoot); 6267 } catch (IOException e) { 6268 // Can't canonicalize the code path -- shenanigans? 6269 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6270 return Environment.getRootDirectory().getPath(); 6271 } 6272 } 6273 return codeRoot.getPath(); 6274 } 6275 6276 /** 6277 * Derive and set the location of native libraries for the given package, 6278 * which varies depending on where and how the package was installed. 6279 */ 6280 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6281 final ApplicationInfo info = pkg.applicationInfo; 6282 final String codePath = pkg.codePath; 6283 final File codeFile = new File(codePath); 6284 // If "/system/lib64/apkname" exists, assume that is the per-package 6285 // native library directory to use; otherwise use "/system/lib/apkname". 6286 final String apkRoot = calculateApkRoot(info.sourceDir); 6287 6288 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6289 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6290 6291 6292 info.nativeLibraryRootDir = null; 6293 info.nativeLibraryRootRequiresIsa = false; 6294 info.nativeLibraryDir = null; 6295 info.secondaryNativeLibraryDir = null; 6296 6297 if (isApkFile(codeFile)) { 6298 // Monolithic install 6299 if (bundledApp) { 6300 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6301 getPrimaryInstructionSet(info)); 6302 6303 // This is a bundled system app so choose the path based on the ABI. 6304 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6305 // is just the default path. 6306 final String apkName = deriveCodePathName(codePath); 6307 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6308 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6309 apkName).getAbsolutePath(); 6310 6311 if (info.secondaryCpuAbi != null) { 6312 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6313 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6314 secondaryLibDir, apkName).getAbsolutePath(); 6315 } 6316 } else if (asecApp) { 6317 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6318 .getAbsolutePath(); 6319 } else { 6320 final String apkName = deriveCodePathName(codePath); 6321 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6322 .getAbsolutePath(); 6323 } 6324 6325 info.nativeLibraryRootRequiresIsa = false; 6326 info.nativeLibraryDir = info.nativeLibraryRootDir; 6327 } else { 6328 // Cluster install 6329 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6330 info.nativeLibraryRootRequiresIsa = true; 6331 6332 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6333 getPrimaryInstructionSet(info)).getAbsolutePath(); 6334 6335 if (info.secondaryCpuAbi != null) { 6336 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6337 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6338 } 6339 } 6340 } 6341 6342 /** 6343 * Calculate the abis and roots for a bundled app. These can uniquely 6344 * be determined from the contents of the system partition, i.e whether 6345 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6346 * of this information, and instead assume that the system was built 6347 * sensibly. 6348 */ 6349 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6350 PackageSetting pkgSetting) { 6351 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6352 6353 // If "/system/lib64/apkname" exists, assume that is the per-package 6354 // native library directory to use; otherwise use "/system/lib/apkname". 6355 final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6356 setBundledAppAbi(pkg, apkRoot, apkName); 6357 // pkgSetting might be null during rescan following uninstall of updates 6358 // to a bundled app, so accommodate that possibility. The settings in 6359 // that case will be established later from the parsed package. 6360 // 6361 // If the settings aren't null, sync them up with what we've just derived. 6362 // note that apkRoot isn't stored in the package settings. 6363 if (pkgSetting != null) { 6364 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6365 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6366 } 6367 } 6368 6369 /** 6370 * Deduces the ABI of a bundled app and sets the relevant fields on the 6371 * parsed pkg object. 6372 * 6373 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6374 * under which system libraries are installed. 6375 * @param apkName the name of the installed package. 6376 */ 6377 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6378 final File codeFile = new File(pkg.codePath); 6379 6380 final boolean has64BitLibs; 6381 final boolean has32BitLibs; 6382 if (isApkFile(codeFile)) { 6383 // Monolithic install 6384 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6385 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6386 } else { 6387 // Cluster install 6388 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6389 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6390 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6391 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6392 has64BitLibs = (new File(rootDir, isa)).exists(); 6393 } else { 6394 has64BitLibs = false; 6395 } 6396 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6397 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6398 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6399 has32BitLibs = (new File(rootDir, isa)).exists(); 6400 } else { 6401 has32BitLibs = false; 6402 } 6403 } 6404 6405 if (has64BitLibs && !has32BitLibs) { 6406 // The package has 64 bit libs, but not 32 bit libs. Its primary 6407 // ABI should be 64 bit. We can safely assume here that the bundled 6408 // native libraries correspond to the most preferred ABI in the list. 6409 6410 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6411 pkg.applicationInfo.secondaryCpuAbi = null; 6412 } else if (has32BitLibs && !has64BitLibs) { 6413 // The package has 32 bit libs but not 64 bit libs. Its primary 6414 // ABI should be 32 bit. 6415 6416 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6417 pkg.applicationInfo.secondaryCpuAbi = null; 6418 } else if (has32BitLibs && has64BitLibs) { 6419 // The application has both 64 and 32 bit bundled libraries. We check 6420 // here that the app declares multiArch support, and warn if it doesn't. 6421 // 6422 // We will be lenient here and record both ABIs. The primary will be the 6423 // ABI that's higher on the list, i.e, a device that's configured to prefer 6424 // 64 bit apps will see a 64 bit primary ABI, 6425 6426 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6427 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6428 } 6429 6430 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6431 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6432 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6433 } else { 6434 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6435 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6436 } 6437 } else { 6438 pkg.applicationInfo.primaryCpuAbi = null; 6439 pkg.applicationInfo.secondaryCpuAbi = null; 6440 } 6441 } 6442 6443 private static void createNativeLibrarySubdir(File path) throws IOException { 6444 if (!path.isDirectory()) { 6445 path.delete(); 6446 6447 if (!path.mkdir()) { 6448 throw new IOException("Cannot create " + path.getPath()); 6449 } 6450 6451 try { 6452 Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6453 } catch (ErrnoException e) { 6454 throw new IOException("Cannot chmod native library directory " 6455 + path.getPath(), e); 6456 } 6457 } else if (!SELinux.restorecon(path)) { 6458 throw new IOException("Cannot set SELinux context for " + path.getPath()); 6459 } 6460 } 6461 6462 private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle, 6463 final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException { 6464 createNativeLibrarySubdir(nativeLibraryRoot); 6465 6466 /* 6467 * If this is an internal application or our nativeLibraryPath points to 6468 * the app-lib directory, unpack the libraries if necessary. 6469 */ 6470 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6471 if (abi >= 0) { 6472 /* 6473 * If we have a matching instruction set, construct a subdir under the native 6474 * library root that corresponds to this instruction set. 6475 */ 6476 final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]); 6477 final File subDir; 6478 if (useIsaSubdir) { 6479 final File isaSubdir = new File(nativeLibraryRoot, instructionSet); 6480 createNativeLibrarySubdir(isaSubdir); 6481 subDir = isaSubdir; 6482 } else { 6483 subDir = nativeLibraryRoot; 6484 } 6485 6486 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, subDir, abiList[abi]); 6487 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6488 return copyRet; 6489 } 6490 } 6491 6492 return abi; 6493 } 6494 6495 private void killApplication(String pkgName, int appId, String reason) { 6496 // Request the ActivityManager to kill the process(only for existing packages) 6497 // so that we do not end up in a confused state while the user is still using the older 6498 // version of the application while the new one gets installed. 6499 IActivityManager am = ActivityManagerNative.getDefault(); 6500 if (am != null) { 6501 try { 6502 am.killApplicationWithAppId(pkgName, appId, reason); 6503 } catch (RemoteException e) { 6504 } 6505 } 6506 } 6507 6508 void removePackageLI(PackageSetting ps, boolean chatty) { 6509 if (DEBUG_INSTALL) { 6510 if (chatty) 6511 Log.d(TAG, "Removing package " + ps.name); 6512 } 6513 6514 // writer 6515 synchronized (mPackages) { 6516 mPackages.remove(ps.name); 6517 if (ps.codePathString != null) { 6518 mAppDirs.remove(ps.codePathString); 6519 } 6520 6521 final PackageParser.Package pkg = ps.pkg; 6522 if (pkg != null) { 6523 cleanPackageDataStructuresLILPw(pkg, chatty); 6524 } 6525 } 6526 } 6527 6528 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6529 if (DEBUG_INSTALL) { 6530 if (chatty) 6531 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6532 } 6533 6534 // writer 6535 synchronized (mPackages) { 6536 mPackages.remove(pkg.applicationInfo.packageName); 6537 if (pkg.codePath != null) { 6538 mAppDirs.remove(pkg.codePath); 6539 } 6540 cleanPackageDataStructuresLILPw(pkg, chatty); 6541 } 6542 } 6543 6544 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6545 int N = pkg.providers.size(); 6546 StringBuilder r = null; 6547 int i; 6548 for (i=0; i<N; i++) { 6549 PackageParser.Provider p = pkg.providers.get(i); 6550 mProviders.removeProvider(p); 6551 if (p.info.authority == null) { 6552 6553 /* There was another ContentProvider with this authority when 6554 * this app was installed so this authority is null, 6555 * Ignore it as we don't have to unregister the provider. 6556 */ 6557 continue; 6558 } 6559 String names[] = p.info.authority.split(";"); 6560 for (int j = 0; j < names.length; j++) { 6561 if (mProvidersByAuthority.get(names[j]) == p) { 6562 mProvidersByAuthority.remove(names[j]); 6563 if (DEBUG_REMOVE) { 6564 if (chatty) 6565 Log.d(TAG, "Unregistered content provider: " + names[j] 6566 + ", className = " + p.info.name + ", isSyncable = " 6567 + p.info.isSyncable); 6568 } 6569 } 6570 } 6571 if (DEBUG_REMOVE && chatty) { 6572 if (r == null) { 6573 r = new StringBuilder(256); 6574 } else { 6575 r.append(' '); 6576 } 6577 r.append(p.info.name); 6578 } 6579 } 6580 if (r != null) { 6581 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6582 } 6583 6584 N = pkg.services.size(); 6585 r = null; 6586 for (i=0; i<N; i++) { 6587 PackageParser.Service s = pkg.services.get(i); 6588 mServices.removeService(s); 6589 if (chatty) { 6590 if (r == null) { 6591 r = new StringBuilder(256); 6592 } else { 6593 r.append(' '); 6594 } 6595 r.append(s.info.name); 6596 } 6597 } 6598 if (r != null) { 6599 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6600 } 6601 6602 N = pkg.receivers.size(); 6603 r = null; 6604 for (i=0; i<N; i++) { 6605 PackageParser.Activity a = pkg.receivers.get(i); 6606 mReceivers.removeActivity(a, "receiver"); 6607 if (DEBUG_REMOVE && chatty) { 6608 if (r == null) { 6609 r = new StringBuilder(256); 6610 } else { 6611 r.append(' '); 6612 } 6613 r.append(a.info.name); 6614 } 6615 } 6616 if (r != null) { 6617 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6618 } 6619 6620 N = pkg.activities.size(); 6621 r = null; 6622 for (i=0; i<N; i++) { 6623 PackageParser.Activity a = pkg.activities.get(i); 6624 mActivities.removeActivity(a, "activity"); 6625 if (DEBUG_REMOVE && chatty) { 6626 if (r == null) { 6627 r = new StringBuilder(256); 6628 } else { 6629 r.append(' '); 6630 } 6631 r.append(a.info.name); 6632 } 6633 } 6634 if (r != null) { 6635 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6636 } 6637 6638 N = pkg.permissions.size(); 6639 r = null; 6640 for (i=0; i<N; i++) { 6641 PackageParser.Permission p = pkg.permissions.get(i); 6642 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6643 if (bp == null) { 6644 bp = mSettings.mPermissionTrees.get(p.info.name); 6645 } 6646 if (bp != null && bp.perm == p) { 6647 bp.perm = null; 6648 if (DEBUG_REMOVE && chatty) { 6649 if (r == null) { 6650 r = new StringBuilder(256); 6651 } else { 6652 r.append(' '); 6653 } 6654 r.append(p.info.name); 6655 } 6656 } 6657 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6658 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6659 if (appOpPerms != null) { 6660 appOpPerms.remove(pkg.packageName); 6661 } 6662 } 6663 } 6664 if (r != null) { 6665 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6666 } 6667 6668 N = pkg.requestedPermissions.size(); 6669 r = null; 6670 for (i=0; i<N; i++) { 6671 String perm = pkg.requestedPermissions.get(i); 6672 BasePermission bp = mSettings.mPermissions.get(perm); 6673 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6674 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6675 if (appOpPerms != null) { 6676 appOpPerms.remove(pkg.packageName); 6677 if (appOpPerms.isEmpty()) { 6678 mAppOpPermissionPackages.remove(perm); 6679 } 6680 } 6681 } 6682 } 6683 if (r != null) { 6684 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6685 } 6686 6687 N = pkg.instrumentation.size(); 6688 r = null; 6689 for (i=0; i<N; i++) { 6690 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6691 mInstrumentation.remove(a.getComponentName()); 6692 if (DEBUG_REMOVE && chatty) { 6693 if (r == null) { 6694 r = new StringBuilder(256); 6695 } else { 6696 r.append(' '); 6697 } 6698 r.append(a.info.name); 6699 } 6700 } 6701 if (r != null) { 6702 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6703 } 6704 6705 r = null; 6706 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6707 // Only system apps can hold shared libraries. 6708 if (pkg.libraryNames != null) { 6709 for (i=0; i<pkg.libraryNames.size(); i++) { 6710 String name = pkg.libraryNames.get(i); 6711 SharedLibraryEntry cur = mSharedLibraries.get(name); 6712 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6713 mSharedLibraries.remove(name); 6714 if (DEBUG_REMOVE && chatty) { 6715 if (r == null) { 6716 r = new StringBuilder(256); 6717 } else { 6718 r.append(' '); 6719 } 6720 r.append(name); 6721 } 6722 } 6723 } 6724 } 6725 } 6726 if (r != null) { 6727 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6728 } 6729 } 6730 6731 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6732 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6733 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6734 return true; 6735 } 6736 } 6737 return false; 6738 } 6739 6740 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6741 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6742 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6743 6744 private void updatePermissionsLPw(String changingPkg, 6745 PackageParser.Package pkgInfo, int flags) { 6746 // Make sure there are no dangling permission trees. 6747 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6748 while (it.hasNext()) { 6749 final BasePermission bp = it.next(); 6750 if (bp.packageSetting == null) { 6751 // We may not yet have parsed the package, so just see if 6752 // we still know about its settings. 6753 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6754 } 6755 if (bp.packageSetting == null) { 6756 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6757 + " from package " + bp.sourcePackage); 6758 it.remove(); 6759 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6760 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6761 Slog.i(TAG, "Removing old permission tree: " + bp.name 6762 + " from package " + bp.sourcePackage); 6763 flags |= UPDATE_PERMISSIONS_ALL; 6764 it.remove(); 6765 } 6766 } 6767 } 6768 6769 // Make sure all dynamic permissions have been assigned to a package, 6770 // and make sure there are no dangling permissions. 6771 it = mSettings.mPermissions.values().iterator(); 6772 while (it.hasNext()) { 6773 final BasePermission bp = it.next(); 6774 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6775 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6776 + bp.name + " pkg=" + bp.sourcePackage 6777 + " info=" + bp.pendingInfo); 6778 if (bp.packageSetting == null && bp.pendingInfo != null) { 6779 final BasePermission tree = findPermissionTreeLP(bp.name); 6780 if (tree != null && tree.perm != null) { 6781 bp.packageSetting = tree.packageSetting; 6782 bp.perm = new PackageParser.Permission(tree.perm.owner, 6783 new PermissionInfo(bp.pendingInfo)); 6784 bp.perm.info.packageName = tree.perm.info.packageName; 6785 bp.perm.info.name = bp.name; 6786 bp.uid = tree.uid; 6787 } 6788 } 6789 } 6790 if (bp.packageSetting == null) { 6791 // We may not yet have parsed the package, so just see if 6792 // we still know about its settings. 6793 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6794 } 6795 if (bp.packageSetting == null) { 6796 Slog.w(TAG, "Removing dangling permission: " + bp.name 6797 + " from package " + bp.sourcePackage); 6798 it.remove(); 6799 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6800 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6801 Slog.i(TAG, "Removing old permission: " + bp.name 6802 + " from package " + bp.sourcePackage); 6803 flags |= UPDATE_PERMISSIONS_ALL; 6804 it.remove(); 6805 } 6806 } 6807 } 6808 6809 // Now update the permissions for all packages, in particular 6810 // replace the granted permissions of the system packages. 6811 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6812 for (PackageParser.Package pkg : mPackages.values()) { 6813 if (pkg != pkgInfo) { 6814 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6815 } 6816 } 6817 } 6818 6819 if (pkgInfo != null) { 6820 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6821 } 6822 } 6823 6824 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6825 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6826 if (ps == null) { 6827 return; 6828 } 6829 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6830 HashSet<String> origPermissions = gp.grantedPermissions; 6831 boolean changedPermission = false; 6832 6833 if (replace) { 6834 ps.permissionsFixed = false; 6835 if (gp == ps) { 6836 origPermissions = new HashSet<String>(gp.grantedPermissions); 6837 gp.grantedPermissions.clear(); 6838 gp.gids = mGlobalGids; 6839 } 6840 } 6841 6842 if (gp.gids == null) { 6843 gp.gids = mGlobalGids; 6844 } 6845 6846 final int N = pkg.requestedPermissions.size(); 6847 for (int i=0; i<N; i++) { 6848 final String name = pkg.requestedPermissions.get(i); 6849 final boolean required = pkg.requestedPermissionsRequired.get(i); 6850 final BasePermission bp = mSettings.mPermissions.get(name); 6851 if (DEBUG_INSTALL) { 6852 if (gp != ps) { 6853 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6854 } 6855 } 6856 6857 if (bp == null || bp.packageSetting == null) { 6858 Slog.w(TAG, "Unknown permission " + name 6859 + " in package " + pkg.packageName); 6860 continue; 6861 } 6862 6863 final String perm = bp.name; 6864 boolean allowed; 6865 boolean allowedSig = false; 6866 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6867 // Keep track of app op permissions. 6868 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6869 if (pkgs == null) { 6870 pkgs = new ArraySet<>(); 6871 mAppOpPermissionPackages.put(bp.name, pkgs); 6872 } 6873 pkgs.add(pkg.packageName); 6874 } 6875 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6876 if (level == PermissionInfo.PROTECTION_NORMAL 6877 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6878 // We grant a normal or dangerous permission if any of the following 6879 // are true: 6880 // 1) The permission is required 6881 // 2) The permission is optional, but was granted in the past 6882 // 3) The permission is optional, but was requested by an 6883 // app in /system (not /data) 6884 // 6885 // Otherwise, reject the permission. 6886 allowed = (required || origPermissions.contains(perm) 6887 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6888 } else if (bp.packageSetting == null) { 6889 // This permission is invalid; skip it. 6890 allowed = false; 6891 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6892 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6893 if (allowed) { 6894 allowedSig = true; 6895 } 6896 } else { 6897 allowed = false; 6898 } 6899 if (DEBUG_INSTALL) { 6900 if (gp != ps) { 6901 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6902 } 6903 } 6904 if (allowed) { 6905 if (!isSystemApp(ps) && ps.permissionsFixed) { 6906 // If this is an existing, non-system package, then 6907 // we can't add any new permissions to it. 6908 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6909 // Except... if this is a permission that was added 6910 // to the platform (note: need to only do this when 6911 // updating the platform). 6912 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6913 } 6914 } 6915 if (allowed) { 6916 if (!gp.grantedPermissions.contains(perm)) { 6917 changedPermission = true; 6918 gp.grantedPermissions.add(perm); 6919 gp.gids = appendInts(gp.gids, bp.gids); 6920 } else if (!ps.haveGids) { 6921 gp.gids = appendInts(gp.gids, bp.gids); 6922 } 6923 } else { 6924 Slog.w(TAG, "Not granting permission " + perm 6925 + " to package " + pkg.packageName 6926 + " because it was previously installed without"); 6927 } 6928 } else { 6929 if (gp.grantedPermissions.remove(perm)) { 6930 changedPermission = true; 6931 gp.gids = removeInts(gp.gids, bp.gids); 6932 Slog.i(TAG, "Un-granting permission " + perm 6933 + " from package " + pkg.packageName 6934 + " (protectionLevel=" + bp.protectionLevel 6935 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6936 + ")"); 6937 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6938 // Don't print warning for app op permissions, since it is fine for them 6939 // not to be granted, there is a UI for the user to decide. 6940 Slog.w(TAG, "Not granting permission " + perm 6941 + " to package " + pkg.packageName 6942 + " (protectionLevel=" + bp.protectionLevel 6943 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6944 + ")"); 6945 } 6946 } 6947 } 6948 6949 if ((changedPermission || replace) && !ps.permissionsFixed && 6950 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6951 // This is the first that we have heard about this package, so the 6952 // permissions we have now selected are fixed until explicitly 6953 // changed. 6954 ps.permissionsFixed = true; 6955 } 6956 ps.haveGids = true; 6957 } 6958 6959 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6960 boolean allowed = false; 6961 final int NP = PackageParser.NEW_PERMISSIONS.length; 6962 for (int ip=0; ip<NP; ip++) { 6963 final PackageParser.NewPermissionInfo npi 6964 = PackageParser.NEW_PERMISSIONS[ip]; 6965 if (npi.name.equals(perm) 6966 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6967 allowed = true; 6968 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6969 + pkg.packageName); 6970 break; 6971 } 6972 } 6973 return allowed; 6974 } 6975 6976 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6977 BasePermission bp, HashSet<String> origPermissions) { 6978 boolean allowed; 6979 allowed = (compareSignatures( 6980 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6981 == PackageManager.SIGNATURE_MATCH) 6982 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6983 == PackageManager.SIGNATURE_MATCH); 6984 if (!allowed && (bp.protectionLevel 6985 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6986 if (isSystemApp(pkg)) { 6987 // For updated system applications, a system permission 6988 // is granted only if it had been defined by the original application. 6989 if (isUpdatedSystemApp(pkg)) { 6990 final PackageSetting sysPs = mSettings 6991 .getDisabledSystemPkgLPr(pkg.packageName); 6992 final GrantedPermissions origGp = sysPs.sharedUser != null 6993 ? sysPs.sharedUser : sysPs; 6994 6995 if (origGp.grantedPermissions.contains(perm)) { 6996 // If the original was granted this permission, we take 6997 // that grant decision as read and propagate it to the 6998 // update. 6999 allowed = true; 7000 } else { 7001 // The system apk may have been updated with an older 7002 // version of the one on the data partition, but which 7003 // granted a new system permission that it didn't have 7004 // before. In this case we do want to allow the app to 7005 // now get the new permission if the ancestral apk is 7006 // privileged to get it. 7007 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7008 for (int j=0; 7009 j<sysPs.pkg.requestedPermissions.size(); j++) { 7010 if (perm.equals( 7011 sysPs.pkg.requestedPermissions.get(j))) { 7012 allowed = true; 7013 break; 7014 } 7015 } 7016 } 7017 } 7018 } else { 7019 allowed = isPrivilegedApp(pkg); 7020 } 7021 } 7022 } 7023 if (!allowed && (bp.protectionLevel 7024 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7025 // For development permissions, a development permission 7026 // is granted only if it was already granted. 7027 allowed = origPermissions.contains(perm); 7028 } 7029 return allowed; 7030 } 7031 7032 final class ActivityIntentResolver 7033 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7034 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7035 boolean defaultOnly, int userId) { 7036 if (!sUserManager.exists(userId)) return null; 7037 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7038 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7039 } 7040 7041 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7042 int userId) { 7043 if (!sUserManager.exists(userId)) return null; 7044 mFlags = flags; 7045 return super.queryIntent(intent, resolvedType, 7046 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7047 } 7048 7049 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7050 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7051 if (!sUserManager.exists(userId)) return null; 7052 if (packageActivities == null) { 7053 return null; 7054 } 7055 mFlags = flags; 7056 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7057 final int N = packageActivities.size(); 7058 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7059 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7060 7061 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7062 for (int i = 0; i < N; ++i) { 7063 intentFilters = packageActivities.get(i).intents; 7064 if (intentFilters != null && intentFilters.size() > 0) { 7065 PackageParser.ActivityIntentInfo[] array = 7066 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7067 intentFilters.toArray(array); 7068 listCut.add(array); 7069 } 7070 } 7071 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7072 } 7073 7074 public final void addActivity(PackageParser.Activity a, String type) { 7075 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7076 mActivities.put(a.getComponentName(), a); 7077 if (DEBUG_SHOW_INFO) 7078 Log.v( 7079 TAG, " " + type + " " + 7080 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7081 if (DEBUG_SHOW_INFO) 7082 Log.v(TAG, " Class=" + a.info.name); 7083 final int NI = a.intents.size(); 7084 for (int j=0; j<NI; j++) { 7085 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7086 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7087 intent.setPriority(0); 7088 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7089 + a.className + " with priority > 0, forcing to 0"); 7090 } 7091 if (DEBUG_SHOW_INFO) { 7092 Log.v(TAG, " IntentFilter:"); 7093 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7094 } 7095 if (!intent.debugCheck()) { 7096 Log.w(TAG, "==> For Activity " + a.info.name); 7097 } 7098 addFilter(intent); 7099 } 7100 } 7101 7102 public final void removeActivity(PackageParser.Activity a, String type) { 7103 mActivities.remove(a.getComponentName()); 7104 if (DEBUG_SHOW_INFO) { 7105 Log.v(TAG, " " + type + " " 7106 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7107 : a.info.name) + ":"); 7108 Log.v(TAG, " Class=" + a.info.name); 7109 } 7110 final int NI = a.intents.size(); 7111 for (int j=0; j<NI; j++) { 7112 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7113 if (DEBUG_SHOW_INFO) { 7114 Log.v(TAG, " IntentFilter:"); 7115 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7116 } 7117 removeFilter(intent); 7118 } 7119 } 7120 7121 @Override 7122 protected boolean allowFilterResult( 7123 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7124 ActivityInfo filterAi = filter.activity.info; 7125 for (int i=dest.size()-1; i>=0; i--) { 7126 ActivityInfo destAi = dest.get(i).activityInfo; 7127 if (destAi.name == filterAi.name 7128 && destAi.packageName == filterAi.packageName) { 7129 return false; 7130 } 7131 } 7132 return true; 7133 } 7134 7135 @Override 7136 protected ActivityIntentInfo[] newArray(int size) { 7137 return new ActivityIntentInfo[size]; 7138 } 7139 7140 @Override 7141 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7142 if (!sUserManager.exists(userId)) return true; 7143 PackageParser.Package p = filter.activity.owner; 7144 if (p != null) { 7145 PackageSetting ps = (PackageSetting)p.mExtras; 7146 if (ps != null) { 7147 // System apps are never considered stopped for purposes of 7148 // filtering, because there may be no way for the user to 7149 // actually re-launch them. 7150 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7151 && ps.getStopped(userId); 7152 } 7153 } 7154 return false; 7155 } 7156 7157 @Override 7158 protected boolean isPackageForFilter(String packageName, 7159 PackageParser.ActivityIntentInfo info) { 7160 return packageName.equals(info.activity.owner.packageName); 7161 } 7162 7163 @Override 7164 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7165 int match, int userId) { 7166 if (!sUserManager.exists(userId)) return null; 7167 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7168 return null; 7169 } 7170 final PackageParser.Activity activity = info.activity; 7171 if (mSafeMode && (activity.info.applicationInfo.flags 7172 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7173 return null; 7174 } 7175 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7176 if (ps == null) { 7177 return null; 7178 } 7179 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7180 ps.readUserState(userId), userId); 7181 if (ai == null) { 7182 return null; 7183 } 7184 final ResolveInfo res = new ResolveInfo(); 7185 res.activityInfo = ai; 7186 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7187 res.filter = info; 7188 } 7189 res.priority = info.getPriority(); 7190 res.preferredOrder = activity.owner.mPreferredOrder; 7191 //System.out.println("Result: " + res.activityInfo.className + 7192 // " = " + res.priority); 7193 res.match = match; 7194 res.isDefault = info.hasDefault; 7195 res.labelRes = info.labelRes; 7196 res.nonLocalizedLabel = info.nonLocalizedLabel; 7197 if (userNeedsBadging(userId)) { 7198 res.noResourceId = true; 7199 } else { 7200 res.icon = info.icon; 7201 } 7202 res.system = isSystemApp(res.activityInfo.applicationInfo); 7203 return res; 7204 } 7205 7206 @Override 7207 protected void sortResults(List<ResolveInfo> results) { 7208 Collections.sort(results, mResolvePrioritySorter); 7209 } 7210 7211 @Override 7212 protected void dumpFilter(PrintWriter out, String prefix, 7213 PackageParser.ActivityIntentInfo filter) { 7214 out.print(prefix); out.print( 7215 Integer.toHexString(System.identityHashCode(filter.activity))); 7216 out.print(' '); 7217 filter.activity.printComponentShortName(out); 7218 out.print(" filter "); 7219 out.println(Integer.toHexString(System.identityHashCode(filter))); 7220 } 7221 7222// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7223// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7224// final List<ResolveInfo> retList = Lists.newArrayList(); 7225// while (i.hasNext()) { 7226// final ResolveInfo resolveInfo = i.next(); 7227// if (isEnabledLP(resolveInfo.activityInfo)) { 7228// retList.add(resolveInfo); 7229// } 7230// } 7231// return retList; 7232// } 7233 7234 // Keys are String (activity class name), values are Activity. 7235 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7236 = new HashMap<ComponentName, PackageParser.Activity>(); 7237 private int mFlags; 7238 } 7239 7240 private final class ServiceIntentResolver 7241 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7242 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7243 boolean defaultOnly, int userId) { 7244 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7245 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7246 } 7247 7248 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7249 int userId) { 7250 if (!sUserManager.exists(userId)) return null; 7251 mFlags = flags; 7252 return super.queryIntent(intent, resolvedType, 7253 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7254 } 7255 7256 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7257 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7258 if (!sUserManager.exists(userId)) return null; 7259 if (packageServices == null) { 7260 return null; 7261 } 7262 mFlags = flags; 7263 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7264 final int N = packageServices.size(); 7265 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7266 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7267 7268 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7269 for (int i = 0; i < N; ++i) { 7270 intentFilters = packageServices.get(i).intents; 7271 if (intentFilters != null && intentFilters.size() > 0) { 7272 PackageParser.ServiceIntentInfo[] array = 7273 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7274 intentFilters.toArray(array); 7275 listCut.add(array); 7276 } 7277 } 7278 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7279 } 7280 7281 public final void addService(PackageParser.Service s) { 7282 mServices.put(s.getComponentName(), s); 7283 if (DEBUG_SHOW_INFO) { 7284 Log.v(TAG, " " 7285 + (s.info.nonLocalizedLabel != null 7286 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7287 Log.v(TAG, " Class=" + s.info.name); 7288 } 7289 final int NI = s.intents.size(); 7290 int j; 7291 for (j=0; j<NI; j++) { 7292 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7293 if (DEBUG_SHOW_INFO) { 7294 Log.v(TAG, " IntentFilter:"); 7295 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7296 } 7297 if (!intent.debugCheck()) { 7298 Log.w(TAG, "==> For Service " + s.info.name); 7299 } 7300 addFilter(intent); 7301 } 7302 } 7303 7304 public final void removeService(PackageParser.Service s) { 7305 mServices.remove(s.getComponentName()); 7306 if (DEBUG_SHOW_INFO) { 7307 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7308 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7309 Log.v(TAG, " Class=" + s.info.name); 7310 } 7311 final int NI = s.intents.size(); 7312 int j; 7313 for (j=0; j<NI; j++) { 7314 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7315 if (DEBUG_SHOW_INFO) { 7316 Log.v(TAG, " IntentFilter:"); 7317 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7318 } 7319 removeFilter(intent); 7320 } 7321 } 7322 7323 @Override 7324 protected boolean allowFilterResult( 7325 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7326 ServiceInfo filterSi = filter.service.info; 7327 for (int i=dest.size()-1; i>=0; i--) { 7328 ServiceInfo destAi = dest.get(i).serviceInfo; 7329 if (destAi.name == filterSi.name 7330 && destAi.packageName == filterSi.packageName) { 7331 return false; 7332 } 7333 } 7334 return true; 7335 } 7336 7337 @Override 7338 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7339 return new PackageParser.ServiceIntentInfo[size]; 7340 } 7341 7342 @Override 7343 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7344 if (!sUserManager.exists(userId)) return true; 7345 PackageParser.Package p = filter.service.owner; 7346 if (p != null) { 7347 PackageSetting ps = (PackageSetting)p.mExtras; 7348 if (ps != null) { 7349 // System apps are never considered stopped for purposes of 7350 // filtering, because there may be no way for the user to 7351 // actually re-launch them. 7352 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7353 && ps.getStopped(userId); 7354 } 7355 } 7356 return false; 7357 } 7358 7359 @Override 7360 protected boolean isPackageForFilter(String packageName, 7361 PackageParser.ServiceIntentInfo info) { 7362 return packageName.equals(info.service.owner.packageName); 7363 } 7364 7365 @Override 7366 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7367 int match, int userId) { 7368 if (!sUserManager.exists(userId)) return null; 7369 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7370 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7371 return null; 7372 } 7373 final PackageParser.Service service = info.service; 7374 if (mSafeMode && (service.info.applicationInfo.flags 7375 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7376 return null; 7377 } 7378 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7379 if (ps == null) { 7380 return null; 7381 } 7382 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7383 ps.readUserState(userId), userId); 7384 if (si == null) { 7385 return null; 7386 } 7387 final ResolveInfo res = new ResolveInfo(); 7388 res.serviceInfo = si; 7389 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7390 res.filter = filter; 7391 } 7392 res.priority = info.getPriority(); 7393 res.preferredOrder = service.owner.mPreferredOrder; 7394 //System.out.println("Result: " + res.activityInfo.className + 7395 // " = " + res.priority); 7396 res.match = match; 7397 res.isDefault = info.hasDefault; 7398 res.labelRes = info.labelRes; 7399 res.nonLocalizedLabel = info.nonLocalizedLabel; 7400 res.icon = info.icon; 7401 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7402 return res; 7403 } 7404 7405 @Override 7406 protected void sortResults(List<ResolveInfo> results) { 7407 Collections.sort(results, mResolvePrioritySorter); 7408 } 7409 7410 @Override 7411 protected void dumpFilter(PrintWriter out, String prefix, 7412 PackageParser.ServiceIntentInfo filter) { 7413 out.print(prefix); out.print( 7414 Integer.toHexString(System.identityHashCode(filter.service))); 7415 out.print(' '); 7416 filter.service.printComponentShortName(out); 7417 out.print(" filter "); 7418 out.println(Integer.toHexString(System.identityHashCode(filter))); 7419 } 7420 7421// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7422// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7423// final List<ResolveInfo> retList = Lists.newArrayList(); 7424// while (i.hasNext()) { 7425// final ResolveInfo resolveInfo = (ResolveInfo) i; 7426// if (isEnabledLP(resolveInfo.serviceInfo)) { 7427// retList.add(resolveInfo); 7428// } 7429// } 7430// return retList; 7431// } 7432 7433 // Keys are String (activity class name), values are Activity. 7434 private final HashMap<ComponentName, PackageParser.Service> mServices 7435 = new HashMap<ComponentName, PackageParser.Service>(); 7436 private int mFlags; 7437 }; 7438 7439 private final class ProviderIntentResolver 7440 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7441 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7442 boolean defaultOnly, int userId) { 7443 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7444 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7445 } 7446 7447 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7448 int userId) { 7449 if (!sUserManager.exists(userId)) 7450 return null; 7451 mFlags = flags; 7452 return super.queryIntent(intent, resolvedType, 7453 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7454 } 7455 7456 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7457 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7458 if (!sUserManager.exists(userId)) 7459 return null; 7460 if (packageProviders == null) { 7461 return null; 7462 } 7463 mFlags = flags; 7464 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7465 final int N = packageProviders.size(); 7466 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7467 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7468 7469 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7470 for (int i = 0; i < N; ++i) { 7471 intentFilters = packageProviders.get(i).intents; 7472 if (intentFilters != null && intentFilters.size() > 0) { 7473 PackageParser.ProviderIntentInfo[] array = 7474 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7475 intentFilters.toArray(array); 7476 listCut.add(array); 7477 } 7478 } 7479 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7480 } 7481 7482 public final void addProvider(PackageParser.Provider p) { 7483 if (mProviders.containsKey(p.getComponentName())) { 7484 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7485 return; 7486 } 7487 7488 mProviders.put(p.getComponentName(), p); 7489 if (DEBUG_SHOW_INFO) { 7490 Log.v(TAG, " " 7491 + (p.info.nonLocalizedLabel != null 7492 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7493 Log.v(TAG, " Class=" + p.info.name); 7494 } 7495 final int NI = p.intents.size(); 7496 int j; 7497 for (j = 0; j < NI; j++) { 7498 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7499 if (DEBUG_SHOW_INFO) { 7500 Log.v(TAG, " IntentFilter:"); 7501 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7502 } 7503 if (!intent.debugCheck()) { 7504 Log.w(TAG, "==> For Provider " + p.info.name); 7505 } 7506 addFilter(intent); 7507 } 7508 } 7509 7510 public final void removeProvider(PackageParser.Provider p) { 7511 mProviders.remove(p.getComponentName()); 7512 if (DEBUG_SHOW_INFO) { 7513 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7514 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7515 Log.v(TAG, " Class=" + p.info.name); 7516 } 7517 final int NI = p.intents.size(); 7518 int j; 7519 for (j = 0; j < NI; j++) { 7520 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7521 if (DEBUG_SHOW_INFO) { 7522 Log.v(TAG, " IntentFilter:"); 7523 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7524 } 7525 removeFilter(intent); 7526 } 7527 } 7528 7529 @Override 7530 protected boolean allowFilterResult( 7531 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7532 ProviderInfo filterPi = filter.provider.info; 7533 for (int i = dest.size() - 1; i >= 0; i--) { 7534 ProviderInfo destPi = dest.get(i).providerInfo; 7535 if (destPi.name == filterPi.name 7536 && destPi.packageName == filterPi.packageName) { 7537 return false; 7538 } 7539 } 7540 return true; 7541 } 7542 7543 @Override 7544 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7545 return new PackageParser.ProviderIntentInfo[size]; 7546 } 7547 7548 @Override 7549 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7550 if (!sUserManager.exists(userId)) 7551 return true; 7552 PackageParser.Package p = filter.provider.owner; 7553 if (p != null) { 7554 PackageSetting ps = (PackageSetting) p.mExtras; 7555 if (ps != null) { 7556 // System apps are never considered stopped for purposes of 7557 // filtering, because there may be no way for the user to 7558 // actually re-launch them. 7559 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7560 && ps.getStopped(userId); 7561 } 7562 } 7563 return false; 7564 } 7565 7566 @Override 7567 protected boolean isPackageForFilter(String packageName, 7568 PackageParser.ProviderIntentInfo info) { 7569 return packageName.equals(info.provider.owner.packageName); 7570 } 7571 7572 @Override 7573 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7574 int match, int userId) { 7575 if (!sUserManager.exists(userId)) 7576 return null; 7577 final PackageParser.ProviderIntentInfo info = filter; 7578 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7579 return null; 7580 } 7581 final PackageParser.Provider provider = info.provider; 7582 if (mSafeMode && (provider.info.applicationInfo.flags 7583 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7584 return null; 7585 } 7586 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7587 if (ps == null) { 7588 return null; 7589 } 7590 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7591 ps.readUserState(userId), userId); 7592 if (pi == null) { 7593 return null; 7594 } 7595 final ResolveInfo res = new ResolveInfo(); 7596 res.providerInfo = pi; 7597 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7598 res.filter = filter; 7599 } 7600 res.priority = info.getPriority(); 7601 res.preferredOrder = provider.owner.mPreferredOrder; 7602 res.match = match; 7603 res.isDefault = info.hasDefault; 7604 res.labelRes = info.labelRes; 7605 res.nonLocalizedLabel = info.nonLocalizedLabel; 7606 res.icon = info.icon; 7607 res.system = isSystemApp(res.providerInfo.applicationInfo); 7608 return res; 7609 } 7610 7611 @Override 7612 protected void sortResults(List<ResolveInfo> results) { 7613 Collections.sort(results, mResolvePrioritySorter); 7614 } 7615 7616 @Override 7617 protected void dumpFilter(PrintWriter out, String prefix, 7618 PackageParser.ProviderIntentInfo filter) { 7619 out.print(prefix); 7620 out.print( 7621 Integer.toHexString(System.identityHashCode(filter.provider))); 7622 out.print(' '); 7623 filter.provider.printComponentShortName(out); 7624 out.print(" filter "); 7625 out.println(Integer.toHexString(System.identityHashCode(filter))); 7626 } 7627 7628 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7629 = new HashMap<ComponentName, PackageParser.Provider>(); 7630 private int mFlags; 7631 }; 7632 7633 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7634 new Comparator<ResolveInfo>() { 7635 public int compare(ResolveInfo r1, ResolveInfo r2) { 7636 int v1 = r1.priority; 7637 int v2 = r2.priority; 7638 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7639 if (v1 != v2) { 7640 return (v1 > v2) ? -1 : 1; 7641 } 7642 v1 = r1.preferredOrder; 7643 v2 = r2.preferredOrder; 7644 if (v1 != v2) { 7645 return (v1 > v2) ? -1 : 1; 7646 } 7647 if (r1.isDefault != r2.isDefault) { 7648 return r1.isDefault ? -1 : 1; 7649 } 7650 v1 = r1.match; 7651 v2 = r2.match; 7652 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7653 if (v1 != v2) { 7654 return (v1 > v2) ? -1 : 1; 7655 } 7656 if (r1.system != r2.system) { 7657 return r1.system ? -1 : 1; 7658 } 7659 return 0; 7660 } 7661 }; 7662 7663 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7664 new Comparator<ProviderInfo>() { 7665 public int compare(ProviderInfo p1, ProviderInfo p2) { 7666 final int v1 = p1.initOrder; 7667 final int v2 = p2.initOrder; 7668 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7669 } 7670 }; 7671 7672 static final void sendPackageBroadcast(String action, String pkg, 7673 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7674 int[] userIds) { 7675 IActivityManager am = ActivityManagerNative.getDefault(); 7676 if (am != null) { 7677 try { 7678 if (userIds == null) { 7679 userIds = am.getRunningUserIds(); 7680 } 7681 for (int id : userIds) { 7682 final Intent intent = new Intent(action, 7683 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7684 if (extras != null) { 7685 intent.putExtras(extras); 7686 } 7687 if (targetPkg != null) { 7688 intent.setPackage(targetPkg); 7689 } 7690 // Modify the UID when posting to other users 7691 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7692 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7693 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7694 intent.putExtra(Intent.EXTRA_UID, uid); 7695 } 7696 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7697 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7698 if (DEBUG_BROADCASTS) { 7699 RuntimeException here = new RuntimeException("here"); 7700 here.fillInStackTrace(); 7701 Slog.d(TAG, "Sending to user " + id + ": " 7702 + intent.toShortString(false, true, false, false) 7703 + " " + intent.getExtras(), here); 7704 } 7705 am.broadcastIntent(null, intent, null, finishedReceiver, 7706 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7707 finishedReceiver != null, false, id); 7708 } 7709 } catch (RemoteException ex) { 7710 } 7711 } 7712 } 7713 7714 /** 7715 * Check if the external storage media is available. This is true if there 7716 * is a mounted external storage medium or if the external storage is 7717 * emulated. 7718 */ 7719 private boolean isExternalMediaAvailable() { 7720 return mMediaMounted || Environment.isExternalStorageEmulated(); 7721 } 7722 7723 @Override 7724 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7725 // writer 7726 synchronized (mPackages) { 7727 if (!isExternalMediaAvailable()) { 7728 // If the external storage is no longer mounted at this point, 7729 // the caller may not have been able to delete all of this 7730 // packages files and can not delete any more. Bail. 7731 return null; 7732 } 7733 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7734 if (lastPackage != null) { 7735 pkgs.remove(lastPackage); 7736 } 7737 if (pkgs.size() > 0) { 7738 return pkgs.get(0); 7739 } 7740 } 7741 return null; 7742 } 7743 7744 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7745 if (false) { 7746 RuntimeException here = new RuntimeException("here"); 7747 here.fillInStackTrace(); 7748 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7749 + " andCode=" + andCode, here); 7750 } 7751 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7752 userId, andCode ? 1 : 0, packageName)); 7753 } 7754 7755 void startCleaningPackages() { 7756 // reader 7757 synchronized (mPackages) { 7758 if (!isExternalMediaAvailable()) { 7759 return; 7760 } 7761 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7762 return; 7763 } 7764 } 7765 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7766 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7767 IActivityManager am = ActivityManagerNative.getDefault(); 7768 if (am != null) { 7769 try { 7770 am.startService(null, intent, null, UserHandle.USER_OWNER); 7771 } catch (RemoteException e) { 7772 } 7773 } 7774 } 7775 7776 @Override 7777 public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags, 7778 String installerPackageName, VerificationParams verificationParams, 7779 String packageAbiOverride) { 7780 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7781 null); 7782 7783 final File originFile = new File(originPath); 7784 final int uid = Binder.getCallingUid(); 7785 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7786 try { 7787 if (observer != null) { 7788 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7789 } 7790 } catch (RemoteException re) { 7791 } 7792 return; 7793 } 7794 7795 UserHandle user; 7796 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7797 user = UserHandle.ALL; 7798 } else { 7799 user = new UserHandle(UserHandle.getUserId(uid)); 7800 } 7801 7802 final int filteredFlags; 7803 if (uid == Process.SHELL_UID || uid == 0) { 7804 if (DEBUG_INSTALL) { 7805 Slog.v(TAG, "Install from ADB"); 7806 } 7807 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7808 } else { 7809 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7810 } 7811 7812 verificationParams.setInstallerUid(uid); 7813 7814 final Message msg = mHandler.obtainMessage(INIT_COPY); 7815 msg.obj = new InstallParams(originFile, false, observer, filteredFlags, 7816 installerPackageName, verificationParams, user, packageAbiOverride); 7817 mHandler.sendMessage(msg); 7818 } 7819 7820 void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer, 7821 InstallSessionParams params, String installerPackageName, int installerUid, 7822 UserHandle user) { 7823 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7824 params.referrerUri, installerUid, null); 7825 7826 final Message msg = mHandler.obtainMessage(INIT_COPY); 7827 msg.obj = new InstallParams(stageDir, true, observer, params.installFlags, 7828 installerPackageName, verifParams, user, params.abiOverride); 7829 mHandler.sendMessage(msg); 7830 } 7831 7832 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7833 Bundle extras = new Bundle(1); 7834 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7835 7836 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7837 packageName, extras, null, null, new int[] {userId}); 7838 try { 7839 IActivityManager am = ActivityManagerNative.getDefault(); 7840 final boolean isSystem = 7841 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7842 if (isSystem && am.isUserRunning(userId, false)) { 7843 // The just-installed/enabled app is bundled on the system, so presumed 7844 // to be able to run automatically without needing an explicit launch. 7845 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7846 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7847 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7848 .setPackage(packageName); 7849 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7850 android.app.AppOpsManager.OP_NONE, false, false, userId); 7851 } 7852 } catch (RemoteException e) { 7853 // shouldn't happen 7854 Slog.w(TAG, "Unable to bootstrap installed package", e); 7855 } 7856 } 7857 7858 @Override 7859 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7860 int userId) { 7861 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7862 PackageSetting pkgSetting; 7863 final int uid = Binder.getCallingUid(); 7864 if (UserHandle.getUserId(uid) != userId) { 7865 mContext.enforceCallingOrSelfPermission( 7866 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7867 "setApplicationHiddenSetting for user " + userId); 7868 } 7869 7870 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7871 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7872 return false; 7873 } 7874 7875 long callingId = Binder.clearCallingIdentity(); 7876 try { 7877 boolean sendAdded = false; 7878 boolean sendRemoved = false; 7879 // writer 7880 synchronized (mPackages) { 7881 pkgSetting = mSettings.mPackages.get(packageName); 7882 if (pkgSetting == null) { 7883 return false; 7884 } 7885 if (pkgSetting.getHidden(userId) != hidden) { 7886 pkgSetting.setHidden(hidden, userId); 7887 mSettings.writePackageRestrictionsLPr(userId); 7888 if (hidden) { 7889 sendRemoved = true; 7890 } else { 7891 sendAdded = true; 7892 } 7893 } 7894 } 7895 if (sendAdded) { 7896 sendPackageAddedForUser(packageName, pkgSetting, userId); 7897 return true; 7898 } 7899 if (sendRemoved) { 7900 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7901 "hiding pkg"); 7902 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7903 } 7904 } finally { 7905 Binder.restoreCallingIdentity(callingId); 7906 } 7907 return false; 7908 } 7909 7910 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7911 int userId) { 7912 final PackageRemovedInfo info = new PackageRemovedInfo(); 7913 info.removedPackage = packageName; 7914 info.removedUsers = new int[] {userId}; 7915 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7916 info.sendBroadcast(false, false, false); 7917 } 7918 7919 /** 7920 * Returns true if application is not found or there was an error. Otherwise it returns 7921 * the hidden state of the package for the given user. 7922 */ 7923 @Override 7924 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 7925 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7926 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7927 "getApplicationHidden for user " + userId); 7928 PackageSetting pkgSetting; 7929 long callingId = Binder.clearCallingIdentity(); 7930 try { 7931 // writer 7932 synchronized (mPackages) { 7933 pkgSetting = mSettings.mPackages.get(packageName); 7934 if (pkgSetting == null) { 7935 return true; 7936 } 7937 return pkgSetting.getHidden(userId); 7938 } 7939 } finally { 7940 Binder.restoreCallingIdentity(callingId); 7941 } 7942 } 7943 7944 /** 7945 * @hide 7946 */ 7947 @Override 7948 public int installExistingPackageAsUser(String packageName, int userId) { 7949 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7950 null); 7951 PackageSetting pkgSetting; 7952 final int uid = Binder.getCallingUid(); 7953 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7954 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7955 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7956 } 7957 7958 long callingId = Binder.clearCallingIdentity(); 7959 try { 7960 boolean sendAdded = false; 7961 Bundle extras = new Bundle(1); 7962 7963 // writer 7964 synchronized (mPackages) { 7965 pkgSetting = mSettings.mPackages.get(packageName); 7966 if (pkgSetting == null) { 7967 return PackageManager.INSTALL_FAILED_INVALID_URI; 7968 } 7969 if (!pkgSetting.getInstalled(userId)) { 7970 pkgSetting.setInstalled(true, userId); 7971 pkgSetting.setHidden(false, userId); 7972 mSettings.writePackageRestrictionsLPr(userId); 7973 sendAdded = true; 7974 } 7975 } 7976 7977 if (sendAdded) { 7978 sendPackageAddedForUser(packageName, pkgSetting, userId); 7979 } 7980 } finally { 7981 Binder.restoreCallingIdentity(callingId); 7982 } 7983 7984 return PackageManager.INSTALL_SUCCEEDED; 7985 } 7986 7987 boolean isUserRestricted(int userId, String restrictionKey) { 7988 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7989 if (restrictions.getBoolean(restrictionKey, false)) { 7990 Log.w(TAG, "User is restricted: " + restrictionKey); 7991 return true; 7992 } 7993 return false; 7994 } 7995 7996 @Override 7997 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7998 mContext.enforceCallingOrSelfPermission( 7999 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8000 "Only package verification agents can verify applications"); 8001 8002 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8003 final PackageVerificationResponse response = new PackageVerificationResponse( 8004 verificationCode, Binder.getCallingUid()); 8005 msg.arg1 = id; 8006 msg.obj = response; 8007 mHandler.sendMessage(msg); 8008 } 8009 8010 @Override 8011 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8012 long millisecondsToDelay) { 8013 mContext.enforceCallingOrSelfPermission( 8014 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8015 "Only package verification agents can extend verification timeouts"); 8016 8017 final PackageVerificationState state = mPendingVerification.get(id); 8018 final PackageVerificationResponse response = new PackageVerificationResponse( 8019 verificationCodeAtTimeout, Binder.getCallingUid()); 8020 8021 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8022 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8023 } 8024 if (millisecondsToDelay < 0) { 8025 millisecondsToDelay = 0; 8026 } 8027 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8028 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8029 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8030 } 8031 8032 if ((state != null) && !state.timeoutExtended()) { 8033 state.extendTimeout(); 8034 8035 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8036 msg.arg1 = id; 8037 msg.obj = response; 8038 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8039 } 8040 } 8041 8042 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8043 int verificationCode, UserHandle user) { 8044 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8045 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8046 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8047 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8048 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8049 8050 mContext.sendBroadcastAsUser(intent, user, 8051 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8052 } 8053 8054 private ComponentName matchComponentForVerifier(String packageName, 8055 List<ResolveInfo> receivers) { 8056 ActivityInfo targetReceiver = null; 8057 8058 final int NR = receivers.size(); 8059 for (int i = 0; i < NR; i++) { 8060 final ResolveInfo info = receivers.get(i); 8061 if (info.activityInfo == null) { 8062 continue; 8063 } 8064 8065 if (packageName.equals(info.activityInfo.packageName)) { 8066 targetReceiver = info.activityInfo; 8067 break; 8068 } 8069 } 8070 8071 if (targetReceiver == null) { 8072 return null; 8073 } 8074 8075 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8076 } 8077 8078 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8079 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8080 if (pkgInfo.verifiers.length == 0) { 8081 return null; 8082 } 8083 8084 final int N = pkgInfo.verifiers.length; 8085 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8086 for (int i = 0; i < N; i++) { 8087 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8088 8089 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8090 receivers); 8091 if (comp == null) { 8092 continue; 8093 } 8094 8095 final int verifierUid = getUidForVerifier(verifierInfo); 8096 if (verifierUid == -1) { 8097 continue; 8098 } 8099 8100 if (DEBUG_VERIFY) { 8101 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8102 + " with the correct signature"); 8103 } 8104 sufficientVerifiers.add(comp); 8105 verificationState.addSufficientVerifier(verifierUid); 8106 } 8107 8108 return sufficientVerifiers; 8109 } 8110 8111 private int getUidForVerifier(VerifierInfo verifierInfo) { 8112 synchronized (mPackages) { 8113 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8114 if (pkg == null) { 8115 return -1; 8116 } else if (pkg.mSignatures.length != 1) { 8117 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8118 + " has more than one signature; ignoring"); 8119 return -1; 8120 } 8121 8122 /* 8123 * If the public key of the package's signature does not match 8124 * our expected public key, then this is a different package and 8125 * we should skip. 8126 */ 8127 8128 final byte[] expectedPublicKey; 8129 try { 8130 final Signature verifierSig = pkg.mSignatures[0]; 8131 final PublicKey publicKey = verifierSig.getPublicKey(); 8132 expectedPublicKey = publicKey.getEncoded(); 8133 } catch (CertificateException e) { 8134 return -1; 8135 } 8136 8137 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8138 8139 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8140 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8141 + " does not have the expected public key; ignoring"); 8142 return -1; 8143 } 8144 8145 return pkg.applicationInfo.uid; 8146 } 8147 } 8148 8149 @Override 8150 public void finishPackageInstall(int token) { 8151 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8152 8153 if (DEBUG_INSTALL) { 8154 Slog.v(TAG, "BM finishing package install for " + token); 8155 } 8156 8157 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8158 mHandler.sendMessage(msg); 8159 } 8160 8161 /** 8162 * Get the verification agent timeout. 8163 * 8164 * @return verification timeout in milliseconds 8165 */ 8166 private long getVerificationTimeout() { 8167 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8168 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8169 DEFAULT_VERIFICATION_TIMEOUT); 8170 } 8171 8172 /** 8173 * Get the default verification agent response code. 8174 * 8175 * @return default verification response code 8176 */ 8177 private int getDefaultVerificationResponse() { 8178 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8179 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8180 DEFAULT_VERIFICATION_RESPONSE); 8181 } 8182 8183 /** 8184 * Check whether or not package verification has been enabled. 8185 * 8186 * @return true if verification should be performed 8187 */ 8188 private boolean isVerificationEnabled(int userId, int flags) { 8189 if (!DEFAULT_VERIFY_ENABLE) { 8190 return false; 8191 } 8192 8193 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8194 8195 // Check if installing from ADB 8196 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8197 // Do not run verification in a test harness environment 8198 if (ActivityManager.isRunningInTestHarness()) { 8199 return false; 8200 } 8201 if (ensureVerifyAppsEnabled) { 8202 return true; 8203 } 8204 // Check if the developer does not want package verification for ADB installs 8205 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8206 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8207 return false; 8208 } 8209 } 8210 8211 if (ensureVerifyAppsEnabled) { 8212 return true; 8213 } 8214 8215 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8216 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8217 } 8218 8219 /** 8220 * Get the "allow unknown sources" setting. 8221 * 8222 * @return the current "allow unknown sources" setting 8223 */ 8224 private int getUnknownSourcesSettings() { 8225 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8226 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8227 -1); 8228 } 8229 8230 @Override 8231 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8232 final int uid = Binder.getCallingUid(); 8233 // writer 8234 synchronized (mPackages) { 8235 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8236 if (targetPackageSetting == null) { 8237 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8238 } 8239 8240 PackageSetting installerPackageSetting; 8241 if (installerPackageName != null) { 8242 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8243 if (installerPackageSetting == null) { 8244 throw new IllegalArgumentException("Unknown installer package: " 8245 + installerPackageName); 8246 } 8247 } else { 8248 installerPackageSetting = null; 8249 } 8250 8251 Signature[] callerSignature; 8252 Object obj = mSettings.getUserIdLPr(uid); 8253 if (obj != null) { 8254 if (obj instanceof SharedUserSetting) { 8255 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8256 } else if (obj instanceof PackageSetting) { 8257 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8258 } else { 8259 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8260 } 8261 } else { 8262 throw new SecurityException("Unknown calling uid " + uid); 8263 } 8264 8265 // Verify: can't set installerPackageName to a package that is 8266 // not signed with the same cert as the caller. 8267 if (installerPackageSetting != null) { 8268 if (compareSignatures(callerSignature, 8269 installerPackageSetting.signatures.mSignatures) 8270 != PackageManager.SIGNATURE_MATCH) { 8271 throw new SecurityException( 8272 "Caller does not have same cert as new installer package " 8273 + installerPackageName); 8274 } 8275 } 8276 8277 // Verify: if target already has an installer package, it must 8278 // be signed with the same cert as the caller. 8279 if (targetPackageSetting.installerPackageName != null) { 8280 PackageSetting setting = mSettings.mPackages.get( 8281 targetPackageSetting.installerPackageName); 8282 // If the currently set package isn't valid, then it's always 8283 // okay to change it. 8284 if (setting != null) { 8285 if (compareSignatures(callerSignature, 8286 setting.signatures.mSignatures) 8287 != PackageManager.SIGNATURE_MATCH) { 8288 throw new SecurityException( 8289 "Caller does not have same cert as old installer package " 8290 + targetPackageSetting.installerPackageName); 8291 } 8292 } 8293 } 8294 8295 // Okay! 8296 targetPackageSetting.installerPackageName = installerPackageName; 8297 scheduleWriteSettingsLocked(); 8298 } 8299 } 8300 8301 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8302 // Queue up an async operation since the package installation may take a little while. 8303 mHandler.post(new Runnable() { 8304 public void run() { 8305 mHandler.removeCallbacks(this); 8306 // Result object to be returned 8307 PackageInstalledInfo res = new PackageInstalledInfo(); 8308 res.returnCode = currentStatus; 8309 res.uid = -1; 8310 res.pkg = null; 8311 res.removedInfo = new PackageRemovedInfo(); 8312 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8313 args.doPreInstall(res.returnCode); 8314 synchronized (mInstallLock) { 8315 installPackageLI(args, true, res); 8316 } 8317 args.doPostInstall(res.returnCode, res.uid); 8318 } 8319 8320 // A restore should be performed at this point if (a) the install 8321 // succeeded, (b) the operation is not an update, and (c) the new 8322 // package has not opted out of backup participation. 8323 final boolean update = res.removedInfo.removedPackage != null; 8324 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8325 boolean doRestore = !update 8326 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8327 8328 // Set up the post-install work request bookkeeping. This will be used 8329 // and cleaned up by the post-install event handling regardless of whether 8330 // there's a restore pass performed. Token values are >= 1. 8331 int token; 8332 if (mNextInstallToken < 0) mNextInstallToken = 1; 8333 token = mNextInstallToken++; 8334 8335 PostInstallData data = new PostInstallData(args, res); 8336 mRunningInstalls.put(token, data); 8337 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8338 8339 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8340 // Pass responsibility to the Backup Manager. It will perform a 8341 // restore if appropriate, then pass responsibility back to the 8342 // Package Manager to run the post-install observer callbacks 8343 // and broadcasts. 8344 IBackupManager bm = IBackupManager.Stub.asInterface( 8345 ServiceManager.getService(Context.BACKUP_SERVICE)); 8346 if (bm != null) { 8347 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8348 + " to BM for possible restore"); 8349 try { 8350 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8351 } catch (RemoteException e) { 8352 // can't happen; the backup manager is local 8353 } catch (Exception e) { 8354 Slog.e(TAG, "Exception trying to enqueue restore", e); 8355 doRestore = false; 8356 } 8357 } else { 8358 Slog.e(TAG, "Backup Manager not found!"); 8359 doRestore = false; 8360 } 8361 } 8362 8363 if (!doRestore) { 8364 // No restore possible, or the Backup Manager was mysteriously not 8365 // available -- just fire the post-install work request directly. 8366 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8367 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8368 mHandler.sendMessage(msg); 8369 } 8370 } 8371 }); 8372 } 8373 8374 private abstract class HandlerParams { 8375 private static final int MAX_RETRIES = 4; 8376 8377 /** 8378 * Number of times startCopy() has been attempted and had a non-fatal 8379 * error. 8380 */ 8381 private int mRetries = 0; 8382 8383 /** User handle for the user requesting the information or installation. */ 8384 private final UserHandle mUser; 8385 8386 HandlerParams(UserHandle user) { 8387 mUser = user; 8388 } 8389 8390 UserHandle getUser() { 8391 return mUser; 8392 } 8393 8394 final boolean startCopy() { 8395 boolean res; 8396 try { 8397 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8398 8399 if (++mRetries > MAX_RETRIES) { 8400 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8401 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8402 handleServiceError(); 8403 return false; 8404 } else { 8405 handleStartCopy(); 8406 res = true; 8407 } 8408 } catch (RemoteException e) { 8409 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8410 mHandler.sendEmptyMessage(MCS_RECONNECT); 8411 res = false; 8412 } 8413 handleReturnCode(); 8414 return res; 8415 } 8416 8417 final void serviceError() { 8418 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8419 handleServiceError(); 8420 handleReturnCode(); 8421 } 8422 8423 abstract void handleStartCopy() throws RemoteException; 8424 abstract void handleServiceError(); 8425 abstract void handleReturnCode(); 8426 } 8427 8428 class MeasureParams extends HandlerParams { 8429 private final PackageStats mStats; 8430 private boolean mSuccess; 8431 8432 private final IPackageStatsObserver mObserver; 8433 8434 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8435 super(new UserHandle(stats.userHandle)); 8436 mObserver = observer; 8437 mStats = stats; 8438 } 8439 8440 @Override 8441 public String toString() { 8442 return "MeasureParams{" 8443 + Integer.toHexString(System.identityHashCode(this)) 8444 + " " + mStats.packageName + "}"; 8445 } 8446 8447 @Override 8448 void handleStartCopy() throws RemoteException { 8449 synchronized (mInstallLock) { 8450 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8451 } 8452 8453 if (mSuccess) { 8454 final boolean mounted; 8455 if (Environment.isExternalStorageEmulated()) { 8456 mounted = true; 8457 } else { 8458 final String status = Environment.getExternalStorageState(); 8459 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8460 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8461 } 8462 8463 if (mounted) { 8464 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8465 8466 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8467 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8468 8469 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8470 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8471 8472 // Always subtract cache size, since it's a subdirectory 8473 mStats.externalDataSize -= mStats.externalCacheSize; 8474 8475 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8476 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8477 8478 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8479 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8480 } 8481 } 8482 } 8483 8484 @Override 8485 void handleReturnCode() { 8486 if (mObserver != null) { 8487 try { 8488 mObserver.onGetStatsCompleted(mStats, mSuccess); 8489 } catch (RemoteException e) { 8490 Slog.i(TAG, "Observer no longer exists."); 8491 } 8492 } 8493 } 8494 8495 @Override 8496 void handleServiceError() { 8497 Slog.e(TAG, "Could not measure application " + mStats.packageName 8498 + " external storage"); 8499 } 8500 } 8501 8502 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8503 throws RemoteException { 8504 long result = 0; 8505 for (File path : paths) { 8506 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8507 } 8508 return result; 8509 } 8510 8511 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8512 for (File path : paths) { 8513 try { 8514 mcs.clearDirectory(path.getAbsolutePath()); 8515 } catch (RemoteException e) { 8516 } 8517 } 8518 } 8519 8520 class InstallParams extends HandlerParams { 8521 /** 8522 * Location where install is coming from, before it has been 8523 * copied/renamed into place. This could be a single monolithic APK 8524 * file, or a cluster directory. This location may be untrusted. 8525 */ 8526 final File originFile; 8527 8528 /** 8529 * Flag indicating that {@link #originFile} has already been staged, 8530 * meaning downstream users don't need to defensively copy the contents. 8531 */ 8532 boolean originStaged; 8533 8534 final IPackageInstallObserver2 observer; 8535 int flags; 8536 final String installerPackageName; 8537 final VerificationParams verificationParams; 8538 private InstallArgs mArgs; 8539 private int mRet; 8540 final String packageAbiOverride; 8541 boolean multiArch; 8542 8543 InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 8544 int flags, String installerPackageName, VerificationParams verificationParams, 8545 UserHandle user, String packageAbiOverride) { 8546 super(user); 8547 this.originFile = Preconditions.checkNotNull(originFile); 8548 this.originStaged = originStaged; 8549 this.observer = observer; 8550 this.flags = flags; 8551 this.installerPackageName = installerPackageName; 8552 this.verificationParams = verificationParams; 8553 this.packageAbiOverride = packageAbiOverride; 8554 } 8555 8556 @Override 8557 public String toString() { 8558 return "InstallParams{" 8559 + Integer.toHexString(System.identityHashCode(this)) 8560 + " " + originFile + "}"; 8561 } 8562 8563 public ManifestDigest getManifestDigest() { 8564 if (verificationParams == null) { 8565 return null; 8566 } 8567 return verificationParams.getManifestDigest(); 8568 } 8569 8570 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8571 String packageName = pkgLite.packageName; 8572 int installLocation = pkgLite.installLocation; 8573 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8574 // reader 8575 synchronized (mPackages) { 8576 PackageParser.Package pkg = mPackages.get(packageName); 8577 if (pkg != null) { 8578 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8579 // Check for downgrading. 8580 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8581 if (pkgLite.versionCode < pkg.mVersionCode) { 8582 Slog.w(TAG, "Can't install update of " + packageName 8583 + " update version " + pkgLite.versionCode 8584 + " is older than installed version " 8585 + pkg.mVersionCode); 8586 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8587 } 8588 } 8589 // Check for updated system application. 8590 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8591 if (onSd) { 8592 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8593 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8594 } 8595 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8596 } else { 8597 if (onSd) { 8598 // Install flag overrides everything. 8599 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8600 } 8601 // If current upgrade specifies particular preference 8602 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8603 // Application explicitly specified internal. 8604 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8605 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8606 // App explictly prefers external. Let policy decide 8607 } else { 8608 // Prefer previous location 8609 if (isExternal(pkg)) { 8610 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8611 } 8612 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8613 } 8614 } 8615 } else { 8616 // Invalid install. Return error code 8617 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8618 } 8619 } 8620 } 8621 // All the special cases have been taken care of. 8622 // Return result based on recommended install location. 8623 if (onSd) { 8624 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8625 } 8626 return pkgLite.recommendedInstallLocation; 8627 } 8628 8629 private long getMemoryLowThreshold() { 8630 final DeviceStorageMonitorInternal 8631 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8632 if (dsm == null) { 8633 return 0L; 8634 } 8635 return dsm.getMemoryLowThreshold(); 8636 } 8637 8638 /* 8639 * Invoke remote method to get package information and install 8640 * location values. Override install location based on default 8641 * policy if needed and then create install arguments based 8642 * on the install location. 8643 */ 8644 public void handleStartCopy() throws RemoteException { 8645 int ret = PackageManager.INSTALL_SUCCEEDED; 8646 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8647 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8648 PackageInfoLite pkgLite = null; 8649 8650 if (onInt && onSd) { 8651 // Check if both bits are set. 8652 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8653 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8654 } else { 8655 final long lowThreshold = getMemoryLowThreshold(); 8656 if (lowThreshold == 0L) { 8657 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8658 } 8659 8660 // Remote call to find out default install location 8661 final String originPath = originFile.getAbsolutePath(); 8662 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold, 8663 packageAbiOverride); 8664 // Keep track of whether this package is a multiArch package until 8665 // we perform a full scan of it. We need to do this because we might 8666 // end up extracting the package shared libraries before we perform 8667 // a full scan. 8668 multiArch = pkgLite.multiArch; 8669 8670 /* 8671 * If we have too little free space, try to free cache 8672 * before giving up. 8673 */ 8674 if (pkgLite.recommendedInstallLocation 8675 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8676 final long size = mContainerService.calculateInstalledSize( 8677 originPath, isForwardLocked(), packageAbiOverride); 8678 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8679 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, 8680 lowThreshold, packageAbiOverride); 8681 } 8682 /* 8683 * The cache free must have deleted the file we 8684 * downloaded to install. 8685 * 8686 * TODO: fix the "freeCache" call to not delete 8687 * the file we care about. 8688 */ 8689 if (pkgLite.recommendedInstallLocation 8690 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8691 pkgLite.recommendedInstallLocation 8692 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8693 } 8694 } 8695 } 8696 8697 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8698 int loc = pkgLite.recommendedInstallLocation; 8699 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8700 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8701 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8702 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8703 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8704 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8705 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8706 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8707 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8708 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8709 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8710 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8711 } else { 8712 // Override with defaults if needed. 8713 loc = installLocationPolicy(pkgLite, flags); 8714 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8715 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8716 } else if (!onSd && !onInt) { 8717 // Override install location with flags 8718 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8719 // Set the flag to install on external media. 8720 flags |= PackageManager.INSTALL_EXTERNAL; 8721 flags &= ~PackageManager.INSTALL_INTERNAL; 8722 } else { 8723 // Make sure the flag for installing on external 8724 // media is unset 8725 flags |= PackageManager.INSTALL_INTERNAL; 8726 flags &= ~PackageManager.INSTALL_EXTERNAL; 8727 } 8728 } 8729 } 8730 } 8731 8732 final InstallArgs args = createInstallArgs(this); 8733 mArgs = args; 8734 8735 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8736 /* 8737 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8738 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8739 */ 8740 int userIdentifier = getUser().getIdentifier(); 8741 if (userIdentifier == UserHandle.USER_ALL 8742 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8743 userIdentifier = UserHandle.USER_OWNER; 8744 } 8745 8746 /* 8747 * Determine if we have any installed package verifiers. If we 8748 * do, then we'll defer to them to verify the packages. 8749 */ 8750 final int requiredUid = mRequiredVerifierPackage == null ? -1 8751 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8752 if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) { 8753 // TODO: send verifier the install session instead of uri 8754 final Intent verification = new Intent( 8755 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8756 verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE); 8757 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8758 8759 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8760 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8761 0 /* TODO: Which userId? */); 8762 8763 if (DEBUG_VERIFY) { 8764 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8765 + verification.toString() + " with " + pkgLite.verifiers.length 8766 + " optional verifiers"); 8767 } 8768 8769 final int verificationId = mPendingVerificationToken++; 8770 8771 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8772 8773 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8774 installerPackageName); 8775 8776 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8777 8778 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8779 pkgLite.packageName); 8780 8781 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8782 pkgLite.versionCode); 8783 8784 if (verificationParams != null) { 8785 if (verificationParams.getVerificationURI() != null) { 8786 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8787 verificationParams.getVerificationURI()); 8788 } 8789 if (verificationParams.getOriginatingURI() != null) { 8790 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8791 verificationParams.getOriginatingURI()); 8792 } 8793 if (verificationParams.getReferrer() != null) { 8794 verification.putExtra(Intent.EXTRA_REFERRER, 8795 verificationParams.getReferrer()); 8796 } 8797 if (verificationParams.getOriginatingUid() >= 0) { 8798 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8799 verificationParams.getOriginatingUid()); 8800 } 8801 if (verificationParams.getInstallerUid() >= 0) { 8802 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8803 verificationParams.getInstallerUid()); 8804 } 8805 } 8806 8807 final PackageVerificationState verificationState = new PackageVerificationState( 8808 requiredUid, args); 8809 8810 mPendingVerification.append(verificationId, verificationState); 8811 8812 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8813 receivers, verificationState); 8814 8815 /* 8816 * If any sufficient verifiers were listed in the package 8817 * manifest, attempt to ask them. 8818 */ 8819 if (sufficientVerifiers != null) { 8820 final int N = sufficientVerifiers.size(); 8821 if (N == 0) { 8822 Slog.i(TAG, "Additional verifiers required, but none installed."); 8823 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8824 } else { 8825 for (int i = 0; i < N; i++) { 8826 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8827 8828 final Intent sufficientIntent = new Intent(verification); 8829 sufficientIntent.setComponent(verifierComponent); 8830 8831 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8832 } 8833 } 8834 } 8835 8836 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8837 mRequiredVerifierPackage, receivers); 8838 if (ret == PackageManager.INSTALL_SUCCEEDED 8839 && mRequiredVerifierPackage != null) { 8840 /* 8841 * Send the intent to the required verification agent, 8842 * but only start the verification timeout after the 8843 * target BroadcastReceivers have run. 8844 */ 8845 verification.setComponent(requiredVerifierComponent); 8846 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8847 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8848 new BroadcastReceiver() { 8849 @Override 8850 public void onReceive(Context context, Intent intent) { 8851 final Message msg = mHandler 8852 .obtainMessage(CHECK_PENDING_VERIFICATION); 8853 msg.arg1 = verificationId; 8854 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8855 } 8856 }, null, 0, null, null); 8857 8858 /* 8859 * We don't want the copy to proceed until verification 8860 * succeeds, so null out this field. 8861 */ 8862 mArgs = null; 8863 } 8864 } else { 8865 /* 8866 * No package verification is enabled, so immediately start 8867 * the remote call to initiate copy using temporary file. 8868 */ 8869 ret = args.copyApk(mContainerService, true); 8870 } 8871 } 8872 8873 mRet = ret; 8874 } 8875 8876 @Override 8877 void handleReturnCode() { 8878 // If mArgs is null, then MCS couldn't be reached. When it 8879 // reconnects, it will try again to install. At that point, this 8880 // will succeed. 8881 if (mArgs != null) { 8882 processPendingInstall(mArgs, mRet); 8883 } 8884 } 8885 8886 @Override 8887 void handleServiceError() { 8888 mArgs = createInstallArgs(this); 8889 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8890 } 8891 8892 public boolean isForwardLocked() { 8893 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8894 } 8895 } 8896 8897 /* 8898 * Utility class used in movePackage api. 8899 * srcArgs and targetArgs are not set for invalid flags and make 8900 * sure to do null checks when invoking methods on them. 8901 * We probably want to return ErrorPrams for both failed installs 8902 * and moves. 8903 */ 8904 class MoveParams extends HandlerParams { 8905 final IPackageMoveObserver observer; 8906 final int flags; 8907 final String packageName; 8908 final InstallArgs srcArgs; 8909 final InstallArgs targetArgs; 8910 int uid; 8911 int mRet; 8912 8913 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8914 String packageName, String[] instructionSets, int uid, UserHandle user, 8915 boolean isMultiArch) { 8916 super(user); 8917 this.srcArgs = srcArgs; 8918 this.observer = observer; 8919 this.flags = flags; 8920 this.packageName = packageName; 8921 this.uid = uid; 8922 if (srcArgs != null) { 8923 final String codePath = srcArgs.getCodePath(); 8924 targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, 8925 instructionSets, isMultiArch); 8926 } else { 8927 targetArgs = null; 8928 } 8929 } 8930 8931 @Override 8932 public String toString() { 8933 return "MoveParams{" 8934 + Integer.toHexString(System.identityHashCode(this)) 8935 + " " + packageName + "}"; 8936 } 8937 8938 public void handleStartCopy() throws RemoteException { 8939 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8940 // Check for storage space on target medium 8941 if (!targetArgs.checkFreeStorage(mContainerService)) { 8942 Log.w(TAG, "Insufficient storage to install"); 8943 return; 8944 } 8945 8946 mRet = srcArgs.doPreCopy(); 8947 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8948 return; 8949 } 8950 8951 mRet = targetArgs.copyApk(mContainerService, false); 8952 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8953 srcArgs.doPostCopy(uid); 8954 return; 8955 } 8956 8957 mRet = srcArgs.doPostCopy(uid); 8958 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8959 return; 8960 } 8961 8962 mRet = targetArgs.doPreInstall(mRet); 8963 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8964 return; 8965 } 8966 8967 if (DEBUG_SD_INSTALL) { 8968 StringBuilder builder = new StringBuilder(); 8969 if (srcArgs != null) { 8970 builder.append("src: "); 8971 builder.append(srcArgs.getCodePath()); 8972 } 8973 if (targetArgs != null) { 8974 builder.append(" target : "); 8975 builder.append(targetArgs.getCodePath()); 8976 } 8977 Log.i(TAG, builder.toString()); 8978 } 8979 } 8980 8981 @Override 8982 void handleReturnCode() { 8983 targetArgs.doPostInstall(mRet, uid); 8984 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8985 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8986 currentStatus = PackageManager.MOVE_SUCCEEDED; 8987 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8988 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8989 } 8990 processPendingMove(this, currentStatus); 8991 } 8992 8993 @Override 8994 void handleServiceError() { 8995 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8996 } 8997 } 8998 8999 /** 9000 * Used during creation of InstallArgs 9001 * 9002 * @param flags package installation flags 9003 * @return true if should be installed on external storage 9004 */ 9005 private static boolean installOnSd(int flags) { 9006 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 9007 return false; 9008 } 9009 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 9010 return true; 9011 } 9012 return false; 9013 } 9014 9015 /** 9016 * Used during creation of InstallArgs 9017 * 9018 * @param flags package installation flags 9019 * @return true if should be installed as forward locked 9020 */ 9021 private static boolean installForwardLocked(int flags) { 9022 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9023 } 9024 9025 private InstallArgs createInstallArgs(InstallParams params) { 9026 // TODO: extend to support incoming zero-copy locations 9027 9028 if (installOnSd(params.flags) || params.isForwardLocked()) { 9029 return new AsecInstallArgs(params); 9030 } else { 9031 return new FileInstallArgs(params); 9032 } 9033 } 9034 9035 /** 9036 * Create args that describe an existing installed package. Typically used 9037 * when cleaning up old installs, or used as a move source. 9038 */ 9039 private InstallArgs createInstallArgsForExisting(int flags, String codePath, 9040 String resourcePath, String nativeLibraryRoot, String[] instructionSets, 9041 boolean isMultiArch) { 9042 final boolean isInAsec; 9043 if (installOnSd(flags)) { 9044 /* Apps on SD card are always in ASEC containers. */ 9045 isInAsec = true; 9046 } else if (installForwardLocked(flags) 9047 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9048 /* 9049 * Forward-locked apps are only in ASEC containers if they're the 9050 * new style 9051 */ 9052 isInAsec = true; 9053 } else { 9054 isInAsec = false; 9055 } 9056 9057 if (isInAsec) { 9058 return new AsecInstallArgs(codePath, instructionSets, 9059 installOnSd(flags), installForwardLocked(flags), isMultiArch); 9060 } else { 9061 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9062 instructionSets, isMultiArch); 9063 } 9064 } 9065 9066 private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName, 9067 String[] instructionSets, boolean isMultiArch) { 9068 final File codeFile = new File(codePath); 9069 if (installOnSd(flags) || installForwardLocked(flags)) { 9070 String cid = getNextCodePath(codePath, pkgName, "/" 9071 + AsecInstallArgs.RES_FILE_NAME); 9072 return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags), 9073 installForwardLocked(flags), isMultiArch); 9074 } else { 9075 return new FileInstallArgs(codeFile, instructionSets, isMultiArch); 9076 } 9077 } 9078 9079 static abstract class InstallArgs { 9080 /** @see InstallParams#originFile */ 9081 final File originFile; 9082 /** @see InstallParams#originStaged */ 9083 final boolean originStaged; 9084 9085 // TODO: define inherit location 9086 9087 final IPackageInstallObserver2 observer; 9088 // Always refers to PackageManager flags only 9089 final int flags; 9090 final String installerPackageName; 9091 final ManifestDigest manifestDigest; 9092 final UserHandle user; 9093 final String abiOverride; 9094 final boolean multiArch; 9095 9096 // The list of instruction sets supported by this app. This is currently 9097 // only used during the rmdex() phase to clean up resources. We can get rid of this 9098 // if we move dex files under the common app path. 9099 /* nullable */ String[] instructionSets; 9100 9101 InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 9102 int flags, String installerPackageName, ManifestDigest manifestDigest, 9103 UserHandle user, String[] instructionSets, 9104 String abiOverride, boolean multiArch) { 9105 this.originFile = originFile; 9106 this.originStaged = originStaged; 9107 this.flags = flags; 9108 this.observer = observer; 9109 this.installerPackageName = installerPackageName; 9110 this.manifestDigest = manifestDigest; 9111 this.user = user; 9112 this.instructionSets = instructionSets; 9113 this.abiOverride = abiOverride; 9114 this.multiArch = multiArch; 9115 } 9116 9117 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9118 abstract int doPreInstall(int status); 9119 9120 /** 9121 * Rename package into final resting place. All paths on the given 9122 * scanned package should be updated to reflect the rename. 9123 */ 9124 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9125 abstract int doPostInstall(int status, int uid); 9126 9127 /** @see PackageSettingBase#codePathString */ 9128 abstract String getCodePath(); 9129 /** @see PackageSettingBase#resourcePathString */ 9130 abstract String getResourcePath(); 9131 abstract String getLegacyNativeLibraryPath(); 9132 9133 // Need installer lock especially for dex file removal. 9134 abstract void cleanUpResourcesLI(); 9135 abstract boolean doPostDeleteLI(boolean delete); 9136 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9137 9138 /** 9139 * Called before the source arguments are copied. This is used mostly 9140 * for MoveParams when it needs to read the source file to put it in the 9141 * destination. 9142 */ 9143 int doPreCopy() { 9144 return PackageManager.INSTALL_SUCCEEDED; 9145 } 9146 9147 /** 9148 * Called after the source arguments are copied. This is used mostly for 9149 * MoveParams when it needs to read the source file to put it in the 9150 * destination. 9151 * 9152 * @return 9153 */ 9154 int doPostCopy(int uid) { 9155 return PackageManager.INSTALL_SUCCEEDED; 9156 } 9157 9158 protected boolean isFwdLocked() { 9159 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9160 } 9161 9162 UserHandle getUser() { 9163 return user; 9164 } 9165 } 9166 9167 /** 9168 * Logic to handle installation of non-ASEC applications, including copying 9169 * and renaming logic. 9170 */ 9171 class FileInstallArgs extends InstallArgs { 9172 private File codeFile; 9173 private File resourceFile; 9174 private File legacyNativeLibraryPath; 9175 9176 // Example topology: 9177 // /data/app/com.example/base.apk 9178 // /data/app/com.example/split_foo.apk 9179 // /data/app/com.example/lib/arm/libfoo.so 9180 // /data/app/com.example/lib/arm64/libfoo.so 9181 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9182 9183 /** New install */ 9184 FileInstallArgs(InstallParams params) { 9185 super(params.originFile, params.originStaged, params.observer, params.flags, 9186 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9187 null /* instruction sets */, params.packageAbiOverride, 9188 params.multiArch); 9189 if (isFwdLocked()) { 9190 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9191 } 9192 } 9193 9194 /** Existing install */ 9195 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9196 String[] instructionSets, boolean isMultiArch) { 9197 super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch); 9198 this.codeFile = (codePath != null) ? new File(codePath) : null; 9199 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9200 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9201 new File(legacyNativeLibraryPath) : null; 9202 } 9203 9204 /** New install from existing */ 9205 FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) { 9206 super(originFile, false, null, 0, null, null, null, instructionSets, null, 9207 isMultiArch); 9208 } 9209 9210 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9211 final long lowThreshold; 9212 9213 final DeviceStorageMonitorInternal 9214 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9215 if (dsm == null) { 9216 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9217 lowThreshold = 0L; 9218 } else { 9219 if (dsm.isMemoryLow()) { 9220 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9221 return false; 9222 } 9223 9224 lowThreshold = dsm.getMemoryLowThreshold(); 9225 } 9226 9227 return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9228 lowThreshold); 9229 } 9230 9231 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9232 int ret = PackageManager.INSTALL_SUCCEEDED; 9233 9234 if (originStaged) { 9235 Slog.d(TAG, originFile + " already staged; skipping copy"); 9236 codeFile = originFile; 9237 resourceFile = originFile; 9238 } else { 9239 try { 9240 final File tempDir = mInstallerService.allocateSessionDir(); 9241 codeFile = tempDir; 9242 resourceFile = tempDir; 9243 } catch (IOException e) { 9244 Slog.w(TAG, "Failed to create copy file: " + e); 9245 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9246 } 9247 9248 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9249 @Override 9250 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9251 if (!FileUtils.isValidExtFilename(name)) { 9252 throw new IllegalArgumentException("Invalid filename: " + name); 9253 } 9254 try { 9255 final File file = new File(codeFile, name); 9256 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9257 O_RDWR | O_CREAT, 0644); 9258 Os.chmod(file.getAbsolutePath(), 0644); 9259 return new ParcelFileDescriptor(fd); 9260 } catch (ErrnoException e) { 9261 throw new RemoteException("Failed to open: " + e.getMessage()); 9262 } 9263 } 9264 }; 9265 9266 ret = imcs.copyPackage(originFile.getAbsolutePath(), target); 9267 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9268 Slog.e(TAG, "Failed to copy package"); 9269 return ret; 9270 } 9271 } 9272 9273 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9274 NativeLibraryHelper.Handle handle = null; 9275 try { 9276 handle = NativeLibraryHelper.Handle.create(codeFile); 9277 if (multiArch) { 9278 // Warn if we've set an abiOverride for multi-lib packages.. 9279 // By definition, we need to copy both 32 and 64 bit libraries for 9280 // such packages. 9281 if (abiOverride != null) { 9282 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9283 } 9284 9285 int copyRet = PackageManager.NO_NATIVE_LIBRARIES; 9286 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9287 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9288 Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */); 9289 maybeThrowExceptionForMultiArchCopy("Failure copying 32 bit native libraries", copyRet); 9290 } 9291 9292 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9293 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9294 Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */); 9295 maybeThrowExceptionForMultiArchCopy("Failure copying 64 bit native libraries", copyRet); 9296 } 9297 } else { 9298 String[] abiList = (abiOverride != null) ? 9299 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 9300 9301 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null && 9302 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9303 abiList = Build.SUPPORTED_32_BIT_ABIS; 9304 } 9305 9306 int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList, 9307 true /* use isa specific subdirs */); 9308 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9309 Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]"); 9310 return copyRet; 9311 } 9312 } 9313 } catch (IOException e) { 9314 Slog.e(TAG, "Copying native libraries failed", e); 9315 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9316 } catch (PackageManagerException pme) { 9317 Slog.e(TAG, "Copying native libraries failed", pme); 9318 ret = pme.error; 9319 } finally { 9320 IoUtils.closeQuietly(handle); 9321 } 9322 9323 return ret; 9324 } 9325 9326 int doPreInstall(int status) { 9327 if (status != PackageManager.INSTALL_SUCCEEDED) { 9328 cleanUp(); 9329 } 9330 return status; 9331 } 9332 9333 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9334 if (status != PackageManager.INSTALL_SUCCEEDED) { 9335 cleanUp(); 9336 return false; 9337 } else { 9338 final File beforeCodeFile = codeFile; 9339 final File afterCodeFile = getNextCodePath(pkg.packageName); 9340 9341 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9342 try { 9343 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9344 } catch (ErrnoException e) { 9345 Slog.d(TAG, "Failed to rename", e); 9346 return false; 9347 } 9348 9349 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9350 Slog.d(TAG, "Failed to restorecon"); 9351 return false; 9352 } 9353 9354 // Reflect the rename internally 9355 codeFile = afterCodeFile; 9356 resourceFile = afterCodeFile; 9357 9358 // Reflect the rename in scanned details 9359 pkg.codePath = afterCodeFile.getAbsolutePath(); 9360 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9361 pkg.baseCodePath); 9362 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9363 pkg.splitCodePaths); 9364 9365 // Reflect the rename in app info 9366 pkg.applicationInfo.setCodePath(pkg.codePath); 9367 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9368 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9369 pkg.applicationInfo.setResourcePath(pkg.codePath); 9370 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9371 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9372 9373 return true; 9374 } 9375 } 9376 9377 int doPostInstall(int status, int uid) { 9378 if (status != PackageManager.INSTALL_SUCCEEDED) { 9379 cleanUp(); 9380 } 9381 return status; 9382 } 9383 9384 @Override 9385 String getCodePath() { 9386 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9387 } 9388 9389 @Override 9390 String getResourcePath() { 9391 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9392 } 9393 9394 @Override 9395 String getLegacyNativeLibraryPath() { 9396 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9397 } 9398 9399 private boolean cleanUp() { 9400 if (codeFile == null || !codeFile.exists()) { 9401 return false; 9402 } 9403 9404 if (codeFile.isDirectory()) { 9405 FileUtils.deleteContents(codeFile); 9406 } 9407 codeFile.delete(); 9408 9409 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9410 resourceFile.delete(); 9411 } 9412 9413 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9414 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9415 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9416 } 9417 legacyNativeLibraryPath.delete(); 9418 } 9419 9420 return true; 9421 } 9422 9423 void cleanUpResourcesLI() { 9424 // Try enumerating all code paths before deleting 9425 List<String> allCodePaths = Collections.EMPTY_LIST; 9426 if (codeFile != null && codeFile.exists()) { 9427 try { 9428 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9429 allCodePaths = pkg.getAllCodePaths(); 9430 } catch (PackageParserException e) { 9431 // Ignored; we tried our best 9432 } 9433 } 9434 9435 cleanUp(); 9436 9437 if (!allCodePaths.isEmpty()) { 9438 if (instructionSets == null) { 9439 throw new IllegalStateException("instructionSet == null"); 9440 } 9441 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9442 for (String codePath : allCodePaths) { 9443 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9444 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9445 if (retCode < 0) { 9446 Slog.w(TAG, "Couldn't remove dex file for package: " 9447 + " at location " + codePath + ", retcode=" + retCode); 9448 // we don't consider this to be a failure of the core package deletion 9449 } 9450 } 9451 } 9452 } 9453 } 9454 9455 boolean doPostDeleteLI(boolean delete) { 9456 // XXX err, shouldn't we respect the delete flag? 9457 cleanUpResourcesLI(); 9458 return true; 9459 } 9460 } 9461 9462 private boolean isAsecExternal(String cid) { 9463 final String asecPath = PackageHelper.getSdFilesystem(cid); 9464 return !asecPath.startsWith(mAsecInternalPath); 9465 } 9466 9467 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9468 PackageManagerException { 9469 if (copyRet < 0) { 9470 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9471 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9472 throw new PackageManagerException(copyRet, message); 9473 } 9474 } 9475 } 9476 9477 /** 9478 * Extract the MountService "container ID" from the full code path of an 9479 * .apk. 9480 */ 9481 static String cidFromCodePath(String fullCodePath) { 9482 int eidx = fullCodePath.lastIndexOf("/"); 9483 String subStr1 = fullCodePath.substring(0, eidx); 9484 int sidx = subStr1.lastIndexOf("/"); 9485 return subStr1.substring(sidx+1, eidx); 9486 } 9487 9488 /** 9489 * Logic to handle installation of ASEC applications, including copying and 9490 * renaming logic. 9491 */ 9492 class AsecInstallArgs extends InstallArgs { 9493 // TODO: teach about handling cluster directories 9494 9495 static final String RES_FILE_NAME = "pkg.apk"; 9496 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9497 9498 String cid; 9499 String packagePath; 9500 String resourcePath; 9501 String legacyNativeLibraryDir; 9502 9503 /** New install */ 9504 AsecInstallArgs(InstallParams params) { 9505 super(params.originFile, params.originStaged, params.observer, params.flags, 9506 params.installerPackageName, params.getManifestDigest(), 9507 params.getUser(), null /* instruction sets */, 9508 params.packageAbiOverride, params.multiArch); 9509 } 9510 9511 /** Existing install */ 9512 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9513 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9514 super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9515 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9516 instructionSets, null, isMultiArch); 9517 // Extract cid from fullCodePath 9518 int eidx = fullCodePath.lastIndexOf("/"); 9519 String subStr1 = fullCodePath.substring(0, eidx); 9520 int sidx = subStr1.lastIndexOf("/"); 9521 cid = subStr1.substring(sidx+1, eidx); 9522 setCachePath(subStr1); 9523 } 9524 9525 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked, 9526 boolean isMultiArch) { 9527 super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9528 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9529 instructionSets, null, isMultiArch); 9530 this.cid = cid; 9531 setCachePath(PackageHelper.getSdDir(cid)); 9532 } 9533 9534 /** New install from existing */ 9535 AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets, 9536 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9537 super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9538 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9539 instructionSets, null, isMultiArch); 9540 this.cid = cid; 9541 } 9542 9543 void createCopyFile() { 9544 cid = getTempContainerId(); 9545 } 9546 9547 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9548 return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9549 abiOverride); 9550 } 9551 9552 private final boolean isExternal() { 9553 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9554 } 9555 9556 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9557 if (temp) { 9558 createCopyFile(); 9559 } else { 9560 /* 9561 * Pre-emptively destroy the container since it's destroyed if 9562 * copying fails due to it existing anyway. 9563 */ 9564 PackageHelper.destroySdDir(cid); 9565 } 9566 9567 final String newCachePath = imcs.copyPackageToContainer( 9568 originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9569 isFwdLocked(), abiOverride); 9570 9571 if (newCachePath != null) { 9572 setCachePath(newCachePath); 9573 return PackageManager.INSTALL_SUCCEEDED; 9574 } else { 9575 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9576 } 9577 } 9578 9579 @Override 9580 String getCodePath() { 9581 return packagePath; 9582 } 9583 9584 @Override 9585 String getResourcePath() { 9586 return resourcePath; 9587 } 9588 9589 @Override 9590 String getLegacyNativeLibraryPath() { 9591 return legacyNativeLibraryDir; 9592 } 9593 9594 int doPreInstall(int status) { 9595 if (status != PackageManager.INSTALL_SUCCEEDED) { 9596 // Destroy container 9597 PackageHelper.destroySdDir(cid); 9598 } else { 9599 boolean mounted = PackageHelper.isContainerMounted(cid); 9600 if (!mounted) { 9601 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9602 Process.SYSTEM_UID); 9603 if (newCachePath != null) { 9604 setCachePath(newCachePath); 9605 } else { 9606 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9607 } 9608 } 9609 } 9610 return status; 9611 } 9612 9613 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9614 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9615 String newCachePath = null; 9616 if (PackageHelper.isContainerMounted(cid)) { 9617 // Unmount the container 9618 if (!PackageHelper.unMountSdDir(cid)) { 9619 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9620 return false; 9621 } 9622 } 9623 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9624 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9625 " which might be stale. Will try to clean up."); 9626 // Clean up the stale container and proceed to recreate. 9627 if (!PackageHelper.destroySdDir(newCacheId)) { 9628 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9629 return false; 9630 } 9631 // Successfully cleaned up stale container. Try to rename again. 9632 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9633 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9634 + " inspite of cleaning it up."); 9635 return false; 9636 } 9637 } 9638 if (!PackageHelper.isContainerMounted(newCacheId)) { 9639 Slog.w(TAG, "Mounting container " + newCacheId); 9640 newCachePath = PackageHelper.mountSdDir(newCacheId, 9641 getEncryptKey(), Process.SYSTEM_UID); 9642 } else { 9643 newCachePath = PackageHelper.getSdDir(newCacheId); 9644 } 9645 if (newCachePath == null) { 9646 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9647 return false; 9648 } 9649 Log.i(TAG, "Succesfully renamed " + cid + 9650 " to " + newCacheId + 9651 " at new path: " + newCachePath); 9652 cid = newCacheId; 9653 setCachePath(newCachePath); 9654 9655 // TODO: extend to support split APKs 9656 pkg.codePath = getCodePath(); 9657 pkg.baseCodePath = getCodePath(); 9658 pkg.splitCodePaths = null; 9659 9660 pkg.applicationInfo.setCodePath(getCodePath()); 9661 pkg.applicationInfo.setBaseCodePath(getCodePath()); 9662 pkg.applicationInfo.setSplitCodePaths(null); 9663 pkg.applicationInfo.setResourcePath(getResourcePath()); 9664 pkg.applicationInfo.setBaseResourcePath(getResourcePath()); 9665 pkg.applicationInfo.setSplitResourcePaths(null); 9666 9667 return true; 9668 } 9669 9670 private void setCachePath(String newCachePath) { 9671 File cachePath = new File(newCachePath); 9672 legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath(); 9673 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9674 9675 if (isFwdLocked()) { 9676 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9677 } else { 9678 resourcePath = packagePath; 9679 } 9680 } 9681 9682 int doPostInstall(int status, int uid) { 9683 if (status != PackageManager.INSTALL_SUCCEEDED) { 9684 cleanUp(); 9685 } else { 9686 final int groupOwner; 9687 final String protectedFile; 9688 if (isFwdLocked()) { 9689 groupOwner = UserHandle.getSharedAppGid(uid); 9690 protectedFile = RES_FILE_NAME; 9691 } else { 9692 groupOwner = -1; 9693 protectedFile = null; 9694 } 9695 9696 if (uid < Process.FIRST_APPLICATION_UID 9697 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9698 Slog.e(TAG, "Failed to finalize " + cid); 9699 PackageHelper.destroySdDir(cid); 9700 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9701 } 9702 9703 boolean mounted = PackageHelper.isContainerMounted(cid); 9704 if (!mounted) { 9705 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9706 } 9707 } 9708 return status; 9709 } 9710 9711 private void cleanUp() { 9712 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9713 9714 // Destroy secure container 9715 PackageHelper.destroySdDir(cid); 9716 } 9717 9718 void cleanUpResourcesLI() { 9719 String sourceFile = getCodePath(); 9720 // Remove dex file 9721 if (instructionSets == null) { 9722 throw new IllegalStateException("instructionSet == null"); 9723 } 9724 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9725 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9726 int retCode = mInstaller.rmdex(sourceFile, dexCodeInstructionSet); 9727 if (retCode < 0) { 9728 Slog.w(TAG, "Couldn't remove dex file for package: " 9729 + " at location " 9730 + sourceFile.toString() + ", retcode=" + retCode); 9731 // we don't consider this to be a failure of the core package deletion 9732 } 9733 } 9734 cleanUp(); 9735 } 9736 9737 boolean matchContainer(String app) { 9738 if (cid.startsWith(app)) { 9739 return true; 9740 } 9741 return false; 9742 } 9743 9744 String getPackageName() { 9745 return getAsecPackageName(cid); 9746 } 9747 9748 boolean doPostDeleteLI(boolean delete) { 9749 boolean ret = false; 9750 boolean mounted = PackageHelper.isContainerMounted(cid); 9751 if (mounted) { 9752 // Unmount first 9753 ret = PackageHelper.unMountSdDir(cid); 9754 } 9755 if (ret && delete) { 9756 cleanUpResourcesLI(); 9757 } 9758 return ret; 9759 } 9760 9761 @Override 9762 int doPreCopy() { 9763 if (isFwdLocked()) { 9764 if (!PackageHelper.fixSdPermissions(cid, 9765 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9766 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9767 } 9768 } 9769 9770 return PackageManager.INSTALL_SUCCEEDED; 9771 } 9772 9773 @Override 9774 int doPostCopy(int uid) { 9775 if (isFwdLocked()) { 9776 if (uid < Process.FIRST_APPLICATION_UID 9777 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9778 RES_FILE_NAME)) { 9779 Slog.e(TAG, "Failed to finalize " + cid); 9780 PackageHelper.destroySdDir(cid); 9781 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9782 } 9783 } 9784 9785 return PackageManager.INSTALL_SUCCEEDED; 9786 } 9787 } 9788 9789 static String getAsecPackageName(String packageCid) { 9790 int idx = packageCid.lastIndexOf("-"); 9791 if (idx == -1) { 9792 return packageCid; 9793 } 9794 return packageCid.substring(0, idx); 9795 } 9796 9797 // Utility method used to create code paths based on package name and available index. 9798 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9799 String idxStr = ""; 9800 int idx = 1; 9801 // Fall back to default value of idx=1 if prefix is not 9802 // part of oldCodePath 9803 if (oldCodePath != null) { 9804 String subStr = oldCodePath; 9805 // Drop the suffix right away 9806 if (suffix != null && subStr.endsWith(suffix)) { 9807 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9808 } 9809 // If oldCodePath already contains prefix find out the 9810 // ending index to either increment or decrement. 9811 int sidx = subStr.lastIndexOf(prefix); 9812 if (sidx != -1) { 9813 subStr = subStr.substring(sidx + prefix.length()); 9814 if (subStr != null) { 9815 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9816 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9817 } 9818 try { 9819 idx = Integer.parseInt(subStr); 9820 if (idx <= 1) { 9821 idx++; 9822 } else { 9823 idx--; 9824 } 9825 } catch(NumberFormatException e) { 9826 } 9827 } 9828 } 9829 } 9830 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9831 return prefix + idxStr; 9832 } 9833 9834 private File getNextCodePath(String packageName) { 9835 int suffix = 1; 9836 File result; 9837 do { 9838 result = new File(mAppInstallDir, packageName + "-" + suffix); 9839 suffix++; 9840 } while (result.exists()); 9841 return result; 9842 } 9843 9844 // Utility method used to ignore ADD/REMOVE events 9845 // by directory observer. 9846 private static boolean ignoreCodePath(String fullPathStr) { 9847 String apkName = deriveCodePathName(fullPathStr); 9848 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9849 if (idx != -1 && ((idx+1) < apkName.length())) { 9850 // Make sure the package ends with a numeral 9851 String version = apkName.substring(idx+1); 9852 try { 9853 Integer.parseInt(version); 9854 return true; 9855 } catch (NumberFormatException e) {} 9856 } 9857 return false; 9858 } 9859 9860 // Utility method that returns the relative package path with respect 9861 // to the installation directory. Like say for /data/data/com.test-1.apk 9862 // string com.test-1 is returned. 9863 static String deriveCodePathName(String codePath) { 9864 if (codePath == null) { 9865 return null; 9866 } 9867 final File codeFile = new File(codePath); 9868 final String name = codeFile.getName(); 9869 if (codeFile.isDirectory()) { 9870 return name; 9871 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9872 final int lastDot = name.lastIndexOf('.'); 9873 return name.substring(0, lastDot); 9874 } else { 9875 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9876 return null; 9877 } 9878 } 9879 9880 class PackageInstalledInfo { 9881 String name; 9882 int uid; 9883 // The set of users that originally had this package installed. 9884 int[] origUsers; 9885 // The set of users that now have this package installed. 9886 int[] newUsers; 9887 PackageParser.Package pkg; 9888 int returnCode; 9889 String returnMsg; 9890 PackageRemovedInfo removedInfo; 9891 9892 public void setError(int code, String msg) { 9893 returnCode = code; 9894 returnMsg = msg; 9895 Slog.w(TAG, msg); 9896 } 9897 9898 public void setError(String msg, PackageParserException e) { 9899 returnCode = e.error; 9900 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9901 Slog.w(TAG, msg, e); 9902 } 9903 9904 public void setError(String msg, PackageManagerException e) { 9905 returnCode = e.error; 9906 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9907 Slog.w(TAG, msg, e); 9908 } 9909 9910 // In some error cases we want to convey more info back to the observer 9911 String origPackage; 9912 String origPermission; 9913 } 9914 9915 /* 9916 * Install a non-existing package. 9917 */ 9918 private void installNewPackageLI(PackageParser.Package pkg, 9919 int parseFlags, int scanMode, UserHandle user, 9920 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9921 // Remember this for later, in case we need to rollback this install 9922 String pkgName = pkg.packageName; 9923 9924 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9925 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9926 synchronized(mPackages) { 9927 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9928 // A package with the same name is already installed, though 9929 // it has been renamed to an older name. The package we 9930 // are trying to install should be installed as an update to 9931 // the existing one, but that has not been requested, so bail. 9932 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9933 + " without first uninstalling package running as " 9934 + mSettings.mRenamedPackages.get(pkgName)); 9935 return; 9936 } 9937 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9938 // Don't allow installation over an existing package with the same name. 9939 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9940 + " without first uninstalling."); 9941 return; 9942 } 9943 } 9944 9945 try { 9946 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9947 System.currentTimeMillis(), user, abiOverride); 9948 9949 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9950 // delete the partially installed application. the data directory will have to be 9951 // restored if it was already existing 9952 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9953 // remove package from internal structures. Note that we want deletePackageX to 9954 // delete the package data and cache directories that it created in 9955 // scanPackageLocked, unless those directories existed before we even tried to 9956 // install. 9957 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9958 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9959 res.removedInfo, true); 9960 } 9961 9962 } catch (PackageManagerException e) { 9963 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9964 } 9965 } 9966 9967 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9968 // Upgrade keysets are being used. Determine if new package has a superset of the 9969 // required keys. 9970 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9971 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9972 for (int i = 0; i < upgradeKeySets.length; i++) { 9973 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9974 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9975 return true; 9976 } 9977 } 9978 return false; 9979 } 9980 9981 private void replacePackageLI(PackageParser.Package pkg, 9982 int parseFlags, int scanMode, UserHandle user, 9983 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9984 PackageParser.Package oldPackage; 9985 String pkgName = pkg.packageName; 9986 int[] allUsers; 9987 boolean[] perUserInstalled; 9988 9989 // First find the old package info and check signatures 9990 synchronized(mPackages) { 9991 oldPackage = mPackages.get(pkgName); 9992 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9993 PackageSetting ps = mSettings.mPackages.get(pkgName); 9994 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9995 // default to original signature matching 9996 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9997 != PackageManager.SIGNATURE_MATCH) { 9998 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9999 "New package has a different signature: " + pkgName); 10000 return; 10001 } 10002 } else { 10003 if(!checkUpgradeKeySetLP(ps, pkg)) { 10004 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10005 "New package not signed by keys specified by upgrade-keysets: " 10006 + pkgName); 10007 return; 10008 } 10009 } 10010 10011 // In case of rollback, remember per-user/profile install state 10012 allUsers = sUserManager.getUserIds(); 10013 perUserInstalled = new boolean[allUsers.length]; 10014 for (int i = 0; i < allUsers.length; i++) { 10015 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10016 } 10017 } 10018 10019 boolean sysPkg = (isSystemApp(oldPackage)); 10020 if (sysPkg) { 10021 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10022 user, allUsers, perUserInstalled, installerPackageName, res, 10023 abiOverride); 10024 } else { 10025 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10026 user, allUsers, perUserInstalled, installerPackageName, res, 10027 abiOverride); 10028 } 10029 } 10030 10031 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10032 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10033 int[] allUsers, boolean[] perUserInstalled, 10034 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10035 String pkgName = deletedPackage.packageName; 10036 boolean deletedPkg = true; 10037 boolean updatedSettings = false; 10038 10039 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10040 + deletedPackage); 10041 long origUpdateTime; 10042 if (pkg.mExtras != null) { 10043 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10044 } else { 10045 origUpdateTime = 0; 10046 } 10047 10048 // First delete the existing package while retaining the data directory 10049 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10050 res.removedInfo, true)) { 10051 // If the existing package wasn't successfully deleted 10052 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10053 deletedPkg = false; 10054 } else { 10055 // Successfully deleted the old package. Now proceed with re-installation 10056 deleteCodeCacheDirsLI(pkgName); 10057 try { 10058 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10059 scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user, abiOverride); 10060 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10061 updatedSettings = true; 10062 } catch (PackageManagerException e) { 10063 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10064 } 10065 } 10066 10067 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10068 // remove package from internal structures. Note that we want deletePackageX to 10069 // delete the package data and cache directories that it created in 10070 // scanPackageLocked, unless those directories existed before we even tried to 10071 // install. 10072 if(updatedSettings) { 10073 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10074 deletePackageLI( 10075 pkgName, null, true, allUsers, perUserInstalled, 10076 PackageManager.DELETE_KEEP_DATA, 10077 res.removedInfo, true); 10078 } 10079 // Since we failed to install the new package we need to restore the old 10080 // package that we deleted. 10081 if (deletedPkg) { 10082 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10083 File restoreFile = new File(deletedPackage.codePath); 10084 // Parse old package 10085 boolean oldOnSd = isExternal(deletedPackage); 10086 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10087 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10088 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10089 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 10090 | SCAN_UPDATE_TIME; 10091 try { 10092 scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null, 10093 null); 10094 } catch (PackageManagerException e) { 10095 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10096 + e.getMessage()); 10097 return; 10098 } 10099 // Restore of old package succeeded. Update permissions. 10100 // writer 10101 synchronized (mPackages) { 10102 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10103 UPDATE_PERMISSIONS_ALL); 10104 // can downgrade to reader 10105 mSettings.writeLPr(); 10106 } 10107 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10108 } 10109 } 10110 } 10111 10112 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10113 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10114 int[] allUsers, boolean[] perUserInstalled, 10115 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10116 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10117 + ", old=" + deletedPackage); 10118 boolean updatedSettings = false; 10119 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 10120 PackageParser.PARSE_IS_SYSTEM; 10121 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10122 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10123 } 10124 String packageName = deletedPackage.packageName; 10125 if (packageName == null) { 10126 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10127 "Attempt to delete null packageName."); 10128 return; 10129 } 10130 PackageParser.Package oldPkg; 10131 PackageSetting oldPkgSetting; 10132 // reader 10133 synchronized (mPackages) { 10134 oldPkg = mPackages.get(packageName); 10135 oldPkgSetting = mSettings.mPackages.get(packageName); 10136 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10137 (oldPkgSetting == null)) { 10138 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10139 "Couldn't find package:" + packageName + " information"); 10140 return; 10141 } 10142 } 10143 10144 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10145 10146 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10147 res.removedInfo.removedPackage = packageName; 10148 // Remove existing system package 10149 removePackageLI(oldPkgSetting, true); 10150 // writer 10151 synchronized (mPackages) { 10152 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10153 // We didn't need to disable the .apk as a current system package, 10154 // which means we are replacing another update that is already 10155 // installed. We need to make sure to delete the older one's .apk. 10156 res.removedInfo.args = createInstallArgsForExisting(0, 10157 deletedPackage.applicationInfo.getCodePath(), 10158 deletedPackage.applicationInfo.getResourcePath(), 10159 deletedPackage.applicationInfo.nativeLibraryRootDir, 10160 getAppDexInstructionSets(deletedPackage.applicationInfo), 10161 isMultiArch(deletedPackage.applicationInfo)); 10162 } else { 10163 res.removedInfo.args = null; 10164 } 10165 } 10166 10167 // Successfully disabled the old package. Now proceed with re-installation 10168 deleteCodeCacheDirsLI(packageName); 10169 10170 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10171 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10172 10173 PackageParser.Package newPackage = null; 10174 try { 10175 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride); 10176 if (newPackage.mExtras != null) { 10177 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10178 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10179 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10180 10181 // is the update attempting to change shared user? that isn't going to work... 10182 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10183 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10184 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10185 + " to " + newPkgSetting.sharedUser); 10186 updatedSettings = true; 10187 } 10188 } 10189 10190 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10191 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10192 updatedSettings = true; 10193 } 10194 10195 } catch (PackageManagerException e) { 10196 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10197 } 10198 10199 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10200 // Re installation failed. Restore old information 10201 // Remove new pkg information 10202 if (newPackage != null) { 10203 removeInstalledPackageLI(newPackage, true); 10204 } 10205 // Add back the old system package 10206 try { 10207 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, 10208 null); 10209 } catch (PackageManagerException e) { 10210 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10211 } 10212 // Restore the old system information in Settings 10213 synchronized(mPackages) { 10214 if (updatedSettings) { 10215 mSettings.enableSystemPackageLPw(packageName); 10216 mSettings.setInstallerPackageName(packageName, 10217 oldPkgSetting.installerPackageName); 10218 } 10219 mSettings.writeLPr(); 10220 } 10221 } 10222 } 10223 10224 // Utility method used to move dex files during install. 10225 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10226 // TODO: extend to move split APK dex files 10227 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10228 final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo); 10229 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10230 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10231 int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath, 10232 dexCodeInstructionSet); 10233 if (retCode != 0) { 10234 /* 10235 * Programs may be lazily run through dexopt, so the 10236 * source may not exist. However, something seems to 10237 * have gone wrong, so note that dexopt needs to be 10238 * run again and remove the source file. In addition, 10239 * remove the target to make sure there isn't a stale 10240 * file from a previous version of the package. 10241 */ 10242 newPackage.mDexOptPerformed.clear(); 10243 mInstaller.rmdex(oldCodePath, dexCodeInstructionSet); 10244 mInstaller.rmdex(newPackage.baseCodePath, dexCodeInstructionSet); 10245 } 10246 } 10247 } 10248 return PackageManager.INSTALL_SUCCEEDED; 10249 } 10250 10251 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10252 int[] allUsers, boolean[] perUserInstalled, 10253 PackageInstalledInfo res) { 10254 String pkgName = newPackage.packageName; 10255 synchronized (mPackages) { 10256 //write settings. the installStatus will be incomplete at this stage. 10257 //note that the new package setting would have already been 10258 //added to mPackages. It hasn't been persisted yet. 10259 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10260 mSettings.writeLPr(); 10261 } 10262 10263 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10264 10265 synchronized (mPackages) { 10266 updatePermissionsLPw(newPackage.packageName, newPackage, 10267 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10268 ? UPDATE_PERMISSIONS_ALL : 0)); 10269 // For system-bundled packages, we assume that installing an upgraded version 10270 // of the package implies that the user actually wants to run that new code, 10271 // so we enable the package. 10272 if (isSystemApp(newPackage)) { 10273 // NB: implicit assumption that system package upgrades apply to all users 10274 if (DEBUG_INSTALL) { 10275 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10276 } 10277 PackageSetting ps = mSettings.mPackages.get(pkgName); 10278 if (ps != null) { 10279 if (res.origUsers != null) { 10280 for (int userHandle : res.origUsers) { 10281 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10282 userHandle, installerPackageName); 10283 } 10284 } 10285 // Also convey the prior install/uninstall state 10286 if (allUsers != null && perUserInstalled != null) { 10287 for (int i = 0; i < allUsers.length; i++) { 10288 if (DEBUG_INSTALL) { 10289 Slog.d(TAG, " user " + allUsers[i] 10290 + " => " + perUserInstalled[i]); 10291 } 10292 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10293 } 10294 // these install state changes will be persisted in the 10295 // upcoming call to mSettings.writeLPr(). 10296 } 10297 } 10298 } 10299 res.name = pkgName; 10300 res.uid = newPackage.applicationInfo.uid; 10301 res.pkg = newPackage; 10302 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10303 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10304 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10305 //to update install status 10306 mSettings.writeLPr(); 10307 } 10308 } 10309 10310 private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) { 10311 int pFlags = args.flags; 10312 String installerPackageName = args.installerPackageName; 10313 File tmpPackageFile = new File(args.getCodePath()); 10314 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10315 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10316 boolean replace = false; 10317 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10318 | (newInstall ? SCAN_NEW_INSTALL : 0); 10319 // Result object to be returned 10320 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10321 10322 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10323 // Retrieve PackageSettings and parse package 10324 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10325 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10326 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10327 PackageParser pp = new PackageParser(); 10328 pp.setSeparateProcesses(mSeparateProcesses); 10329 pp.setDisplayMetrics(mMetrics); 10330 10331 final PackageParser.Package pkg; 10332 try { 10333 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10334 } catch (PackageParserException e) { 10335 res.setError("Failed parse during installPackageLI", e); 10336 return; 10337 } 10338 10339 String pkgName = res.name = pkg.packageName; 10340 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10341 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10342 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10343 return; 10344 } 10345 } 10346 10347 try { 10348 pp.collectCertificates(pkg, parseFlags); 10349 pp.collectManifestDigest(pkg); 10350 } catch (PackageParserException e) { 10351 res.setError("Failed collect during installPackageLI", e); 10352 return; 10353 } 10354 10355 /* If the installer passed in a manifest digest, compare it now. */ 10356 if (args.manifestDigest != null) { 10357 if (DEBUG_INSTALL) { 10358 final String parsedManifest = pkg.manifestDigest == null ? "null" 10359 : pkg.manifestDigest.toString(); 10360 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10361 + parsedManifest); 10362 } 10363 10364 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10365 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10366 return; 10367 } 10368 } else if (DEBUG_INSTALL) { 10369 final String parsedManifest = pkg.manifestDigest == null 10370 ? "null" : pkg.manifestDigest.toString(); 10371 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10372 } 10373 10374 // Get rid of all references to package scan path via parser. 10375 pp = null; 10376 String oldCodePath = null; 10377 boolean systemApp = false; 10378 synchronized (mPackages) { 10379 // Check whether the newly-scanned package wants to define an already-defined perm 10380 int N = pkg.permissions.size(); 10381 for (int i = N-1; i >= 0; i--) { 10382 PackageParser.Permission perm = pkg.permissions.get(i); 10383 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10384 if (bp != null) { 10385 // If the defining package is signed with our cert, it's okay. This 10386 // also includes the "updating the same package" case, of course. 10387 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10388 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10389 // If the owning package is the system itself, we log but allow 10390 // install to proceed; we fail the install on all other permission 10391 // redefinitions. 10392 if (!bp.sourcePackage.equals("android")) { 10393 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10394 + pkg.packageName + " attempting to redeclare permission " 10395 + perm.info.name + " already owned by " + bp.sourcePackage); 10396 res.origPermission = perm.info.name; 10397 res.origPackage = bp.sourcePackage; 10398 return; 10399 } else { 10400 Slog.w(TAG, "Package " + pkg.packageName 10401 + " attempting to redeclare system permission " 10402 + perm.info.name + "; ignoring new declaration"); 10403 pkg.permissions.remove(i); 10404 } 10405 } 10406 } 10407 } 10408 10409 // Check if installing already existing package 10410 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10411 String oldName = mSettings.mRenamedPackages.get(pkgName); 10412 if (pkg.mOriginalPackages != null 10413 && pkg.mOriginalPackages.contains(oldName) 10414 && mPackages.containsKey(oldName)) { 10415 // This package is derived from an original package, 10416 // and this device has been updating from that original 10417 // name. We must continue using the original name, so 10418 // rename the new package here. 10419 pkg.setPackageName(oldName); 10420 pkgName = pkg.packageName; 10421 replace = true; 10422 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10423 + oldName + " pkgName=" + pkgName); 10424 } else if (mPackages.containsKey(pkgName)) { 10425 // This package, under its official name, already exists 10426 // on the device; we should replace it. 10427 replace = true; 10428 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10429 } 10430 } 10431 PackageSetting ps = mSettings.mPackages.get(pkgName); 10432 if (ps != null) { 10433 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10434 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10435 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10436 systemApp = (ps.pkg.applicationInfo.flags & 10437 ApplicationInfo.FLAG_SYSTEM) != 0; 10438 } 10439 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10440 } 10441 } 10442 10443 if (systemApp && onSd) { 10444 // Disable updates to system apps on sdcard 10445 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10446 "Cannot install updates to system apps on sdcard"); 10447 return; 10448 } 10449 10450 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10451 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10452 return; 10453 } 10454 10455 if (replace) { 10456 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10457 installerPackageName, res, args.abiOverride); 10458 } else { 10459 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10460 installerPackageName, res, args.abiOverride); 10461 } 10462 synchronized (mPackages) { 10463 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10464 if (ps != null) { 10465 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10466 } 10467 } 10468 } 10469 10470 private static boolean isForwardLocked(PackageParser.Package pkg) { 10471 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10472 } 10473 10474 private static boolean isForwardLocked(ApplicationInfo info) { 10475 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10476 } 10477 10478 private boolean isForwardLocked(PackageSetting ps) { 10479 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10480 } 10481 10482 private static boolean isMultiArch(PackageSetting ps) { 10483 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10484 } 10485 10486 private static boolean isMultiArch(ApplicationInfo info) { 10487 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10488 } 10489 10490 private static boolean isExternal(PackageParser.Package pkg) { 10491 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10492 } 10493 10494 private static boolean isExternal(PackageSetting ps) { 10495 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10496 } 10497 10498 private static boolean isExternal(ApplicationInfo info) { 10499 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10500 } 10501 10502 private static boolean isSystemApp(PackageParser.Package pkg) { 10503 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10504 } 10505 10506 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10507 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10508 } 10509 10510 private static boolean isSystemApp(ApplicationInfo info) { 10511 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10512 } 10513 10514 private static boolean isSystemApp(PackageSetting ps) { 10515 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10516 } 10517 10518 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10519 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10520 } 10521 10522 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10523 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10524 } 10525 10526 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10527 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10528 } 10529 10530 private int packageFlagsToInstallFlags(PackageSetting ps) { 10531 int installFlags = 0; 10532 if (isExternal(ps)) { 10533 installFlags |= PackageManager.INSTALL_EXTERNAL; 10534 } 10535 if (isForwardLocked(ps)) { 10536 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10537 } 10538 return installFlags; 10539 } 10540 10541 private void deleteTempPackageFiles() { 10542 final FilenameFilter filter = new FilenameFilter() { 10543 public boolean accept(File dir, String name) { 10544 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10545 } 10546 }; 10547 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10548 file.delete(); 10549 } 10550 } 10551 10552 @Override 10553 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10554 int flags) { 10555 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10556 flags); 10557 } 10558 10559 @Override 10560 public void deletePackage(final String packageName, 10561 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10562 mContext.enforceCallingOrSelfPermission( 10563 android.Manifest.permission.DELETE_PACKAGES, null); 10564 final int uid = Binder.getCallingUid(); 10565 if (UserHandle.getUserId(uid) != userId) { 10566 mContext.enforceCallingPermission( 10567 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10568 "deletePackage for user " + userId); 10569 } 10570 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10571 try { 10572 observer.onPackageDeleted(packageName, 10573 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10574 } catch (RemoteException re) { 10575 } 10576 return; 10577 } 10578 10579 boolean uninstallBlocked = false; 10580 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10581 int[] users = sUserManager.getUserIds(); 10582 for (int i = 0; i < users.length; ++i) { 10583 if (getBlockUninstallForUser(packageName, users[i])) { 10584 uninstallBlocked = true; 10585 break; 10586 } 10587 } 10588 } else { 10589 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10590 } 10591 if (uninstallBlocked) { 10592 try { 10593 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10594 null); 10595 } catch (RemoteException re) { 10596 } 10597 return; 10598 } 10599 10600 if (DEBUG_REMOVE) { 10601 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10602 } 10603 // Queue up an async operation since the package deletion may take a little while. 10604 mHandler.post(new Runnable() { 10605 public void run() { 10606 mHandler.removeCallbacks(this); 10607 final int returnCode = deletePackageX(packageName, userId, flags); 10608 if (observer != null) { 10609 try { 10610 observer.onPackageDeleted(packageName, returnCode, null); 10611 } catch (RemoteException e) { 10612 Log.i(TAG, "Observer no longer exists."); 10613 } //end catch 10614 } //end if 10615 } //end run 10616 }); 10617 } 10618 10619 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10620 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10621 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10622 try { 10623 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10624 || dpm.isDeviceOwner(packageName))) { 10625 return true; 10626 } 10627 } catch (RemoteException e) { 10628 } 10629 return false; 10630 } 10631 10632 /** 10633 * This method is an internal method that could be get invoked either 10634 * to delete an installed package or to clean up a failed installation. 10635 * After deleting an installed package, a broadcast is sent to notify any 10636 * listeners that the package has been installed. For cleaning up a failed 10637 * installation, the broadcast is not necessary since the package's 10638 * installation wouldn't have sent the initial broadcast either 10639 * The key steps in deleting a package are 10640 * deleting the package information in internal structures like mPackages, 10641 * deleting the packages base directories through installd 10642 * updating mSettings to reflect current status 10643 * persisting settings for later use 10644 * sending a broadcast if necessary 10645 */ 10646 private int deletePackageX(String packageName, int userId, int flags) { 10647 final PackageRemovedInfo info = new PackageRemovedInfo(); 10648 final boolean res; 10649 10650 if (isPackageDeviceAdmin(packageName, userId)) { 10651 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10652 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10653 } 10654 10655 boolean removedForAllUsers = false; 10656 boolean systemUpdate = false; 10657 10658 // for the uninstall-updates case and restricted profiles, remember the per- 10659 // userhandle installed state 10660 int[] allUsers; 10661 boolean[] perUserInstalled; 10662 synchronized (mPackages) { 10663 PackageSetting ps = mSettings.mPackages.get(packageName); 10664 allUsers = sUserManager.getUserIds(); 10665 perUserInstalled = new boolean[allUsers.length]; 10666 for (int i = 0; i < allUsers.length; i++) { 10667 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10668 } 10669 } 10670 10671 synchronized (mInstallLock) { 10672 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10673 res = deletePackageLI(packageName, 10674 (flags & PackageManager.DELETE_ALL_USERS) != 0 10675 ? UserHandle.ALL : new UserHandle(userId), 10676 true, allUsers, perUserInstalled, 10677 flags | REMOVE_CHATTY, info, true); 10678 systemUpdate = info.isRemovedPackageSystemUpdate; 10679 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10680 removedForAllUsers = true; 10681 } 10682 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10683 + " removedForAllUsers=" + removedForAllUsers); 10684 } 10685 10686 if (res) { 10687 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10688 10689 // If the removed package was a system update, the old system package 10690 // was re-enabled; we need to broadcast this information 10691 if (systemUpdate) { 10692 Bundle extras = new Bundle(1); 10693 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10694 ? info.removedAppId : info.uid); 10695 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10696 10697 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10698 extras, null, null, null); 10699 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10700 extras, null, null, null); 10701 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10702 null, packageName, null, null); 10703 } 10704 } 10705 // Force a gc here. 10706 Runtime.getRuntime().gc(); 10707 // Delete the resources here after sending the broadcast to let 10708 // other processes clean up before deleting resources. 10709 if (info.args != null) { 10710 synchronized (mInstallLock) { 10711 info.args.doPostDeleteLI(true); 10712 } 10713 } 10714 10715 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10716 } 10717 10718 static class PackageRemovedInfo { 10719 String removedPackage; 10720 int uid = -1; 10721 int removedAppId = -1; 10722 int[] removedUsers = null; 10723 boolean isRemovedPackageSystemUpdate = false; 10724 // Clean up resources deleted packages. 10725 InstallArgs args = null; 10726 10727 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10728 Bundle extras = new Bundle(1); 10729 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10730 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10731 if (replacing) { 10732 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10733 } 10734 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10735 if (removedPackage != null) { 10736 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10737 extras, null, null, removedUsers); 10738 if (fullRemove && !replacing) { 10739 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10740 extras, null, null, removedUsers); 10741 } 10742 } 10743 if (removedAppId >= 0) { 10744 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10745 removedUsers); 10746 } 10747 } 10748 } 10749 10750 /* 10751 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10752 * flag is not set, the data directory is removed as well. 10753 * make sure this flag is set for partially installed apps. If not its meaningless to 10754 * delete a partially installed application. 10755 */ 10756 private void removePackageDataLI(PackageSetting ps, 10757 int[] allUserHandles, boolean[] perUserInstalled, 10758 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10759 String packageName = ps.name; 10760 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10761 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10762 // Retrieve object to delete permissions for shared user later on 10763 final PackageSetting deletedPs; 10764 // reader 10765 synchronized (mPackages) { 10766 deletedPs = mSettings.mPackages.get(packageName); 10767 if (outInfo != null) { 10768 outInfo.removedPackage = packageName; 10769 outInfo.removedUsers = deletedPs != null 10770 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10771 : null; 10772 } 10773 } 10774 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10775 removeDataDirsLI(packageName); 10776 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10777 } 10778 // writer 10779 synchronized (mPackages) { 10780 if (deletedPs != null) { 10781 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10782 if (outInfo != null) { 10783 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10784 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10785 } 10786 if (deletedPs != null) { 10787 updatePermissionsLPw(deletedPs.name, null, 0); 10788 if (deletedPs.sharedUser != null) { 10789 // remove permissions associated with package 10790 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10791 } 10792 } 10793 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10794 } 10795 // make sure to preserve per-user disabled state if this removal was just 10796 // a downgrade of a system app to the factory package 10797 if (allUserHandles != null && perUserInstalled != null) { 10798 if (DEBUG_REMOVE) { 10799 Slog.d(TAG, "Propagating install state across downgrade"); 10800 } 10801 for (int i = 0; i < allUserHandles.length; i++) { 10802 if (DEBUG_REMOVE) { 10803 Slog.d(TAG, " user " + allUserHandles[i] 10804 + " => " + perUserInstalled[i]); 10805 } 10806 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10807 } 10808 } 10809 } 10810 // can downgrade to reader 10811 if (writeSettings) { 10812 // Save settings now 10813 mSettings.writeLPr(); 10814 } 10815 } 10816 if (outInfo != null) { 10817 // A user ID was deleted here. Go through all users and remove it 10818 // from KeyStore. 10819 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10820 } 10821 } 10822 10823 static boolean locationIsPrivileged(File path) { 10824 try { 10825 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10826 .getCanonicalPath(); 10827 return path.getCanonicalPath().startsWith(privilegedAppDir); 10828 } catch (IOException e) { 10829 Slog.e(TAG, "Unable to access code path " + path); 10830 } 10831 return false; 10832 } 10833 10834 /* 10835 * Tries to delete system package. 10836 */ 10837 private boolean deleteSystemPackageLI(PackageSetting newPs, 10838 int[] allUserHandles, boolean[] perUserInstalled, 10839 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10840 final boolean applyUserRestrictions 10841 = (allUserHandles != null) && (perUserInstalled != null); 10842 PackageSetting disabledPs = null; 10843 // Confirm if the system package has been updated 10844 // An updated system app can be deleted. This will also have to restore 10845 // the system pkg from system partition 10846 // reader 10847 synchronized (mPackages) { 10848 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10849 } 10850 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10851 + " disabledPs=" + disabledPs); 10852 if (disabledPs == null) { 10853 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10854 return false; 10855 } else if (DEBUG_REMOVE) { 10856 Slog.d(TAG, "Deleting system pkg from data partition"); 10857 } 10858 if (DEBUG_REMOVE) { 10859 if (applyUserRestrictions) { 10860 Slog.d(TAG, "Remembering install states:"); 10861 for (int i = 0; i < allUserHandles.length; i++) { 10862 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10863 } 10864 } 10865 } 10866 // Delete the updated package 10867 outInfo.isRemovedPackageSystemUpdate = true; 10868 if (disabledPs.versionCode < newPs.versionCode) { 10869 // Delete data for downgrades 10870 flags &= ~PackageManager.DELETE_KEEP_DATA; 10871 } else { 10872 // Preserve data by setting flag 10873 flags |= PackageManager.DELETE_KEEP_DATA; 10874 } 10875 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10876 allUserHandles, perUserInstalled, outInfo, writeSettings); 10877 if (!ret) { 10878 return false; 10879 } 10880 // writer 10881 synchronized (mPackages) { 10882 // Reinstate the old system package 10883 mSettings.enableSystemPackageLPw(newPs.name); 10884 // Remove any native libraries from the upgraded package. 10885 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10886 } 10887 // Install the system package 10888 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10889 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10890 if (locationIsPrivileged(disabledPs.codePath)) { 10891 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10892 } 10893 10894 final PackageParser.Package newPkg; 10895 try { 10896 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, 10897 null, null); 10898 } catch (PackageManagerException e) { 10899 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10900 return false; 10901 } 10902 10903 // writer 10904 synchronized (mPackages) { 10905 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10906 updatePermissionsLPw(newPkg.packageName, newPkg, 10907 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10908 if (applyUserRestrictions) { 10909 if (DEBUG_REMOVE) { 10910 Slog.d(TAG, "Propagating install state across reinstall"); 10911 } 10912 for (int i = 0; i < allUserHandles.length; i++) { 10913 if (DEBUG_REMOVE) { 10914 Slog.d(TAG, " user " + allUserHandles[i] 10915 + " => " + perUserInstalled[i]); 10916 } 10917 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10918 } 10919 // Regardless of writeSettings we need to ensure that this restriction 10920 // state propagation is persisted 10921 mSettings.writeAllUsersPackageRestrictionsLPr(); 10922 } 10923 // can downgrade to reader here 10924 if (writeSettings) { 10925 mSettings.writeLPr(); 10926 } 10927 } 10928 return true; 10929 } 10930 10931 private boolean deleteInstalledPackageLI(PackageSetting ps, 10932 boolean deleteCodeAndResources, int flags, 10933 int[] allUserHandles, boolean[] perUserInstalled, 10934 PackageRemovedInfo outInfo, boolean writeSettings) { 10935 if (outInfo != null) { 10936 outInfo.uid = ps.appId; 10937 } 10938 10939 // Delete package data from internal structures and also remove data if flag is set 10940 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10941 10942 // Delete application code and resources 10943 if (deleteCodeAndResources && (outInfo != null)) { 10944 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10945 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10946 getAppDexInstructionSets(ps), isMultiArch(ps)); 10947 } 10948 return true; 10949 } 10950 10951 @Override 10952 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10953 int userId) { 10954 mContext.enforceCallingOrSelfPermission( 10955 android.Manifest.permission.DELETE_PACKAGES, null); 10956 synchronized (mPackages) { 10957 PackageSetting ps = mSettings.mPackages.get(packageName); 10958 if (ps == null) { 10959 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10960 return false; 10961 } 10962 if (!ps.getInstalled(userId)) { 10963 // Can't block uninstall for an app that is not installed or enabled. 10964 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10965 return false; 10966 } 10967 ps.setBlockUninstall(blockUninstall, userId); 10968 mSettings.writePackageRestrictionsLPr(userId); 10969 } 10970 return true; 10971 } 10972 10973 @Override 10974 public boolean getBlockUninstallForUser(String packageName, int userId) { 10975 synchronized (mPackages) { 10976 PackageSetting ps = mSettings.mPackages.get(packageName); 10977 if (ps == null) { 10978 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10979 return false; 10980 } 10981 return ps.getBlockUninstall(userId); 10982 } 10983 } 10984 10985 /* 10986 * This method handles package deletion in general 10987 */ 10988 private boolean deletePackageLI(String packageName, UserHandle user, 10989 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10990 int flags, PackageRemovedInfo outInfo, 10991 boolean writeSettings) { 10992 if (packageName == null) { 10993 Slog.w(TAG, "Attempt to delete null packageName."); 10994 return false; 10995 } 10996 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10997 PackageSetting ps; 10998 boolean dataOnly = false; 10999 int removeUser = -1; 11000 int appId = -1; 11001 synchronized (mPackages) { 11002 ps = mSettings.mPackages.get(packageName); 11003 if (ps == null) { 11004 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11005 return false; 11006 } 11007 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11008 && user.getIdentifier() != UserHandle.USER_ALL) { 11009 // The caller is asking that the package only be deleted for a single 11010 // user. To do this, we just mark its uninstalled state and delete 11011 // its data. If this is a system app, we only allow this to happen if 11012 // they have set the special DELETE_SYSTEM_APP which requests different 11013 // semantics than normal for uninstalling system apps. 11014 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11015 ps.setUserState(user.getIdentifier(), 11016 COMPONENT_ENABLED_STATE_DEFAULT, 11017 false, //installed 11018 true, //stopped 11019 true, //notLaunched 11020 false, //hidden 11021 null, null, null, 11022 false // blockUninstall 11023 ); 11024 if (!isSystemApp(ps)) { 11025 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11026 // Other user still have this package installed, so all 11027 // we need to do is clear this user's data and save that 11028 // it is uninstalled. 11029 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11030 removeUser = user.getIdentifier(); 11031 appId = ps.appId; 11032 mSettings.writePackageRestrictionsLPr(removeUser); 11033 } else { 11034 // We need to set it back to 'installed' so the uninstall 11035 // broadcasts will be sent correctly. 11036 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11037 ps.setInstalled(true, user.getIdentifier()); 11038 } 11039 } else { 11040 // This is a system app, so we assume that the 11041 // other users still have this package installed, so all 11042 // we need to do is clear this user's data and save that 11043 // it is uninstalled. 11044 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11045 removeUser = user.getIdentifier(); 11046 appId = ps.appId; 11047 mSettings.writePackageRestrictionsLPr(removeUser); 11048 } 11049 } 11050 } 11051 11052 if (removeUser >= 0) { 11053 // From above, we determined that we are deleting this only 11054 // for a single user. Continue the work here. 11055 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11056 if (outInfo != null) { 11057 outInfo.removedPackage = packageName; 11058 outInfo.removedAppId = appId; 11059 outInfo.removedUsers = new int[] {removeUser}; 11060 } 11061 mInstaller.clearUserData(packageName, removeUser); 11062 removeKeystoreDataIfNeeded(removeUser, appId); 11063 schedulePackageCleaning(packageName, removeUser, false); 11064 return true; 11065 } 11066 11067 if (dataOnly) { 11068 // Delete application data first 11069 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11070 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11071 return true; 11072 } 11073 11074 boolean ret = false; 11075 if (isSystemApp(ps)) { 11076 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11077 // When an updated system application is deleted we delete the existing resources as well and 11078 // fall back to existing code in system partition 11079 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11080 flags, outInfo, writeSettings); 11081 } else { 11082 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11083 // Kill application pre-emptively especially for apps on sd. 11084 killApplication(packageName, ps.appId, "uninstall pkg"); 11085 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11086 allUserHandles, perUserInstalled, 11087 outInfo, writeSettings); 11088 } 11089 11090 return ret; 11091 } 11092 11093 private final class ClearStorageConnection implements ServiceConnection { 11094 IMediaContainerService mContainerService; 11095 11096 @Override 11097 public void onServiceConnected(ComponentName name, IBinder service) { 11098 synchronized (this) { 11099 mContainerService = IMediaContainerService.Stub.asInterface(service); 11100 notifyAll(); 11101 } 11102 } 11103 11104 @Override 11105 public void onServiceDisconnected(ComponentName name) { 11106 } 11107 } 11108 11109 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11110 final boolean mounted; 11111 if (Environment.isExternalStorageEmulated()) { 11112 mounted = true; 11113 } else { 11114 final String status = Environment.getExternalStorageState(); 11115 11116 mounted = status.equals(Environment.MEDIA_MOUNTED) 11117 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11118 } 11119 11120 if (!mounted) { 11121 return; 11122 } 11123 11124 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11125 int[] users; 11126 if (userId == UserHandle.USER_ALL) { 11127 users = sUserManager.getUserIds(); 11128 } else { 11129 users = new int[] { userId }; 11130 } 11131 final ClearStorageConnection conn = new ClearStorageConnection(); 11132 if (mContext.bindServiceAsUser( 11133 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11134 try { 11135 for (int curUser : users) { 11136 long timeout = SystemClock.uptimeMillis() + 5000; 11137 synchronized (conn) { 11138 long now = SystemClock.uptimeMillis(); 11139 while (conn.mContainerService == null && now < timeout) { 11140 try { 11141 conn.wait(timeout - now); 11142 } catch (InterruptedException e) { 11143 } 11144 } 11145 } 11146 if (conn.mContainerService == null) { 11147 return; 11148 } 11149 11150 final UserEnvironment userEnv = new UserEnvironment(curUser); 11151 clearDirectory(conn.mContainerService, 11152 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11153 if (allData) { 11154 clearDirectory(conn.mContainerService, 11155 userEnv.buildExternalStorageAppDataDirs(packageName)); 11156 clearDirectory(conn.mContainerService, 11157 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11158 } 11159 } 11160 } finally { 11161 mContext.unbindService(conn); 11162 } 11163 } 11164 } 11165 11166 @Override 11167 public void clearApplicationUserData(final String packageName, 11168 final IPackageDataObserver observer, final int userId) { 11169 mContext.enforceCallingOrSelfPermission( 11170 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11171 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11172 // Queue up an async operation since the package deletion may take a little while. 11173 mHandler.post(new Runnable() { 11174 public void run() { 11175 mHandler.removeCallbacks(this); 11176 final boolean succeeded; 11177 synchronized (mInstallLock) { 11178 succeeded = clearApplicationUserDataLI(packageName, userId); 11179 } 11180 clearExternalStorageDataSync(packageName, userId, true); 11181 if (succeeded) { 11182 // invoke DeviceStorageMonitor's update method to clear any notifications 11183 DeviceStorageMonitorInternal 11184 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11185 if (dsm != null) { 11186 dsm.checkMemory(); 11187 } 11188 } 11189 if(observer != null) { 11190 try { 11191 observer.onRemoveCompleted(packageName, succeeded); 11192 } catch (RemoteException e) { 11193 Log.i(TAG, "Observer no longer exists."); 11194 } 11195 } //end if observer 11196 } //end run 11197 }); 11198 } 11199 11200 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11201 if (packageName == null) { 11202 Slog.w(TAG, "Attempt to delete null packageName."); 11203 return false; 11204 } 11205 PackageParser.Package p; 11206 boolean dataOnly = false; 11207 final int appId; 11208 synchronized (mPackages) { 11209 p = mPackages.get(packageName); 11210 if (p == null) { 11211 dataOnly = true; 11212 PackageSetting ps = mSettings.mPackages.get(packageName); 11213 if ((ps == null) || (ps.pkg == null)) { 11214 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11215 return false; 11216 } 11217 p = ps.pkg; 11218 } 11219 if (!dataOnly) { 11220 // need to check this only for fully installed applications 11221 if (p == null) { 11222 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11223 return false; 11224 } 11225 final ApplicationInfo applicationInfo = p.applicationInfo; 11226 if (applicationInfo == null) { 11227 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11228 return false; 11229 } 11230 } 11231 if (p != null && p.applicationInfo != null) { 11232 appId = p.applicationInfo.uid; 11233 } else { 11234 appId = -1; 11235 } 11236 } 11237 int retCode = mInstaller.clearUserData(packageName, userId); 11238 if (retCode < 0) { 11239 Slog.w(TAG, "Couldn't remove cache files for package: " 11240 + packageName); 11241 return false; 11242 } 11243 removeKeystoreDataIfNeeded(userId, appId); 11244 return true; 11245 } 11246 11247 /** 11248 * Remove entries from the keystore daemon. Will only remove it if the 11249 * {@code appId} is valid. 11250 */ 11251 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11252 if (appId < 0) { 11253 return; 11254 } 11255 11256 final KeyStore keyStore = KeyStore.getInstance(); 11257 if (keyStore != null) { 11258 if (userId == UserHandle.USER_ALL) { 11259 for (final int individual : sUserManager.getUserIds()) { 11260 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11261 } 11262 } else { 11263 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11264 } 11265 } else { 11266 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11267 } 11268 } 11269 11270 @Override 11271 public void deleteApplicationCacheFiles(final String packageName, 11272 final IPackageDataObserver observer) { 11273 mContext.enforceCallingOrSelfPermission( 11274 android.Manifest.permission.DELETE_CACHE_FILES, null); 11275 // Queue up an async operation since the package deletion may take a little while. 11276 final int userId = UserHandle.getCallingUserId(); 11277 mHandler.post(new Runnable() { 11278 public void run() { 11279 mHandler.removeCallbacks(this); 11280 final boolean succeded; 11281 synchronized (mInstallLock) { 11282 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11283 } 11284 clearExternalStorageDataSync(packageName, userId, false); 11285 if(observer != null) { 11286 try { 11287 observer.onRemoveCompleted(packageName, succeded); 11288 } catch (RemoteException e) { 11289 Log.i(TAG, "Observer no longer exists."); 11290 } 11291 } //end if observer 11292 } //end run 11293 }); 11294 } 11295 11296 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11297 if (packageName == null) { 11298 Slog.w(TAG, "Attempt to delete null packageName."); 11299 return false; 11300 } 11301 PackageParser.Package p; 11302 synchronized (mPackages) { 11303 p = mPackages.get(packageName); 11304 } 11305 if (p == null) { 11306 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11307 return false; 11308 } 11309 final ApplicationInfo applicationInfo = p.applicationInfo; 11310 if (applicationInfo == null) { 11311 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11312 return false; 11313 } 11314 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11315 if (retCode < 0) { 11316 Slog.w(TAG, "Couldn't remove cache files for package: " 11317 + packageName + " u" + userId); 11318 return false; 11319 } 11320 return true; 11321 } 11322 11323 @Override 11324 public void getPackageSizeInfo(final String packageName, int userHandle, 11325 final IPackageStatsObserver observer) { 11326 mContext.enforceCallingOrSelfPermission( 11327 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11328 if (packageName == null) { 11329 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11330 } 11331 11332 PackageStats stats = new PackageStats(packageName, userHandle); 11333 11334 /* 11335 * Queue up an async operation since the package measurement may take a 11336 * little while. 11337 */ 11338 Message msg = mHandler.obtainMessage(INIT_COPY); 11339 msg.obj = new MeasureParams(stats, observer); 11340 mHandler.sendMessage(msg); 11341 } 11342 11343 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11344 PackageStats pStats) { 11345 if (packageName == null) { 11346 Slog.w(TAG, "Attempt to get size of null packageName."); 11347 return false; 11348 } 11349 PackageParser.Package p; 11350 boolean dataOnly = false; 11351 String libDirRoot = null; 11352 String asecPath = null; 11353 PackageSetting ps = null; 11354 synchronized (mPackages) { 11355 p = mPackages.get(packageName); 11356 ps = mSettings.mPackages.get(packageName); 11357 if(p == null) { 11358 dataOnly = true; 11359 if((ps == null) || (ps.pkg == null)) { 11360 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11361 return false; 11362 } 11363 p = ps.pkg; 11364 } 11365 if (ps != null) { 11366 libDirRoot = ps.legacyNativeLibraryPathString; 11367 } 11368 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11369 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11370 if (secureContainerId != null) { 11371 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11372 } 11373 } 11374 } 11375 String publicSrcDir = null; 11376 if(!dataOnly) { 11377 final ApplicationInfo applicationInfo = p.applicationInfo; 11378 if (applicationInfo == null) { 11379 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11380 return false; 11381 } 11382 if (isForwardLocked(p)) { 11383 publicSrcDir = applicationInfo.getBaseResourcePath(); 11384 } 11385 } 11386 // TODO: extend to measure size of split APKs 11387 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11388 // not just the first level. 11389 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11390 // just the primary. 11391 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11392 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11393 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11394 if (res < 0) { 11395 return false; 11396 } 11397 11398 // Fix-up for forward-locked applications in ASEC containers. 11399 if (!isExternal(p)) { 11400 pStats.codeSize += pStats.externalCodeSize; 11401 pStats.externalCodeSize = 0L; 11402 } 11403 11404 return true; 11405 } 11406 11407 11408 @Override 11409 public void addPackageToPreferred(String packageName) { 11410 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11411 } 11412 11413 @Override 11414 public void removePackageFromPreferred(String packageName) { 11415 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11416 } 11417 11418 @Override 11419 public List<PackageInfo> getPreferredPackages(int flags) { 11420 return new ArrayList<PackageInfo>(); 11421 } 11422 11423 private int getUidTargetSdkVersionLockedLPr(int uid) { 11424 Object obj = mSettings.getUserIdLPr(uid); 11425 if (obj instanceof SharedUserSetting) { 11426 final SharedUserSetting sus = (SharedUserSetting) obj; 11427 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11428 final Iterator<PackageSetting> it = sus.packages.iterator(); 11429 while (it.hasNext()) { 11430 final PackageSetting ps = it.next(); 11431 if (ps.pkg != null) { 11432 int v = ps.pkg.applicationInfo.targetSdkVersion; 11433 if (v < vers) vers = v; 11434 } 11435 } 11436 return vers; 11437 } else if (obj instanceof PackageSetting) { 11438 final PackageSetting ps = (PackageSetting) obj; 11439 if (ps.pkg != null) { 11440 return ps.pkg.applicationInfo.targetSdkVersion; 11441 } 11442 } 11443 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11444 } 11445 11446 @Override 11447 public void addPreferredActivity(IntentFilter filter, int match, 11448 ComponentName[] set, ComponentName activity, int userId) { 11449 addPreferredActivityInternal(filter, match, set, activity, true, userId); 11450 } 11451 11452 private void addPreferredActivityInternal(IntentFilter filter, int match, 11453 ComponentName[] set, ComponentName activity, boolean always, int userId) { 11454 // writer 11455 int callingUid = Binder.getCallingUid(); 11456 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11457 if (filter.countActions() == 0) { 11458 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11459 return; 11460 } 11461 synchronized (mPackages) { 11462 if (mContext.checkCallingOrSelfPermission( 11463 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11464 != PackageManager.PERMISSION_GRANTED) { 11465 if (getUidTargetSdkVersionLockedLPr(callingUid) 11466 < Build.VERSION_CODES.FROYO) { 11467 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11468 + callingUid); 11469 return; 11470 } 11471 mContext.enforceCallingOrSelfPermission( 11472 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11473 } 11474 11475 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 11476 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11477 mSettings.editPreferredActivitiesLPw(userId).addFilter( 11478 new PreferredActivity(filter, match, set, activity, always)); 11479 mSettings.writePackageRestrictionsLPr(userId); 11480 } 11481 } 11482 11483 @Override 11484 public void replacePreferredActivity(IntentFilter filter, int match, 11485 ComponentName[] set, ComponentName activity, int userId) { 11486 if (filter.countActions() != 1) { 11487 throw new IllegalArgumentException( 11488 "replacePreferredActivity expects filter to have only 1 action."); 11489 } 11490 if (filter.countDataAuthorities() != 0 11491 || filter.countDataPaths() != 0 11492 || filter.countDataSchemes() > 1 11493 || filter.countDataTypes() != 0) { 11494 throw new IllegalArgumentException( 11495 "replacePreferredActivity expects filter to have no data authorities, " + 11496 "paths, or types; and at most one scheme."); 11497 } 11498 11499 final int callingUid = Binder.getCallingUid(); 11500 enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity"); 11501 final int callingUserId = UserHandle.getUserId(callingUid); 11502 synchronized (mPackages) { 11503 if (mContext.checkCallingOrSelfPermission( 11504 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11505 != PackageManager.PERMISSION_GRANTED) { 11506 if (getUidTargetSdkVersionLockedLPr(callingUid) 11507 < Build.VERSION_CODES.FROYO) { 11508 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11509 + Binder.getCallingUid()); 11510 return; 11511 } 11512 mContext.enforceCallingOrSelfPermission( 11513 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11514 } 11515 11516 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 11517 if (pir != null) { 11518 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 11519 if (filter.countDataSchemes() == 1) { 11520 Uri.Builder builder = new Uri.Builder(); 11521 builder.scheme(filter.getDataScheme(0)); 11522 intent.setData(builder.build()); 11523 } 11524 List<PreferredActivity> matches = pir.queryIntent( 11525 intent, null, true, callingUserId); 11526 if (DEBUG_PREFERRED) { 11527 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 11528 } 11529 for (int i = 0; i < matches.size(); i++) { 11530 PreferredActivity pa = matches.get(i); 11531 if (DEBUG_PREFERRED) { 11532 Slog.i(TAG, "Removing preferred activity " 11533 + pa.mPref.mComponent + ":"); 11534 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11535 } 11536 pir.removeFilter(pa); 11537 } 11538 } 11539 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 11540 } 11541 } 11542 11543 @Override 11544 public void clearPackagePreferredActivities(String packageName) { 11545 final int uid = Binder.getCallingUid(); 11546 // writer 11547 synchronized (mPackages) { 11548 PackageParser.Package pkg = mPackages.get(packageName); 11549 if (pkg == null || pkg.applicationInfo.uid != uid) { 11550 if (mContext.checkCallingOrSelfPermission( 11551 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11552 != PackageManager.PERMISSION_GRANTED) { 11553 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11554 < Build.VERSION_CODES.FROYO) { 11555 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11556 + Binder.getCallingUid()); 11557 return; 11558 } 11559 mContext.enforceCallingOrSelfPermission( 11560 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11561 } 11562 } 11563 11564 int user = UserHandle.getCallingUserId(); 11565 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11566 mSettings.writePackageRestrictionsLPr(user); 11567 scheduleWriteSettingsLocked(); 11568 } 11569 } 11570 } 11571 11572 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11573 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11574 ArrayList<PreferredActivity> removed = null; 11575 boolean changed = false; 11576 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11577 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11578 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11579 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11580 continue; 11581 } 11582 Iterator<PreferredActivity> it = pir.filterIterator(); 11583 while (it.hasNext()) { 11584 PreferredActivity pa = it.next(); 11585 // Mark entry for removal only if it matches the package name 11586 // and the entry is of type "always". 11587 if (packageName == null || 11588 (pa.mPref.mComponent.getPackageName().equals(packageName) 11589 && pa.mPref.mAlways)) { 11590 if (removed == null) { 11591 removed = new ArrayList<PreferredActivity>(); 11592 } 11593 removed.add(pa); 11594 } 11595 } 11596 if (removed != null) { 11597 for (int j=0; j<removed.size(); j++) { 11598 PreferredActivity pa = removed.get(j); 11599 pir.removeFilter(pa); 11600 } 11601 changed = true; 11602 } 11603 } 11604 return changed; 11605 } 11606 11607 @Override 11608 public void resetPreferredActivities(int userId) { 11609 mContext.enforceCallingOrSelfPermission( 11610 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11611 // writer 11612 synchronized (mPackages) { 11613 int user = UserHandle.getCallingUserId(); 11614 clearPackagePreferredActivitiesLPw(null, user); 11615 mSettings.readDefaultPreferredAppsLPw(this, user); 11616 mSettings.writePackageRestrictionsLPr(user); 11617 scheduleWriteSettingsLocked(); 11618 } 11619 } 11620 11621 @Override 11622 public int getPreferredActivities(List<IntentFilter> outFilters, 11623 List<ComponentName> outActivities, String packageName) { 11624 11625 int num = 0; 11626 final int userId = UserHandle.getCallingUserId(); 11627 // reader 11628 synchronized (mPackages) { 11629 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11630 if (pir != null) { 11631 final Iterator<PreferredActivity> it = pir.filterIterator(); 11632 while (it.hasNext()) { 11633 final PreferredActivity pa = it.next(); 11634 if (packageName == null 11635 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11636 && pa.mPref.mAlways)) { 11637 if (outFilters != null) { 11638 outFilters.add(new IntentFilter(pa)); 11639 } 11640 if (outActivities != null) { 11641 outActivities.add(pa.mPref.mComponent); 11642 } 11643 } 11644 } 11645 } 11646 } 11647 11648 return num; 11649 } 11650 11651 @Override 11652 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11653 int userId) { 11654 int callingUid = Binder.getCallingUid(); 11655 if (callingUid != Process.SYSTEM_UID) { 11656 throw new SecurityException( 11657 "addPersistentPreferredActivity can only be run by the system"); 11658 } 11659 if (filter.countActions() == 0) { 11660 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11661 return; 11662 } 11663 synchronized (mPackages) { 11664 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11665 " :"); 11666 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11667 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11668 new PersistentPreferredActivity(filter, activity)); 11669 mSettings.writePackageRestrictionsLPr(userId); 11670 } 11671 } 11672 11673 @Override 11674 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11675 int callingUid = Binder.getCallingUid(); 11676 if (callingUid != Process.SYSTEM_UID) { 11677 throw new SecurityException( 11678 "clearPackagePersistentPreferredActivities can only be run by the system"); 11679 } 11680 ArrayList<PersistentPreferredActivity> removed = null; 11681 boolean changed = false; 11682 synchronized (mPackages) { 11683 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11684 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11685 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11686 .valueAt(i); 11687 if (userId != thisUserId) { 11688 continue; 11689 } 11690 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11691 while (it.hasNext()) { 11692 PersistentPreferredActivity ppa = it.next(); 11693 // Mark entry for removal only if it matches the package name. 11694 if (ppa.mComponent.getPackageName().equals(packageName)) { 11695 if (removed == null) { 11696 removed = new ArrayList<PersistentPreferredActivity>(); 11697 } 11698 removed.add(ppa); 11699 } 11700 } 11701 if (removed != null) { 11702 for (int j=0; j<removed.size(); j++) { 11703 PersistentPreferredActivity ppa = removed.get(j); 11704 ppir.removeFilter(ppa); 11705 } 11706 changed = true; 11707 } 11708 } 11709 11710 if (changed) { 11711 mSettings.writePackageRestrictionsLPr(userId); 11712 } 11713 } 11714 } 11715 11716 @Override 11717 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11718 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11719 mContext.enforceCallingOrSelfPermission( 11720 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11721 int callingUid = Binder.getCallingUid(); 11722 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11723 if (intentFilter.countActions() == 0) { 11724 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11725 return; 11726 } 11727 synchronized (mPackages) { 11728 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11729 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11730 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11731 mSettings.writePackageRestrictionsLPr(sourceUserId); 11732 } 11733 } 11734 11735 @Override 11736 public void addCrossProfileIntentsForPackage(String packageName, 11737 int sourceUserId, int targetUserId) { 11738 mContext.enforceCallingOrSelfPermission( 11739 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11740 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11741 mSettings.writePackageRestrictionsLPr(sourceUserId); 11742 } 11743 11744 @Override 11745 public void removeCrossProfileIntentsForPackage(String packageName, 11746 int sourceUserId, int targetUserId) { 11747 mContext.enforceCallingOrSelfPermission( 11748 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11749 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11750 mSettings.writePackageRestrictionsLPr(sourceUserId); 11751 } 11752 11753 @Override 11754 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11755 int ownerUserId) { 11756 mContext.enforceCallingOrSelfPermission( 11757 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11758 int callingUid = Binder.getCallingUid(); 11759 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11760 int callingUserId = UserHandle.getUserId(callingUid); 11761 synchronized (mPackages) { 11762 CrossProfileIntentResolver resolver = 11763 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11764 HashSet<CrossProfileIntentFilter> set = 11765 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11766 for (CrossProfileIntentFilter filter : set) { 11767 if (filter.getOwnerPackage().equals(ownerPackage) 11768 && filter.getOwnerUserId() == callingUserId) { 11769 resolver.removeFilter(filter); 11770 } 11771 } 11772 mSettings.writePackageRestrictionsLPr(sourceUserId); 11773 } 11774 } 11775 11776 // Enforcing that callingUid is owning pkg on userId 11777 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11778 // The system owns everything. 11779 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11780 return; 11781 } 11782 int callingUserId = UserHandle.getUserId(callingUid); 11783 if (callingUserId != userId) { 11784 throw new SecurityException("calling uid " + callingUid 11785 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11786 + callingUserId); 11787 } 11788 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11789 if (pi == null) { 11790 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11791 + callingUserId); 11792 } 11793 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11794 throw new SecurityException("Calling uid " + callingUid 11795 + " does not own package " + pkg); 11796 } 11797 } 11798 11799 @Override 11800 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11801 Intent intent = new Intent(Intent.ACTION_MAIN); 11802 intent.addCategory(Intent.CATEGORY_HOME); 11803 11804 final int callingUserId = UserHandle.getCallingUserId(); 11805 List<ResolveInfo> list = queryIntentActivities(intent, null, 11806 PackageManager.GET_META_DATA, callingUserId); 11807 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11808 true, false, false, callingUserId); 11809 11810 allHomeCandidates.clear(); 11811 if (list != null) { 11812 for (ResolveInfo ri : list) { 11813 allHomeCandidates.add(ri); 11814 } 11815 } 11816 return (preferred == null || preferred.activityInfo == null) 11817 ? null 11818 : new ComponentName(preferred.activityInfo.packageName, 11819 preferred.activityInfo.name); 11820 } 11821 11822 /** 11823 * Check if calling UID is the current home app. This handles both the case 11824 * where the user has selected a specific home app, and where there is only 11825 * one home app. 11826 */ 11827 public boolean checkCallerIsHomeApp() { 11828 final Intent intent = new Intent(Intent.ACTION_MAIN); 11829 intent.addCategory(Intent.CATEGORY_HOME); 11830 11831 final int callingUid = Binder.getCallingUid(); 11832 final int callingUserId = UserHandle.getCallingUserId(); 11833 final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId); 11834 final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true, 11835 false, false, callingUserId); 11836 11837 if (preferredHome != null) { 11838 if (callingUid == preferredHome.activityInfo.applicationInfo.uid) { 11839 return true; 11840 } 11841 } else { 11842 for (ResolveInfo info : allHomes) { 11843 if (callingUid == info.activityInfo.applicationInfo.uid) { 11844 return true; 11845 } 11846 } 11847 } 11848 11849 return false; 11850 } 11851 11852 /** 11853 * Enforce that calling UID is the current home app. This handles both the 11854 * case where the user has selected a specific home app, and where there is 11855 * only one home app. 11856 */ 11857 public void enforceCallerIsHomeApp() { 11858 if (!checkCallerIsHomeApp()) { 11859 throw new SecurityException("Caller is not currently selected home app"); 11860 } 11861 } 11862 11863 @Override 11864 public void setApplicationEnabledSetting(String appPackageName, 11865 int newState, int flags, int userId, String callingPackage) { 11866 if (!sUserManager.exists(userId)) return; 11867 if (callingPackage == null) { 11868 callingPackage = Integer.toString(Binder.getCallingUid()); 11869 } 11870 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11871 } 11872 11873 @Override 11874 public void setComponentEnabledSetting(ComponentName componentName, 11875 int newState, int flags, int userId) { 11876 if (!sUserManager.exists(userId)) return; 11877 setEnabledSetting(componentName.getPackageName(), 11878 componentName.getClassName(), newState, flags, userId, null); 11879 } 11880 11881 private void setEnabledSetting(final String packageName, String className, int newState, 11882 final int flags, int userId, String callingPackage) { 11883 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11884 || newState == COMPONENT_ENABLED_STATE_ENABLED 11885 || newState == COMPONENT_ENABLED_STATE_DISABLED 11886 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11887 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11888 throw new IllegalArgumentException("Invalid new component state: " 11889 + newState); 11890 } 11891 PackageSetting pkgSetting; 11892 final int uid = Binder.getCallingUid(); 11893 final int permission = mContext.checkCallingOrSelfPermission( 11894 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11895 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11896 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11897 boolean sendNow = false; 11898 boolean isApp = (className == null); 11899 String componentName = isApp ? packageName : className; 11900 int packageUid = -1; 11901 ArrayList<String> components; 11902 11903 // writer 11904 synchronized (mPackages) { 11905 pkgSetting = mSettings.mPackages.get(packageName); 11906 if (pkgSetting == null) { 11907 if (className == null) { 11908 throw new IllegalArgumentException( 11909 "Unknown package: " + packageName); 11910 } 11911 throw new IllegalArgumentException( 11912 "Unknown component: " + packageName 11913 + "/" + className); 11914 } 11915 // Allow root and verify that userId is not being specified by a different user 11916 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11917 throw new SecurityException( 11918 "Permission Denial: attempt to change component state from pid=" 11919 + Binder.getCallingPid() 11920 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11921 } 11922 if (className == null) { 11923 // We're dealing with an application/package level state change 11924 if (pkgSetting.getEnabled(userId) == newState) { 11925 // Nothing to do 11926 return; 11927 } 11928 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11929 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11930 // Don't care about who enables an app. 11931 callingPackage = null; 11932 } 11933 pkgSetting.setEnabled(newState, userId, callingPackage); 11934 // pkgSetting.pkg.mSetEnabled = newState; 11935 } else { 11936 // We're dealing with a component level state change 11937 // First, verify that this is a valid class name. 11938 PackageParser.Package pkg = pkgSetting.pkg; 11939 if (pkg == null || !pkg.hasComponentClassName(className)) { 11940 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11941 throw new IllegalArgumentException("Component class " + className 11942 + " does not exist in " + packageName); 11943 } else { 11944 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11945 + className + " does not exist in " + packageName); 11946 } 11947 } 11948 switch (newState) { 11949 case COMPONENT_ENABLED_STATE_ENABLED: 11950 if (!pkgSetting.enableComponentLPw(className, userId)) { 11951 return; 11952 } 11953 break; 11954 case COMPONENT_ENABLED_STATE_DISABLED: 11955 if (!pkgSetting.disableComponentLPw(className, userId)) { 11956 return; 11957 } 11958 break; 11959 case COMPONENT_ENABLED_STATE_DEFAULT: 11960 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11961 return; 11962 } 11963 break; 11964 default: 11965 Slog.e(TAG, "Invalid new component state: " + newState); 11966 return; 11967 } 11968 } 11969 mSettings.writePackageRestrictionsLPr(userId); 11970 components = mPendingBroadcasts.get(userId, packageName); 11971 final boolean newPackage = components == null; 11972 if (newPackage) { 11973 components = new ArrayList<String>(); 11974 } 11975 if (!components.contains(componentName)) { 11976 components.add(componentName); 11977 } 11978 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11979 sendNow = true; 11980 // Purge entry from pending broadcast list if another one exists already 11981 // since we are sending one right away. 11982 mPendingBroadcasts.remove(userId, packageName); 11983 } else { 11984 if (newPackage) { 11985 mPendingBroadcasts.put(userId, packageName, components); 11986 } 11987 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11988 // Schedule a message 11989 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11990 } 11991 } 11992 } 11993 11994 long callingId = Binder.clearCallingIdentity(); 11995 try { 11996 if (sendNow) { 11997 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11998 sendPackageChangedBroadcast(packageName, 11999 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12000 } 12001 } finally { 12002 Binder.restoreCallingIdentity(callingId); 12003 } 12004 } 12005 12006 private void sendPackageChangedBroadcast(String packageName, 12007 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12008 if (DEBUG_INSTALL) 12009 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12010 + componentNames); 12011 Bundle extras = new Bundle(4); 12012 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12013 String nameList[] = new String[componentNames.size()]; 12014 componentNames.toArray(nameList); 12015 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12016 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12017 extras.putInt(Intent.EXTRA_UID, packageUid); 12018 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12019 new int[] {UserHandle.getUserId(packageUid)}); 12020 } 12021 12022 @Override 12023 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12024 if (!sUserManager.exists(userId)) return; 12025 final int uid = Binder.getCallingUid(); 12026 final int permission = mContext.checkCallingOrSelfPermission( 12027 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12028 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12029 enforceCrossUserPermission(uid, userId, true, "stop package"); 12030 // writer 12031 synchronized (mPackages) { 12032 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12033 uid, userId)) { 12034 scheduleWritePackageRestrictionsLocked(userId); 12035 } 12036 } 12037 } 12038 12039 @Override 12040 public String getInstallerPackageName(String packageName) { 12041 // reader 12042 synchronized (mPackages) { 12043 return mSettings.getInstallerPackageNameLPr(packageName); 12044 } 12045 } 12046 12047 @Override 12048 public int getApplicationEnabledSetting(String packageName, int userId) { 12049 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12050 int uid = Binder.getCallingUid(); 12051 enforceCrossUserPermission(uid, userId, false, "get enabled"); 12052 // reader 12053 synchronized (mPackages) { 12054 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12055 } 12056 } 12057 12058 @Override 12059 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12060 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12061 int uid = Binder.getCallingUid(); 12062 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 12063 // reader 12064 synchronized (mPackages) { 12065 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12066 } 12067 } 12068 12069 @Override 12070 public void enterSafeMode() { 12071 enforceSystemOrRoot("Only the system can request entering safe mode"); 12072 12073 if (!mSystemReady) { 12074 mSafeMode = true; 12075 } 12076 } 12077 12078 @Override 12079 public void systemReady() { 12080 mSystemReady = true; 12081 12082 // Read the compatibilty setting when the system is ready. 12083 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12084 mContext.getContentResolver(), 12085 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12086 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12087 if (DEBUG_SETTINGS) { 12088 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12089 } 12090 12091 synchronized (mPackages) { 12092 // Verify that all of the preferred activity components actually 12093 // exist. It is possible for applications to be updated and at 12094 // that point remove a previously declared activity component that 12095 // had been set as a preferred activity. We try to clean this up 12096 // the next time we encounter that preferred activity, but it is 12097 // possible for the user flow to never be able to return to that 12098 // situation so here we do a sanity check to make sure we haven't 12099 // left any junk around. 12100 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12101 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12102 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12103 removed.clear(); 12104 for (PreferredActivity pa : pir.filterSet()) { 12105 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12106 removed.add(pa); 12107 } 12108 } 12109 if (removed.size() > 0) { 12110 for (int r=0; r<removed.size(); r++) { 12111 PreferredActivity pa = removed.get(r); 12112 Slog.w(TAG, "Removing dangling preferred activity: " 12113 + pa.mPref.mComponent); 12114 pir.removeFilter(pa); 12115 } 12116 mSettings.writePackageRestrictionsLPr( 12117 mSettings.mPreferredActivities.keyAt(i)); 12118 } 12119 } 12120 } 12121 sUserManager.systemReady(); 12122 } 12123 12124 @Override 12125 public boolean isSafeMode() { 12126 return mSafeMode; 12127 } 12128 12129 @Override 12130 public boolean hasSystemUidErrors() { 12131 return mHasSystemUidErrors; 12132 } 12133 12134 static String arrayToString(int[] array) { 12135 StringBuffer buf = new StringBuffer(128); 12136 buf.append('['); 12137 if (array != null) { 12138 for (int i=0; i<array.length; i++) { 12139 if (i > 0) buf.append(", "); 12140 buf.append(array[i]); 12141 } 12142 } 12143 buf.append(']'); 12144 return buf.toString(); 12145 } 12146 12147 static class DumpState { 12148 public static final int DUMP_LIBS = 1 << 0; 12149 public static final int DUMP_FEATURES = 1 << 1; 12150 public static final int DUMP_RESOLVERS = 1 << 2; 12151 public static final int DUMP_PERMISSIONS = 1 << 3; 12152 public static final int DUMP_PACKAGES = 1 << 4; 12153 public static final int DUMP_SHARED_USERS = 1 << 5; 12154 public static final int DUMP_MESSAGES = 1 << 6; 12155 public static final int DUMP_PROVIDERS = 1 << 7; 12156 public static final int DUMP_VERIFIERS = 1 << 8; 12157 public static final int DUMP_PREFERRED = 1 << 9; 12158 public static final int DUMP_PREFERRED_XML = 1 << 10; 12159 public static final int DUMP_KEYSETS = 1 << 11; 12160 public static final int DUMP_VERSION = 1 << 12; 12161 public static final int DUMP_INSTALLS = 1 << 13; 12162 12163 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12164 12165 private int mTypes; 12166 12167 private int mOptions; 12168 12169 private boolean mTitlePrinted; 12170 12171 private SharedUserSetting mSharedUser; 12172 12173 public boolean isDumping(int type) { 12174 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12175 return true; 12176 } 12177 12178 return (mTypes & type) != 0; 12179 } 12180 12181 public void setDump(int type) { 12182 mTypes |= type; 12183 } 12184 12185 public boolean isOptionEnabled(int option) { 12186 return (mOptions & option) != 0; 12187 } 12188 12189 public void setOptionEnabled(int option) { 12190 mOptions |= option; 12191 } 12192 12193 public boolean onTitlePrinted() { 12194 final boolean printed = mTitlePrinted; 12195 mTitlePrinted = true; 12196 return printed; 12197 } 12198 12199 public boolean getTitlePrinted() { 12200 return mTitlePrinted; 12201 } 12202 12203 public void setTitlePrinted(boolean enabled) { 12204 mTitlePrinted = enabled; 12205 } 12206 12207 public SharedUserSetting getSharedUser() { 12208 return mSharedUser; 12209 } 12210 12211 public void setSharedUser(SharedUserSetting user) { 12212 mSharedUser = user; 12213 } 12214 } 12215 12216 @Override 12217 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12218 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12219 != PackageManager.PERMISSION_GRANTED) { 12220 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12221 + Binder.getCallingPid() 12222 + ", uid=" + Binder.getCallingUid() 12223 + " without permission " 12224 + android.Manifest.permission.DUMP); 12225 return; 12226 } 12227 12228 DumpState dumpState = new DumpState(); 12229 boolean fullPreferred = false; 12230 boolean checkin = false; 12231 12232 String packageName = null; 12233 12234 int opti = 0; 12235 while (opti < args.length) { 12236 String opt = args[opti]; 12237 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12238 break; 12239 } 12240 opti++; 12241 if ("-a".equals(opt)) { 12242 // Right now we only know how to print all. 12243 } else if ("-h".equals(opt)) { 12244 pw.println("Package manager dump options:"); 12245 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12246 pw.println(" --checkin: dump for a checkin"); 12247 pw.println(" -f: print details of intent filters"); 12248 pw.println(" -h: print this help"); 12249 pw.println(" cmd may be one of:"); 12250 pw.println(" l[ibraries]: list known shared libraries"); 12251 pw.println(" f[ibraries]: list device features"); 12252 pw.println(" k[eysets]: print known keysets"); 12253 pw.println(" r[esolvers]: dump intent resolvers"); 12254 pw.println(" perm[issions]: dump permissions"); 12255 pw.println(" pref[erred]: print preferred package settings"); 12256 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12257 pw.println(" prov[iders]: dump content providers"); 12258 pw.println(" p[ackages]: dump installed packages"); 12259 pw.println(" s[hared-users]: dump shared user IDs"); 12260 pw.println(" m[essages]: print collected runtime messages"); 12261 pw.println(" v[erifiers]: print package verifier info"); 12262 pw.println(" version: print database version info"); 12263 pw.println(" write: write current settings now"); 12264 pw.println(" <package.name>: info about given package"); 12265 pw.println(" installs: details about install sessions"); 12266 return; 12267 } else if ("--checkin".equals(opt)) { 12268 checkin = true; 12269 } else if ("-f".equals(opt)) { 12270 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12271 } else { 12272 pw.println("Unknown argument: " + opt + "; use -h for help"); 12273 } 12274 } 12275 12276 // Is the caller requesting to dump a particular piece of data? 12277 if (opti < args.length) { 12278 String cmd = args[opti]; 12279 opti++; 12280 // Is this a package name? 12281 if ("android".equals(cmd) || cmd.contains(".")) { 12282 packageName = cmd; 12283 // When dumping a single package, we always dump all of its 12284 // filter information since the amount of data will be reasonable. 12285 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12286 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12287 dumpState.setDump(DumpState.DUMP_LIBS); 12288 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12289 dumpState.setDump(DumpState.DUMP_FEATURES); 12290 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12291 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12292 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12293 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12294 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12295 dumpState.setDump(DumpState.DUMP_PREFERRED); 12296 } else if ("preferred-xml".equals(cmd)) { 12297 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12298 if (opti < args.length && "--full".equals(args[opti])) { 12299 fullPreferred = true; 12300 opti++; 12301 } 12302 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12303 dumpState.setDump(DumpState.DUMP_PACKAGES); 12304 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12305 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12306 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12307 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12308 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12309 dumpState.setDump(DumpState.DUMP_MESSAGES); 12310 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12311 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12312 } else if ("version".equals(cmd)) { 12313 dumpState.setDump(DumpState.DUMP_VERSION); 12314 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12315 dumpState.setDump(DumpState.DUMP_KEYSETS); 12316 } else if ("write".equals(cmd)) { 12317 synchronized (mPackages) { 12318 mSettings.writeLPr(); 12319 pw.println("Settings written."); 12320 return; 12321 } 12322 } else if ("installs".equals(cmd)) { 12323 dumpState.setDump(DumpState.DUMP_INSTALLS); 12324 } 12325 } 12326 12327 if (checkin) { 12328 pw.println("vers,1"); 12329 } 12330 12331 // reader 12332 synchronized (mPackages) { 12333 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12334 if (!checkin) { 12335 if (dumpState.onTitlePrinted()) 12336 pw.println(); 12337 pw.println("Database versions:"); 12338 pw.print(" SDK Version:"); 12339 pw.print(" internal="); 12340 pw.print(mSettings.mInternalSdkPlatform); 12341 pw.print(" external="); 12342 pw.println(mSettings.mExternalSdkPlatform); 12343 pw.print(" DB Version:"); 12344 pw.print(" internal="); 12345 pw.print(mSettings.mInternalDatabaseVersion); 12346 pw.print(" external="); 12347 pw.println(mSettings.mExternalDatabaseVersion); 12348 } 12349 } 12350 12351 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12352 if (!checkin) { 12353 if (dumpState.onTitlePrinted()) 12354 pw.println(); 12355 pw.println("Verifiers:"); 12356 pw.print(" Required: "); 12357 pw.print(mRequiredVerifierPackage); 12358 pw.print(" (uid="); 12359 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12360 pw.println(")"); 12361 } else if (mRequiredVerifierPackage != null) { 12362 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12363 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12364 } 12365 } 12366 12367 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12368 boolean printedHeader = false; 12369 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12370 while (it.hasNext()) { 12371 String name = it.next(); 12372 SharedLibraryEntry ent = mSharedLibraries.get(name); 12373 if (!checkin) { 12374 if (!printedHeader) { 12375 if (dumpState.onTitlePrinted()) 12376 pw.println(); 12377 pw.println("Libraries:"); 12378 printedHeader = true; 12379 } 12380 pw.print(" "); 12381 } else { 12382 pw.print("lib,"); 12383 } 12384 pw.print(name); 12385 if (!checkin) { 12386 pw.print(" -> "); 12387 } 12388 if (ent.path != null) { 12389 if (!checkin) { 12390 pw.print("(jar) "); 12391 pw.print(ent.path); 12392 } else { 12393 pw.print(",jar,"); 12394 pw.print(ent.path); 12395 } 12396 } else { 12397 if (!checkin) { 12398 pw.print("(apk) "); 12399 pw.print(ent.apk); 12400 } else { 12401 pw.print(",apk,"); 12402 pw.print(ent.apk); 12403 } 12404 } 12405 pw.println(); 12406 } 12407 } 12408 12409 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12410 if (dumpState.onTitlePrinted()) 12411 pw.println(); 12412 if (!checkin) { 12413 pw.println("Features:"); 12414 } 12415 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12416 while (it.hasNext()) { 12417 String name = it.next(); 12418 if (!checkin) { 12419 pw.print(" "); 12420 } else { 12421 pw.print("feat,"); 12422 } 12423 pw.println(name); 12424 } 12425 } 12426 12427 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12428 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12429 : "Activity Resolver Table:", " ", packageName, 12430 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12431 dumpState.setTitlePrinted(true); 12432 } 12433 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12434 : "Receiver Resolver Table:", " ", packageName, 12435 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12436 dumpState.setTitlePrinted(true); 12437 } 12438 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12439 : "Service Resolver Table:", " ", packageName, 12440 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12441 dumpState.setTitlePrinted(true); 12442 } 12443 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12444 : "Provider Resolver Table:", " ", packageName, 12445 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12446 dumpState.setTitlePrinted(true); 12447 } 12448 } 12449 12450 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12451 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12452 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12453 int user = mSettings.mPreferredActivities.keyAt(i); 12454 if (pir.dump(pw, 12455 dumpState.getTitlePrinted() 12456 ? "\nPreferred Activities User " + user + ":" 12457 : "Preferred Activities User " + user + ":", " ", 12458 packageName, true)) { 12459 dumpState.setTitlePrinted(true); 12460 } 12461 } 12462 } 12463 12464 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12465 pw.flush(); 12466 FileOutputStream fout = new FileOutputStream(fd); 12467 BufferedOutputStream str = new BufferedOutputStream(fout); 12468 XmlSerializer serializer = new FastXmlSerializer(); 12469 try { 12470 serializer.setOutput(str, "utf-8"); 12471 serializer.startDocument(null, true); 12472 serializer.setFeature( 12473 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12474 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12475 serializer.endDocument(); 12476 serializer.flush(); 12477 } catch (IllegalArgumentException e) { 12478 pw.println("Failed writing: " + e); 12479 } catch (IllegalStateException e) { 12480 pw.println("Failed writing: " + e); 12481 } catch (IOException e) { 12482 pw.println("Failed writing: " + e); 12483 } 12484 } 12485 12486 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12487 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12488 if (packageName == null) { 12489 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12490 if (iperm == 0) { 12491 if (dumpState.onTitlePrinted()) 12492 pw.println(); 12493 pw.println("AppOp Permissions:"); 12494 } 12495 pw.print(" AppOp Permission "); 12496 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12497 pw.println(":"); 12498 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12499 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12500 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12501 } 12502 } 12503 } 12504 } 12505 12506 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12507 boolean printedSomething = false; 12508 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12509 if (packageName != null && !packageName.equals(p.info.packageName)) { 12510 continue; 12511 } 12512 if (!printedSomething) { 12513 if (dumpState.onTitlePrinted()) 12514 pw.println(); 12515 pw.println("Registered ContentProviders:"); 12516 printedSomething = true; 12517 } 12518 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12519 pw.print(" "); pw.println(p.toString()); 12520 } 12521 printedSomething = false; 12522 for (Map.Entry<String, PackageParser.Provider> entry : 12523 mProvidersByAuthority.entrySet()) { 12524 PackageParser.Provider p = entry.getValue(); 12525 if (packageName != null && !packageName.equals(p.info.packageName)) { 12526 continue; 12527 } 12528 if (!printedSomething) { 12529 if (dumpState.onTitlePrinted()) 12530 pw.println(); 12531 pw.println("ContentProvider Authorities:"); 12532 printedSomething = true; 12533 } 12534 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12535 pw.print(" "); pw.println(p.toString()); 12536 if (p.info != null && p.info.applicationInfo != null) { 12537 final String appInfo = p.info.applicationInfo.toString(); 12538 pw.print(" applicationInfo="); pw.println(appInfo); 12539 } 12540 } 12541 } 12542 12543 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12544 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12545 } 12546 12547 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12548 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12549 } 12550 12551 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12552 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12553 } 12554 12555 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) { 12556 if (dumpState.onTitlePrinted()) pw.println(); 12557 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12558 } 12559 12560 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12561 if (dumpState.onTitlePrinted()) pw.println(); 12562 mSettings.dumpReadMessagesLPr(pw, dumpState); 12563 12564 pw.println(); 12565 pw.println("Package warning messages:"); 12566 final File fname = getSettingsProblemFile(); 12567 FileInputStream in = null; 12568 try { 12569 in = new FileInputStream(fname); 12570 final int avail = in.available(); 12571 final byte[] data = new byte[avail]; 12572 in.read(data); 12573 pw.print(new String(data)); 12574 } catch (FileNotFoundException e) { 12575 } catch (IOException e) { 12576 } finally { 12577 if (in != null) { 12578 try { 12579 in.close(); 12580 } catch (IOException e) { 12581 } 12582 } 12583 } 12584 } 12585 } 12586 } 12587 12588 // ------- apps on sdcard specific code ------- 12589 static final boolean DEBUG_SD_INSTALL = false; 12590 12591 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12592 12593 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12594 12595 private boolean mMediaMounted = false; 12596 12597 private String getEncryptKey() { 12598 try { 12599 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12600 SD_ENCRYPTION_KEYSTORE_NAME); 12601 if (sdEncKey == null) { 12602 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12603 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12604 if (sdEncKey == null) { 12605 Slog.e(TAG, "Failed to create encryption keys"); 12606 return null; 12607 } 12608 } 12609 return sdEncKey; 12610 } catch (NoSuchAlgorithmException nsae) { 12611 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12612 return null; 12613 } catch (IOException ioe) { 12614 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12615 return null; 12616 } 12617 12618 } 12619 12620 /* package */static String getTempContainerId() { 12621 int tmpIdx = 1; 12622 String list[] = PackageHelper.getSecureContainerList(); 12623 if (list != null) { 12624 for (final String name : list) { 12625 // Ignore null and non-temporary container entries 12626 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12627 continue; 12628 } 12629 12630 String subStr = name.substring(mTempContainerPrefix.length()); 12631 try { 12632 int cid = Integer.parseInt(subStr); 12633 if (cid >= tmpIdx) { 12634 tmpIdx = cid + 1; 12635 } 12636 } catch (NumberFormatException e) { 12637 } 12638 } 12639 } 12640 return mTempContainerPrefix + tmpIdx; 12641 } 12642 12643 /* 12644 * Update media status on PackageManager. 12645 */ 12646 @Override 12647 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12648 int callingUid = Binder.getCallingUid(); 12649 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12650 throw new SecurityException("Media status can only be updated by the system"); 12651 } 12652 // reader; this apparently protects mMediaMounted, but should probably 12653 // be a different lock in that case. 12654 synchronized (mPackages) { 12655 Log.i(TAG, "Updating external media status from " 12656 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12657 + (mediaStatus ? "mounted" : "unmounted")); 12658 if (DEBUG_SD_INSTALL) 12659 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12660 + ", mMediaMounted=" + mMediaMounted); 12661 if (mediaStatus == mMediaMounted) { 12662 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12663 : 0, -1); 12664 mHandler.sendMessage(msg); 12665 return; 12666 } 12667 mMediaMounted = mediaStatus; 12668 } 12669 // Queue up an async operation since the package installation may take a 12670 // little while. 12671 mHandler.post(new Runnable() { 12672 public void run() { 12673 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12674 } 12675 }); 12676 } 12677 12678 /** 12679 * Called by MountService when the initial ASECs to scan are available. 12680 * Should block until all the ASEC containers are finished being scanned. 12681 */ 12682 public void scanAvailableAsecs() { 12683 updateExternalMediaStatusInner(true, false, false); 12684 if (mShouldRestoreconData) { 12685 SELinuxMMAC.setRestoreconDone(); 12686 mShouldRestoreconData = false; 12687 } 12688 } 12689 12690 /* 12691 * Collect information of applications on external media, map them against 12692 * existing containers and update information based on current mount status. 12693 * Please note that we always have to report status if reportStatus has been 12694 * set to true especially when unloading packages. 12695 */ 12696 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12697 boolean externalStorage) { 12698 // Collection of uids 12699 int uidArr[] = null; 12700 // Collection of stale containers 12701 HashSet<String> removeCids = new HashSet<String>(); 12702 // Collection of packages on external media with valid containers. 12703 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12704 // Get list of secure containers. 12705 final String list[] = PackageHelper.getSecureContainerList(); 12706 if (list == null || list.length == 0) { 12707 Log.i(TAG, "No secure containers on sdcard"); 12708 } else { 12709 // Process list of secure containers and categorize them 12710 // as active or stale based on their package internal state. 12711 int uidList[] = new int[list.length]; 12712 int num = 0; 12713 // reader 12714 synchronized (mPackages) { 12715 for (String cid : list) { 12716 if (DEBUG_SD_INSTALL) 12717 Log.i(TAG, "Processing container " + cid); 12718 String pkgName = getAsecPackageName(cid); 12719 if (pkgName == null) { 12720 if (DEBUG_SD_INSTALL) 12721 Log.i(TAG, "Container : " + cid + " stale"); 12722 removeCids.add(cid); 12723 continue; 12724 } 12725 if (DEBUG_SD_INSTALL) 12726 Log.i(TAG, "Looking for pkg : " + pkgName); 12727 12728 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12729 if (ps == null) { 12730 Log.i(TAG, "Deleting container with no matching settings " + cid); 12731 removeCids.add(cid); 12732 continue; 12733 } 12734 12735 /* 12736 * Skip packages that are not external if we're unmounting 12737 * external storage. 12738 */ 12739 if (externalStorage && !isMounted && !isExternal(ps)) { 12740 continue; 12741 } 12742 12743 final AsecInstallArgs args = new AsecInstallArgs(cid, 12744 getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps)); 12745 // The package status is changed only if the code path 12746 // matches between settings and the container id. 12747 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12748 if (DEBUG_SD_INSTALL) { 12749 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12750 + " at code path: " + ps.codePathString); 12751 } 12752 12753 // We do have a valid package installed on sdcard 12754 processCids.put(args, ps.codePathString); 12755 final int uid = ps.appId; 12756 if (uid != -1) { 12757 uidList[num++] = uid; 12758 } 12759 } else { 12760 Log.i(TAG, "Deleting stale container for " + cid); 12761 removeCids.add(cid); 12762 } 12763 } 12764 } 12765 12766 if (num > 0) { 12767 // Sort uid list 12768 Arrays.sort(uidList, 0, num); 12769 // Throw away duplicates 12770 uidArr = new int[num]; 12771 uidArr[0] = uidList[0]; 12772 int di = 0; 12773 for (int i = 1; i < num; i++) { 12774 if (uidList[i - 1] != uidList[i]) { 12775 uidArr[di++] = uidList[i]; 12776 } 12777 } 12778 } 12779 } 12780 // Process packages with valid entries. 12781 if (isMounted) { 12782 if (DEBUG_SD_INSTALL) 12783 Log.i(TAG, "Loading packages"); 12784 loadMediaPackages(processCids, uidArr, removeCids); 12785 startCleaningPackages(); 12786 } else { 12787 if (DEBUG_SD_INSTALL) 12788 Log.i(TAG, "Unloading packages"); 12789 unloadMediaPackages(processCids, uidArr, reportStatus); 12790 } 12791 } 12792 12793 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12794 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12795 int size = pkgList.size(); 12796 if (size > 0) { 12797 // Send broadcasts here 12798 Bundle extras = new Bundle(); 12799 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12800 .toArray(new String[size])); 12801 if (uidArr != null) { 12802 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12803 } 12804 if (replacing) { 12805 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12806 } 12807 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12808 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12809 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12810 } 12811 } 12812 12813 /* 12814 * Look at potentially valid container ids from processCids If package 12815 * information doesn't match the one on record or package scanning fails, 12816 * the cid is added to list of removeCids. We currently don't delete stale 12817 * containers. 12818 */ 12819 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12820 HashSet<String> removeCids) { 12821 ArrayList<String> pkgList = new ArrayList<String>(); 12822 Set<AsecInstallArgs> keys = processCids.keySet(); 12823 boolean doGc = false; 12824 for (AsecInstallArgs args : keys) { 12825 String codePath = processCids.get(args); 12826 if (DEBUG_SD_INSTALL) 12827 Log.i(TAG, "Loading container : " + args.cid); 12828 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12829 try { 12830 // Make sure there are no container errors first. 12831 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12832 Slog.e(TAG, "Failed to mount cid : " + args.cid 12833 + " when installing from sdcard"); 12834 continue; 12835 } 12836 // Check code path here. 12837 if (codePath == null || !codePath.equals(args.getCodePath())) { 12838 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12839 + " does not match one in settings " + codePath); 12840 continue; 12841 } 12842 // Parse package 12843 int parseFlags = mDefParseFlags; 12844 if (args.isExternal()) { 12845 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12846 } 12847 if (args.isFwdLocked()) { 12848 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12849 } 12850 12851 doGc = true; 12852 synchronized (mInstallLock) { 12853 PackageParser.Package pkg = null; 12854 try { 12855 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null, null); 12856 } catch (PackageManagerException e) { 12857 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12858 } 12859 // Scan the package 12860 if (pkg != null) { 12861 /* 12862 * TODO why is the lock being held? doPostInstall is 12863 * called in other places without the lock. This needs 12864 * to be straightened out. 12865 */ 12866 // writer 12867 synchronized (mPackages) { 12868 retCode = PackageManager.INSTALL_SUCCEEDED; 12869 pkgList.add(pkg.packageName); 12870 // Post process args 12871 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12872 pkg.applicationInfo.uid); 12873 } 12874 } else { 12875 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12876 } 12877 } 12878 12879 } finally { 12880 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12881 // Don't destroy container here. Wait till gc clears things 12882 // up. 12883 removeCids.add(args.cid); 12884 } 12885 } 12886 } 12887 // writer 12888 synchronized (mPackages) { 12889 // If the platform SDK has changed since the last time we booted, 12890 // we need to re-grant app permission to catch any new ones that 12891 // appear. This is really a hack, and means that apps can in some 12892 // cases get permissions that the user didn't initially explicitly 12893 // allow... it would be nice to have some better way to handle 12894 // this situation. 12895 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12896 if (regrantPermissions) 12897 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12898 + mSdkVersion + "; regranting permissions for external storage"); 12899 mSettings.mExternalSdkPlatform = mSdkVersion; 12900 12901 // Make sure group IDs have been assigned, and any permission 12902 // changes in other apps are accounted for 12903 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12904 | (regrantPermissions 12905 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12906 : 0)); 12907 12908 mSettings.updateExternalDatabaseVersion(); 12909 12910 // can downgrade to reader 12911 // Persist settings 12912 mSettings.writeLPr(); 12913 } 12914 // Send a broadcast to let everyone know we are done processing 12915 if (pkgList.size() > 0) { 12916 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12917 } 12918 // Force gc to avoid any stale parser references that we might have. 12919 if (doGc) { 12920 Runtime.getRuntime().gc(); 12921 } 12922 // List stale containers and destroy stale temporary containers. 12923 if (removeCids != null) { 12924 for (String cid : removeCids) { 12925 if (cid.startsWith(mTempContainerPrefix)) { 12926 Log.i(TAG, "Destroying stale temporary container " + cid); 12927 PackageHelper.destroySdDir(cid); 12928 } else { 12929 Log.w(TAG, "Container " + cid + " is stale"); 12930 } 12931 } 12932 } 12933 } 12934 12935 /* 12936 * Utility method to unload a list of specified containers 12937 */ 12938 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12939 // Just unmount all valid containers. 12940 for (AsecInstallArgs arg : cidArgs) { 12941 synchronized (mInstallLock) { 12942 arg.doPostDeleteLI(false); 12943 } 12944 } 12945 } 12946 12947 /* 12948 * Unload packages mounted on external media. This involves deleting package 12949 * data from internal structures, sending broadcasts about diabled packages, 12950 * gc'ing to free up references, unmounting all secure containers 12951 * corresponding to packages on external media, and posting a 12952 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12953 * that we always have to post this message if status has been requested no 12954 * matter what. 12955 */ 12956 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12957 final boolean reportStatus) { 12958 if (DEBUG_SD_INSTALL) 12959 Log.i(TAG, "unloading media packages"); 12960 ArrayList<String> pkgList = new ArrayList<String>(); 12961 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12962 final Set<AsecInstallArgs> keys = processCids.keySet(); 12963 for (AsecInstallArgs args : keys) { 12964 String pkgName = args.getPackageName(); 12965 if (DEBUG_SD_INSTALL) 12966 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12967 // Delete package internally 12968 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12969 synchronized (mInstallLock) { 12970 boolean res = deletePackageLI(pkgName, null, false, null, null, 12971 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12972 if (res) { 12973 pkgList.add(pkgName); 12974 } else { 12975 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12976 failedList.add(args); 12977 } 12978 } 12979 } 12980 12981 // reader 12982 synchronized (mPackages) { 12983 // We didn't update the settings after removing each package; 12984 // write them now for all packages. 12985 mSettings.writeLPr(); 12986 } 12987 12988 // We have to absolutely send UPDATED_MEDIA_STATUS only 12989 // after confirming that all the receivers processed the ordered 12990 // broadcast when packages get disabled, force a gc to clean things up. 12991 // and unload all the containers. 12992 if (pkgList.size() > 0) { 12993 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12994 new IIntentReceiver.Stub() { 12995 public void performReceive(Intent intent, int resultCode, String data, 12996 Bundle extras, boolean ordered, boolean sticky, 12997 int sendingUser) throws RemoteException { 12998 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12999 reportStatus ? 1 : 0, 1, keys); 13000 mHandler.sendMessage(msg); 13001 } 13002 }); 13003 } else { 13004 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 13005 keys); 13006 mHandler.sendMessage(msg); 13007 } 13008 } 13009 13010 /** Binder call */ 13011 @Override 13012 public void movePackage(final String packageName, final IPackageMoveObserver observer, 13013 final int flags) { 13014 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 13015 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 13016 int returnCode = PackageManager.MOVE_SUCCEEDED; 13017 int currFlags = 0; 13018 int newFlags = 0; 13019 // reader 13020 synchronized (mPackages) { 13021 PackageParser.Package pkg = mPackages.get(packageName); 13022 if (pkg == null) { 13023 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13024 } else { 13025 // Disable moving fwd locked apps and system packages 13026 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 13027 Slog.w(TAG, "Cannot move system application"); 13028 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13029 } else if (pkg.mOperationPending) { 13030 Slog.w(TAG, "Attempt to move package which has pending operations"); 13031 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13032 } else { 13033 // Find install location first 13034 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13035 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13036 Slog.w(TAG, "Ambigous flags specified for move location."); 13037 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13038 } else { 13039 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 13040 : PackageManager.INSTALL_INTERNAL; 13041 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 13042 : PackageManager.INSTALL_INTERNAL; 13043 13044 if (newFlags == currFlags) { 13045 Slog.w(TAG, "No move required. Trying to move to same location"); 13046 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13047 } else { 13048 if (isForwardLocked(pkg)) { 13049 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13050 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13051 } 13052 } 13053 } 13054 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13055 pkg.mOperationPending = true; 13056 } 13057 } 13058 } 13059 13060 /* 13061 * TODO this next block probably shouldn't be inside the lock. We 13062 * can't guarantee these won't change after this is fired off 13063 * anyway. 13064 */ 13065 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13066 processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false), 13067 returnCode); 13068 } else { 13069 Message msg = mHandler.obtainMessage(INIT_COPY); 13070 final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 13071 final boolean multiArch = isMultiArch(pkg.applicationInfo); 13072 InstallArgs srcArgs = createInstallArgsForExisting(currFlags, 13073 pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(), 13074 pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch); 13075 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 13076 instructionSets, pkg.applicationInfo.uid, user, multiArch); 13077 msg.obj = mp; 13078 mHandler.sendMessage(msg); 13079 } 13080 } 13081 } 13082 13083 private void processPendingMove(final MoveParams mp, final int currentStatus) { 13084 // Queue up an async operation since the package deletion may take a 13085 // little while. 13086 mHandler.post(new Runnable() { 13087 public void run() { 13088 // TODO fix this; this does nothing. 13089 mHandler.removeCallbacks(this); 13090 int returnCode = currentStatus; 13091 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 13092 int uidArr[] = null; 13093 ArrayList<String> pkgList = null; 13094 synchronized (mPackages) { 13095 PackageParser.Package pkg = mPackages.get(mp.packageName); 13096 if (pkg == null) { 13097 Slog.w(TAG, " Package " + mp.packageName 13098 + " doesn't exist. Aborting move"); 13099 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13100 } else if (!mp.srcArgs.getCodePath().equals( 13101 pkg.applicationInfo.getCodePath())) { 13102 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 13103 + mp.srcArgs.getCodePath() + " to " 13104 + pkg.applicationInfo.getCodePath() 13105 + " Aborting move and returning error"); 13106 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13107 } else { 13108 uidArr = new int[] { 13109 pkg.applicationInfo.uid 13110 }; 13111 pkgList = new ArrayList<String>(); 13112 pkgList.add(mp.packageName); 13113 } 13114 } 13115 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13116 // Send resources unavailable broadcast 13117 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 13118 // Update package code and resource paths 13119 synchronized (mInstallLock) { 13120 synchronized (mPackages) { 13121 PackageParser.Package pkg = mPackages.get(mp.packageName); 13122 // Recheck for package again. 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 13130 + " code path changed from " + mp.srcArgs.getCodePath() 13131 + " to " + pkg.applicationInfo.getCodePath() 13132 + " Aborting move and returning error"); 13133 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13134 } else { 13135 final String oldCodePath = pkg.codePath; 13136 final String newCodePath = mp.targetArgs.getCodePath(); 13137 final String newResPath = mp.targetArgs.getResourcePath(); 13138 // TODO: This assumes the new style of installation. 13139 // should we look at legacyNativeLibraryPath ? 13140 final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath(); 13141 final File newNativeDir = new File(newNativeRoot); 13142 13143 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 13144 // TODO(multiArch): Fix this so that it looks at the existing 13145 // recorded CPU abis from the package. There's no need for a separate 13146 // round of ABI scanning here. 13147 NativeLibraryHelper.Handle handle = null; 13148 try { 13149 handle = NativeLibraryHelper.Handle.create( 13150 new File(newCodePath)); 13151 final int abi = NativeLibraryHelper.findSupportedAbi( 13152 handle, Build.SUPPORTED_ABIS); 13153 if (abi >= 0) { 13154 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 13155 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 13156 } 13157 } catch (IOException ioe) { 13158 Slog.w(TAG, "Unable to extract native libs for package :" 13159 + mp.packageName, ioe); 13160 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13161 } finally { 13162 IoUtils.closeQuietly(handle); 13163 } 13164 } 13165 13166 final int[] users = sUserManager.getUserIds(); 13167 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13168 for (int user : users) { 13169 // TODO(multiArch): Fix this so that it links to the 13170 // correct directory. We're currently pointing to root. but we 13171 // must point to the arch specific subdirectory (if applicable). 13172 // 13173 // TODO(multiArch): Bogus reference to nativeLibraryDir. 13174 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 13175 newNativeRoot, user) < 0) { 13176 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13177 } 13178 } 13179 } 13180 13181 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13182 pkg.codePath = newCodePath; 13183 pkg.baseCodePath = newCodePath; 13184 // Move dex files around 13185 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 13186 // Moving of dex files failed. Set 13187 // error code and abort move. 13188 pkg.codePath = oldCodePath; 13189 pkg.baseCodePath = oldCodePath; 13190 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13191 } 13192 } 13193 13194 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13195 pkg.applicationInfo.setCodePath(newCodePath); 13196 pkg.applicationInfo.setBaseCodePath(newCodePath); 13197 pkg.applicationInfo.setSplitCodePaths(null); 13198 pkg.applicationInfo.setResourcePath(newResPath); 13199 pkg.applicationInfo.setBaseResourcePath(newResPath); 13200 pkg.applicationInfo.setSplitResourcePaths(null); 13201 13202 PackageSetting ps = (PackageSetting) pkg.mExtras; 13203 ps.codePath = new File(pkg.applicationInfo.getCodePath()); 13204 ps.codePathString = ps.codePath.getPath(); 13205 ps.resourcePath = new File(pkg.applicationInfo.getResourcePath()); 13206 ps.resourcePathString = ps.resourcePath.getPath(); 13207 13208 // Note that we don't have to recalculate the primary and secondary 13209 // CPU ABIs because they must already have been calculated during the 13210 // initial install of the app. 13211 ps.legacyNativeLibraryPathString = null; 13212 13213 // Set the application info flag 13214 // correctly. 13215 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 13216 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13217 } else { 13218 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13219 } 13220 ps.setFlags(pkg.applicationInfo.flags); 13221 mAppDirs.remove(oldCodePath); 13222 mAppDirs.put(newCodePath, pkg); 13223 // Persist settings 13224 mSettings.writeLPr(); 13225 } 13226 } 13227 } 13228 } 13229 // Send resources available broadcast 13230 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13231 } 13232 } 13233 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13234 // Clean up failed installation 13235 if (mp.targetArgs != null) { 13236 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 13237 -1); 13238 } 13239 } else { 13240 // Force a gc to clear things up. 13241 Runtime.getRuntime().gc(); 13242 // Delete older code 13243 synchronized (mInstallLock) { 13244 mp.srcArgs.doPostDeleteLI(true); 13245 } 13246 } 13247 13248 // Allow more operations on this file if we didn't fail because 13249 // an operation was already pending for this package. 13250 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 13251 synchronized (mPackages) { 13252 PackageParser.Package pkg = mPackages.get(mp.packageName); 13253 if (pkg != null) { 13254 pkg.mOperationPending = false; 13255 } 13256 } 13257 } 13258 13259 IPackageMoveObserver observer = mp.observer; 13260 if (observer != null) { 13261 try { 13262 observer.packageMoved(mp.packageName, returnCode); 13263 } catch (RemoteException e) { 13264 Log.i(TAG, "Observer no longer exists."); 13265 } 13266 } 13267 } 13268 }); 13269 } 13270 13271 @Override 13272 public boolean setInstallLocation(int loc) { 13273 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13274 null); 13275 if (getInstallLocation() == loc) { 13276 return true; 13277 } 13278 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13279 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13280 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13281 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13282 return true; 13283 } 13284 return false; 13285 } 13286 13287 @Override 13288 public int getInstallLocation() { 13289 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13290 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13291 PackageHelper.APP_INSTALL_AUTO); 13292 } 13293 13294 /** Called by UserManagerService */ 13295 void cleanUpUserLILPw(int userHandle) { 13296 mDirtyUsers.remove(userHandle); 13297 mSettings.removeUserLPw(userHandle); 13298 mPendingBroadcasts.remove(userHandle); 13299 if (mInstaller != null) { 13300 // Technically, we shouldn't be doing this with the package lock 13301 // held. However, this is very rare, and there is already so much 13302 // other disk I/O going on, that we'll let it slide for now. 13303 mInstaller.removeUserDataDirs(userHandle); 13304 } 13305 mUserNeedsBadging.delete(userHandle); 13306 } 13307 13308 /** Called by UserManagerService */ 13309 void createNewUserLILPw(int userHandle, File path) { 13310 if (mInstaller != null) { 13311 mInstaller.createUserConfig(userHandle); 13312 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13313 } 13314 } 13315 13316 @Override 13317 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13318 mContext.enforceCallingOrSelfPermission( 13319 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13320 "Only package verification agents can read the verifier device identity"); 13321 13322 synchronized (mPackages) { 13323 return mSettings.getVerifierDeviceIdentityLPw(); 13324 } 13325 } 13326 13327 @Override 13328 public void setPermissionEnforced(String permission, boolean enforced) { 13329 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13330 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13331 synchronized (mPackages) { 13332 if (mSettings.mReadExternalStorageEnforced == null 13333 || mSettings.mReadExternalStorageEnforced != enforced) { 13334 mSettings.mReadExternalStorageEnforced = enforced; 13335 mSettings.writeLPr(); 13336 } 13337 } 13338 // kill any non-foreground processes so we restart them and 13339 // grant/revoke the GID. 13340 final IActivityManager am = ActivityManagerNative.getDefault(); 13341 if (am != null) { 13342 final long token = Binder.clearCallingIdentity(); 13343 try { 13344 am.killProcessesBelowForeground("setPermissionEnforcement"); 13345 } catch (RemoteException e) { 13346 } finally { 13347 Binder.restoreCallingIdentity(token); 13348 } 13349 } 13350 } else { 13351 throw new IllegalArgumentException("No selective enforcement for " + permission); 13352 } 13353 } 13354 13355 @Override 13356 @Deprecated 13357 public boolean isPermissionEnforced(String permission) { 13358 return true; 13359 } 13360 13361 @Override 13362 public boolean isStorageLow() { 13363 final long token = Binder.clearCallingIdentity(); 13364 try { 13365 final DeviceStorageMonitorInternal 13366 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13367 if (dsm != null) { 13368 return dsm.isMemoryLow(); 13369 } else { 13370 return false; 13371 } 13372 } finally { 13373 Binder.restoreCallingIdentity(token); 13374 } 13375 } 13376 13377 @Override 13378 public IPackageInstaller getPackageInstaller() { 13379 return mInstallerService; 13380 } 13381 13382 private boolean userNeedsBadging(int userId) { 13383 int index = mUserNeedsBadging.indexOfKey(userId); 13384 if (index < 0) { 13385 final UserInfo userInfo; 13386 final long token = Binder.clearCallingIdentity(); 13387 try { 13388 userInfo = sUserManager.getUserInfo(userId); 13389 } finally { 13390 Binder.restoreCallingIdentity(token); 13391 } 13392 final boolean b; 13393 if (userInfo != null && userInfo.isManagedProfile()) { 13394 b = true; 13395 } else { 13396 b = false; 13397 } 13398 mUserNeedsBadging.put(userId, b); 13399 return b; 13400 } 13401 return mUserNeedsBadging.valueAt(index); 13402 } 13403 13404 @Override 13405 public KeySetHandle getKeySetByAlias(String packageName, String alias) { 13406 if (packageName == null || alias == null) { 13407 return null; 13408 } 13409 synchronized(mPackages) { 13410 final PackageParser.Package pkg = mPackages.get(packageName); 13411 if (pkg == null) { 13412 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13413 throw new IllegalArgumentException("Unknown package: " + packageName); 13414 } 13415 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13416 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13417 throw new SecurityException("May not access KeySets defined by" 13418 + " aliases in other applications."); 13419 } 13420 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13421 return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias); 13422 } 13423 } 13424 13425 @Override 13426 public KeySetHandle getSigningKeySet(String packageName) { 13427 if (packageName == null) { 13428 return null; 13429 } 13430 synchronized(mPackages) { 13431 final PackageParser.Package pkg = mPackages.get(packageName); 13432 if (pkg == null) { 13433 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13434 throw new IllegalArgumentException("Unknown package: " + packageName); 13435 } 13436 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13437 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13438 throw new SecurityException("May not access signing KeySet of other apps."); 13439 } 13440 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13441 return ksms.getSigningKeySetByPackageNameLPr(packageName); 13442 } 13443 } 13444 13445 @Override 13446 public boolean isPackageSignedByKeySet(String packageName, IBinder ks) { 13447 if (packageName == null || ks == null) { 13448 return false; 13449 } 13450 synchronized(mPackages) { 13451 final PackageParser.Package pkg = mPackages.get(packageName); 13452 if (pkg == null) { 13453 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13454 throw new IllegalArgumentException("Unknown package: " + packageName); 13455 } 13456 if (ks instanceof KeySetHandle) { 13457 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13458 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks); 13459 } 13460 return false; 13461 } 13462 } 13463 13464 @Override 13465 public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) { 13466 if (packageName == null || ks == null) { 13467 return false; 13468 } 13469 synchronized(mPackages) { 13470 final PackageParser.Package pkg = mPackages.get(packageName); 13471 if (pkg == null) { 13472 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13473 throw new IllegalArgumentException("Unknown package: " + packageName); 13474 } 13475 if (ks instanceof KeySetHandle) { 13476 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13477 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks); 13478 } 13479 return false; 13480 } 13481 } 13482} 13483