PackageManagerService.java revision 9d35c5dc79650c5e3781af15f8df5b0d8d078306
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 com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 53import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 54import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 55import static com.android.internal.util.ArrayUtils.appendInt; 56import static com.android.internal.util.ArrayUtils.removeInt; 57 58import android.util.ArrayMap; 59 60import com.android.internal.R; 61import com.android.internal.app.IMediaContainerService; 62import com.android.internal.app.ResolverActivity; 63import com.android.internal.content.NativeLibraryHelper; 64import com.android.internal.content.PackageHelper; 65import com.android.internal.os.IParcelFileDescriptorFactory; 66import com.android.internal.util.ArrayUtils; 67import com.android.internal.util.FastPrintWriter; 68import com.android.internal.util.FastXmlSerializer; 69import com.android.internal.util.IndentingPrintWriter; 70import com.android.server.EventLogTags; 71import com.android.server.IntentResolver; 72import com.android.server.LocalServices; 73import com.android.server.ServiceThread; 74import com.android.server.SystemConfig; 75import com.android.server.Watchdog; 76import com.android.server.pm.Settings.DatabaseVersion; 77import com.android.server.storage.DeviceStorageMonitorInternal; 78 79import org.xmlpull.v1.XmlSerializer; 80 81import android.app.ActivityManager; 82import android.app.ActivityManagerNative; 83import android.app.AppGlobals; 84import android.app.IActivityManager; 85import android.app.admin.IDevicePolicyManager; 86import android.app.backup.IBackupManager; 87import android.content.BroadcastReceiver; 88import android.content.ComponentName; 89import android.content.Context; 90import android.content.IIntentReceiver; 91import android.content.Intent; 92import android.content.IntentFilter; 93import android.content.IntentSender; 94import android.content.IntentSender.SendIntentException; 95import android.content.ServiceConnection; 96import android.content.pm.ActivityInfo; 97import android.content.pm.ApplicationInfo; 98import android.content.pm.FeatureInfo; 99import android.content.pm.IPackageDataObserver; 100import android.content.pm.IPackageDeleteObserver; 101import android.content.pm.IPackageDeleteObserver2; 102import android.content.pm.IPackageInstallObserver2; 103import android.content.pm.IPackageInstaller; 104import android.content.pm.IPackageManager; 105import android.content.pm.IPackageMoveObserver; 106import android.content.pm.IPackageStatsObserver; 107import android.content.pm.InstrumentationInfo; 108import android.content.pm.KeySet; 109import android.content.pm.ManifestDigest; 110import android.content.pm.PackageCleanItem; 111import android.content.pm.PackageInfo; 112import android.content.pm.PackageInfoLite; 113import android.content.pm.PackageInstaller; 114import android.content.pm.PackageManager; 115import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 116import android.content.pm.PackageParser.ActivityIntentInfo; 117import android.content.pm.PackageParser.PackageLite; 118import android.content.pm.PackageParser.PackageParserException; 119import android.content.pm.PackageParser; 120import android.content.pm.PackageStats; 121import android.content.pm.PackageUserState; 122import android.content.pm.ParceledListSlice; 123import android.content.pm.PermissionGroupInfo; 124import android.content.pm.PermissionInfo; 125import android.content.pm.ProviderInfo; 126import android.content.pm.ResolveInfo; 127import android.content.pm.ServiceInfo; 128import android.content.pm.Signature; 129import android.content.pm.UserInfo; 130import android.content.pm.VerificationParams; 131import android.content.pm.VerifierDeviceIdentity; 132import android.content.pm.VerifierInfo; 133import android.content.res.Resources; 134import android.hardware.display.DisplayManager; 135import android.net.Uri; 136import android.os.Binder; 137import android.os.Build; 138import android.os.Bundle; 139import android.os.Environment; 140import android.os.Environment.UserEnvironment; 141import android.os.storage.StorageManager; 142import android.os.Debug; 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.Objects; 206import java.util.Set; 207import java.util.concurrent.atomic.AtomicBoolean; 208import java.util.concurrent.atomic.AtomicLong; 209 210import dalvik.system.DexFile; 211import dalvik.system.StaleDexCacheError; 212import dalvik.system.VMRuntime; 213 214import libcore.io.IoUtils; 215import libcore.util.EmptyArray; 216 217/** 218 * Keep track of all those .apks everywhere. 219 * 220 * This is very central to the platform's security; please run the unit 221 * tests whenever making modifications here: 222 * 223mmm frameworks/base/tests/AndroidTests 224adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 225adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 226 * 227 * {@hide} 228 */ 229public class PackageManagerService extends IPackageManager.Stub { 230 static final String TAG = "PackageManager"; 231 static final boolean DEBUG_SETTINGS = false; 232 static final boolean DEBUG_PREFERRED = false; 233 static final boolean DEBUG_UPGRADE = false; 234 private static final boolean DEBUG_INSTALL = false; 235 private static final boolean DEBUG_REMOVE = false; 236 private static final boolean DEBUG_BROADCASTS = false; 237 private static final boolean DEBUG_SHOW_INFO = false; 238 private static final boolean DEBUG_PACKAGE_INFO = false; 239 private static final boolean DEBUG_INTENT_MATCHING = false; 240 private static final boolean DEBUG_PACKAGE_SCANNING = false; 241 private static final boolean DEBUG_VERIFY = false; 242 private static final boolean DEBUG_DEXOPT = false; 243 private static final boolean DEBUG_ABI_SELECTION = false; 244 245 private static final int RADIO_UID = Process.PHONE_UID; 246 private static final int LOG_UID = Process.LOG_UID; 247 private static final int NFC_UID = Process.NFC_UID; 248 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 249 private static final int SHELL_UID = Process.SHELL_UID; 250 251 // Cap the size of permission trees that 3rd party apps can define 252 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 253 254 // Suffix used during package installation when copying/moving 255 // package apks to install directory. 256 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 257 258 static final int SCAN_NO_DEX = 1<<1; 259 static final int SCAN_FORCE_DEX = 1<<2; 260 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 261 static final int SCAN_NEW_INSTALL = 1<<4; 262 static final int SCAN_NO_PATHS = 1<<5; 263 static final int SCAN_UPDATE_TIME = 1<<6; 264 static final int SCAN_DEFER_DEX = 1<<7; 265 static final int SCAN_BOOTING = 1<<8; 266 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 267 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 268 static final int SCAN_REPLACING = 1<<11; 269 270 static final int REMOVE_CHATTY = 1<<16; 271 272 /** 273 * Timeout (in milliseconds) after which the watchdog should declare that 274 * our handler thread is wedged. The usual default for such things is one 275 * minute but we sometimes do very lengthy I/O operations on this thread, 276 * such as installing multi-gigabyte applications, so ours needs to be longer. 277 */ 278 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 279 280 /** 281 * Whether verification is enabled by default. 282 */ 283 private static final boolean DEFAULT_VERIFY_ENABLE = true; 284 285 /** 286 * The default maximum time to wait for the verification agent to return in 287 * milliseconds. 288 */ 289 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 290 291 /** 292 * The default response for package verification timeout. 293 * 294 * This can be either PackageManager.VERIFICATION_ALLOW or 295 * PackageManager.VERIFICATION_REJECT. 296 */ 297 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 298 299 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 300 301 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 302 DEFAULT_CONTAINER_PACKAGE, 303 "com.android.defcontainer.DefaultContainerService"); 304 305 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 306 307 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 308 309 private static String sPreferredInstructionSet; 310 311 final ServiceThread mHandlerThread; 312 313 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 314 private static final String IDMAP_SUFFIX = "@idmap"; 315 316 final PackageHandler mHandler; 317 318 /** 319 * Messages for {@link #mHandler} that need to wait for system ready before 320 * being dispatched. 321 */ 322 private ArrayList<Message> mPostSystemReadyMessages; 323 324 final int mSdkVersion = Build.VERSION.SDK_INT; 325 326 final Context mContext; 327 final boolean mFactoryTest; 328 final boolean mOnlyCore; 329 final boolean mLazyDexOpt; 330 final DisplayMetrics mMetrics; 331 final int mDefParseFlags; 332 final String[] mSeparateProcesses; 333 334 // This is where all application persistent data goes. 335 final File mAppDataDir; 336 337 // This is where all application persistent data goes for secondary users. 338 final File mUserAppDataDir; 339 340 /** The location for ASEC container files on internal storage. */ 341 final String mAsecInternalPath; 342 343 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 344 // LOCK HELD. Can be called with mInstallLock held. 345 final Installer mInstaller; 346 347 /** Directory where installed third-party apps stored */ 348 final File mAppInstallDir; 349 350 /** 351 * Directory to which applications installed internally have their 352 * 32 bit native libraries copied. 353 */ 354 private File mAppLib32InstallDir; 355 356 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 357 // apps. 358 final File mDrmAppPrivateInstallDir; 359 360 // ---------------------------------------------------------------- 361 362 // Lock for state used when installing and doing other long running 363 // operations. Methods that must be called with this lock held have 364 // the suffix "LI". 365 final Object mInstallLock = new Object(); 366 367 // ---------------------------------------------------------------- 368 369 // Keys are String (package name), values are Package. This also serves 370 // as the lock for the global state. Methods that must be called with 371 // this lock held have the prefix "LP". 372 final HashMap<String, PackageParser.Package> mPackages = 373 new HashMap<String, PackageParser.Package>(); 374 375 // Tracks available target package names -> overlay package paths. 376 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 377 new HashMap<String, HashMap<String, PackageParser.Package>>(); 378 379 final Settings mSettings; 380 boolean mRestoredSettings; 381 382 // System configuration read by SystemConfig. 383 final int[] mGlobalGids; 384 final SparseArray<HashSet<String>> mSystemPermissions; 385 final HashMap<String, FeatureInfo> mAvailableFeatures; 386 387 // If mac_permissions.xml was found for seinfo labeling. 388 boolean mFoundPolicyFile; 389 390 // If a recursive restorecon of /data/data/<pkg> is needed. 391 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 392 393 public static final class SharedLibraryEntry { 394 public final String path; 395 public final String apk; 396 397 SharedLibraryEntry(String _path, String _apk) { 398 path = _path; 399 apk = _apk; 400 } 401 } 402 403 // Currently known shared libraries. 404 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 405 new HashMap<String, SharedLibraryEntry>(); 406 407 // All available activities, for your resolving pleasure. 408 final ActivityIntentResolver mActivities = 409 new ActivityIntentResolver(); 410 411 // All available receivers, for your resolving pleasure. 412 final ActivityIntentResolver mReceivers = 413 new ActivityIntentResolver(); 414 415 // All available services, for your resolving pleasure. 416 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 417 418 // All available providers, for your resolving pleasure. 419 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 420 421 // Mapping from provider base names (first directory in content URI codePath) 422 // to the provider information. 423 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 424 new HashMap<String, PackageParser.Provider>(); 425 426 // Mapping from instrumentation class names to info about them. 427 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 428 new HashMap<ComponentName, PackageParser.Instrumentation>(); 429 430 // Mapping from permission names to info about them. 431 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 432 new HashMap<String, PackageParser.PermissionGroup>(); 433 434 // Packages whose data we have transfered into another package, thus 435 // should no longer exist. 436 final HashSet<String> mTransferedPackages = new HashSet<String>(); 437 438 // Broadcast actions that are only available to the system. 439 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 440 441 /** List of packages waiting for verification. */ 442 final SparseArray<PackageVerificationState> mPendingVerification 443 = new SparseArray<PackageVerificationState>(); 444 445 /** Set of packages associated with each app op permission. */ 446 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 447 448 final PackageInstallerService mInstallerService; 449 450 HashSet<PackageParser.Package> mDeferredDexOpt = null; 451 452 // Cache of users who need badging. 453 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 454 455 /** Token for keys in mPendingVerification. */ 456 private int mPendingVerificationToken = 0; 457 458 volatile boolean mSystemReady; 459 volatile boolean mSafeMode; 460 volatile boolean mHasSystemUidErrors; 461 462 ApplicationInfo mAndroidApplication; 463 final ActivityInfo mResolveActivity = new ActivityInfo(); 464 final ResolveInfo mResolveInfo = new ResolveInfo(); 465 ComponentName mResolveComponentName; 466 PackageParser.Package mPlatformPackage; 467 ComponentName mCustomResolverComponentName; 468 469 boolean mResolverReplaced = false; 470 471 // Set of pending broadcasts for aggregating enable/disable of components. 472 static class PendingPackageBroadcasts { 473 // for each user id, a map of <package name -> components within that package> 474 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 475 476 public PendingPackageBroadcasts() { 477 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 478 } 479 480 public ArrayList<String> get(int userId, String packageName) { 481 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 482 return packages.get(packageName); 483 } 484 485 public void put(int userId, String packageName, ArrayList<String> components) { 486 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 487 packages.put(packageName, components); 488 } 489 490 public void remove(int userId, String packageName) { 491 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 492 if (packages != null) { 493 packages.remove(packageName); 494 } 495 } 496 497 public void remove(int userId) { 498 mUidMap.remove(userId); 499 } 500 501 public int userIdCount() { 502 return mUidMap.size(); 503 } 504 505 public int userIdAt(int n) { 506 return mUidMap.keyAt(n); 507 } 508 509 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 510 return mUidMap.get(userId); 511 } 512 513 public int size() { 514 // total number of pending broadcast entries across all userIds 515 int num = 0; 516 for (int i = 0; i< mUidMap.size(); i++) { 517 num += mUidMap.valueAt(i).size(); 518 } 519 return num; 520 } 521 522 public void clear() { 523 mUidMap.clear(); 524 } 525 526 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 527 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 528 if (map == null) { 529 map = new HashMap<String, ArrayList<String>>(); 530 mUidMap.put(userId, map); 531 } 532 return map; 533 } 534 } 535 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 536 537 // Service Connection to remote media container service to copy 538 // package uri's from external media onto secure containers 539 // or internal storage. 540 private IMediaContainerService mContainerService = null; 541 542 static final int SEND_PENDING_BROADCAST = 1; 543 static final int MCS_BOUND = 3; 544 static final int END_COPY = 4; 545 static final int INIT_COPY = 5; 546 static final int MCS_UNBIND = 6; 547 static final int START_CLEANING_PACKAGE = 7; 548 static final int FIND_INSTALL_LOC = 8; 549 static final int POST_INSTALL = 9; 550 static final int MCS_RECONNECT = 10; 551 static final int MCS_GIVE_UP = 11; 552 static final int UPDATED_MEDIA_STATUS = 12; 553 static final int WRITE_SETTINGS = 13; 554 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 555 static final int PACKAGE_VERIFIED = 15; 556 static final int CHECK_PENDING_VERIFICATION = 16; 557 558 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 559 560 // Delay time in millisecs 561 static final int BROADCAST_DELAY = 10 * 1000; 562 563 static UserManagerService sUserManager; 564 565 // Stores a list of users whose package restrictions file needs to be updated 566 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 567 568 final private DefaultContainerConnection mDefContainerConn = 569 new DefaultContainerConnection(); 570 class DefaultContainerConnection implements ServiceConnection { 571 public void onServiceConnected(ComponentName name, IBinder service) { 572 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 573 IMediaContainerService imcs = 574 IMediaContainerService.Stub.asInterface(service); 575 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 576 } 577 578 public void onServiceDisconnected(ComponentName name) { 579 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 580 } 581 }; 582 583 // Recordkeeping of restore-after-install operations that are currently in flight 584 // between the Package Manager and the Backup Manager 585 class PostInstallData { 586 public InstallArgs args; 587 public PackageInstalledInfo res; 588 589 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 590 args = _a; 591 res = _r; 592 } 593 }; 594 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 595 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 596 597 private final String mRequiredVerifierPackage; 598 599 private final PackageUsage mPackageUsage = new PackageUsage(); 600 601 private class PackageUsage { 602 private static final int WRITE_INTERVAL 603 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 604 605 private final Object mFileLock = new Object(); 606 private final AtomicLong mLastWritten = new AtomicLong(0); 607 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 608 609 private boolean mIsHistoricalPackageUsageAvailable = true; 610 611 boolean isHistoricalPackageUsageAvailable() { 612 return mIsHistoricalPackageUsageAvailable; 613 } 614 615 void write(boolean force) { 616 if (force) { 617 writeInternal(); 618 return; 619 } 620 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 621 && !DEBUG_DEXOPT) { 622 return; 623 } 624 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 625 new Thread("PackageUsage_DiskWriter") { 626 @Override 627 public void run() { 628 try { 629 writeInternal(); 630 } finally { 631 mBackgroundWriteRunning.set(false); 632 } 633 } 634 }.start(); 635 } 636 } 637 638 private void writeInternal() { 639 synchronized (mPackages) { 640 synchronized (mFileLock) { 641 AtomicFile file = getFile(); 642 FileOutputStream f = null; 643 try { 644 f = file.startWrite(); 645 BufferedOutputStream out = new BufferedOutputStream(f); 646 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 647 StringBuilder sb = new StringBuilder(); 648 for (PackageParser.Package pkg : mPackages.values()) { 649 if (pkg.mLastPackageUsageTimeInMills == 0) { 650 continue; 651 } 652 sb.setLength(0); 653 sb.append(pkg.packageName); 654 sb.append(' '); 655 sb.append((long)pkg.mLastPackageUsageTimeInMills); 656 sb.append('\n'); 657 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 658 } 659 out.flush(); 660 file.finishWrite(f); 661 } catch (IOException e) { 662 if (f != null) { 663 file.failWrite(f); 664 } 665 Log.e(TAG, "Failed to write package usage times", e); 666 } 667 } 668 } 669 mLastWritten.set(SystemClock.elapsedRealtime()); 670 } 671 672 void readLP() { 673 synchronized (mFileLock) { 674 AtomicFile file = getFile(); 675 BufferedInputStream in = null; 676 try { 677 in = new BufferedInputStream(file.openRead()); 678 StringBuffer sb = new StringBuffer(); 679 while (true) { 680 String packageName = readToken(in, sb, ' '); 681 if (packageName == null) { 682 break; 683 } 684 String timeInMillisString = readToken(in, sb, '\n'); 685 if (timeInMillisString == null) { 686 throw new IOException("Failed to find last usage time for package " 687 + packageName); 688 } 689 PackageParser.Package pkg = mPackages.get(packageName); 690 if (pkg == null) { 691 continue; 692 } 693 long timeInMillis; 694 try { 695 timeInMillis = Long.parseLong(timeInMillisString.toString()); 696 } catch (NumberFormatException e) { 697 throw new IOException("Failed to parse " + timeInMillisString 698 + " as a long.", e); 699 } 700 pkg.mLastPackageUsageTimeInMills = timeInMillis; 701 } 702 } catch (FileNotFoundException expected) { 703 mIsHistoricalPackageUsageAvailable = false; 704 } catch (IOException e) { 705 Log.w(TAG, "Failed to read package usage times", e); 706 } finally { 707 IoUtils.closeQuietly(in); 708 } 709 } 710 mLastWritten.set(SystemClock.elapsedRealtime()); 711 } 712 713 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 714 throws IOException { 715 sb.setLength(0); 716 while (true) { 717 int ch = in.read(); 718 if (ch == -1) { 719 if (sb.length() == 0) { 720 return null; 721 } 722 throw new IOException("Unexpected EOF"); 723 } 724 if (ch == endOfToken) { 725 return sb.toString(); 726 } 727 sb.append((char)ch); 728 } 729 } 730 731 private AtomicFile getFile() { 732 File dataDir = Environment.getDataDirectory(); 733 File systemDir = new File(dataDir, "system"); 734 File fname = new File(systemDir, "package-usage.list"); 735 return new AtomicFile(fname); 736 } 737 } 738 739 class PackageHandler extends Handler { 740 private boolean mBound = false; 741 final ArrayList<HandlerParams> mPendingInstalls = 742 new ArrayList<HandlerParams>(); 743 744 private boolean connectToService() { 745 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 746 " DefaultContainerService"); 747 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 748 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 749 if (mContext.bindServiceAsUser(service, mDefContainerConn, 750 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 751 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 752 mBound = true; 753 return true; 754 } 755 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 756 return false; 757 } 758 759 private void disconnectService() { 760 mContainerService = null; 761 mBound = false; 762 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 763 mContext.unbindService(mDefContainerConn); 764 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 765 } 766 767 PackageHandler(Looper looper) { 768 super(looper); 769 } 770 771 public void handleMessage(Message msg) { 772 try { 773 doHandleMessage(msg); 774 } finally { 775 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 776 } 777 } 778 779 void doHandleMessage(Message msg) { 780 switch (msg.what) { 781 case INIT_COPY: { 782 HandlerParams params = (HandlerParams) msg.obj; 783 int idx = mPendingInstalls.size(); 784 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 785 // If a bind was already initiated we dont really 786 // need to do anything. The pending install 787 // will be processed later on. 788 if (!mBound) { 789 // If this is the only one pending we might 790 // have to bind to the service again. 791 if (!connectToService()) { 792 Slog.e(TAG, "Failed to bind to media container service"); 793 params.serviceError(); 794 return; 795 } else { 796 // Once we bind to the service, the first 797 // pending request will be processed. 798 mPendingInstalls.add(idx, params); 799 } 800 } else { 801 mPendingInstalls.add(idx, params); 802 // Already bound to the service. Just make 803 // sure we trigger off processing the first request. 804 if (idx == 0) { 805 mHandler.sendEmptyMessage(MCS_BOUND); 806 } 807 } 808 break; 809 } 810 case MCS_BOUND: { 811 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 812 if (msg.obj != null) { 813 mContainerService = (IMediaContainerService) msg.obj; 814 } 815 if (mContainerService == null) { 816 // Something seriously wrong. Bail out 817 Slog.e(TAG, "Cannot bind to media container service"); 818 for (HandlerParams params : mPendingInstalls) { 819 // Indicate service bind error 820 params.serviceError(); 821 } 822 mPendingInstalls.clear(); 823 } else if (mPendingInstalls.size() > 0) { 824 HandlerParams params = mPendingInstalls.get(0); 825 if (params != null) { 826 if (params.startCopy()) { 827 // We are done... look for more work or to 828 // go idle. 829 if (DEBUG_SD_INSTALL) Log.i(TAG, 830 "Checking for more work or unbind..."); 831 // Delete pending install 832 if (mPendingInstalls.size() > 0) { 833 mPendingInstalls.remove(0); 834 } 835 if (mPendingInstalls.size() == 0) { 836 if (mBound) { 837 if (DEBUG_SD_INSTALL) Log.i(TAG, 838 "Posting delayed MCS_UNBIND"); 839 removeMessages(MCS_UNBIND); 840 Message ubmsg = obtainMessage(MCS_UNBIND); 841 // Unbind after a little delay, to avoid 842 // continual thrashing. 843 sendMessageDelayed(ubmsg, 10000); 844 } 845 } else { 846 // There are more pending requests in queue. 847 // Just post MCS_BOUND message to trigger processing 848 // of next pending install. 849 if (DEBUG_SD_INSTALL) Log.i(TAG, 850 "Posting MCS_BOUND for next work"); 851 mHandler.sendEmptyMessage(MCS_BOUND); 852 } 853 } 854 } 855 } else { 856 // Should never happen ideally. 857 Slog.w(TAG, "Empty queue"); 858 } 859 break; 860 } 861 case MCS_RECONNECT: { 862 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 863 if (mPendingInstalls.size() > 0) { 864 if (mBound) { 865 disconnectService(); 866 } 867 if (!connectToService()) { 868 Slog.e(TAG, "Failed to bind to media container service"); 869 for (HandlerParams params : mPendingInstalls) { 870 // Indicate service bind error 871 params.serviceError(); 872 } 873 mPendingInstalls.clear(); 874 } 875 } 876 break; 877 } 878 case MCS_UNBIND: { 879 // If there is no actual work left, then time to unbind. 880 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 881 882 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 883 if (mBound) { 884 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 885 886 disconnectService(); 887 } 888 } else if (mPendingInstalls.size() > 0) { 889 // There are more pending requests in queue. 890 // Just post MCS_BOUND message to trigger processing 891 // of next pending install. 892 mHandler.sendEmptyMessage(MCS_BOUND); 893 } 894 895 break; 896 } 897 case MCS_GIVE_UP: { 898 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 899 mPendingInstalls.remove(0); 900 break; 901 } 902 case SEND_PENDING_BROADCAST: { 903 String packages[]; 904 ArrayList<String> components[]; 905 int size = 0; 906 int uids[]; 907 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 908 synchronized (mPackages) { 909 if (mPendingBroadcasts == null) { 910 return; 911 } 912 size = mPendingBroadcasts.size(); 913 if (size <= 0) { 914 // Nothing to be done. Just return 915 return; 916 } 917 packages = new String[size]; 918 components = new ArrayList[size]; 919 uids = new int[size]; 920 int i = 0; // filling out the above arrays 921 922 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 923 int packageUserId = mPendingBroadcasts.userIdAt(n); 924 Iterator<Map.Entry<String, ArrayList<String>>> it 925 = mPendingBroadcasts.packagesForUserId(packageUserId) 926 .entrySet().iterator(); 927 while (it.hasNext() && i < size) { 928 Map.Entry<String, ArrayList<String>> ent = it.next(); 929 packages[i] = ent.getKey(); 930 components[i] = ent.getValue(); 931 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 932 uids[i] = (ps != null) 933 ? UserHandle.getUid(packageUserId, ps.appId) 934 : -1; 935 i++; 936 } 937 } 938 size = i; 939 mPendingBroadcasts.clear(); 940 } 941 // Send broadcasts 942 for (int i = 0; i < size; i++) { 943 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 944 } 945 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 946 break; 947 } 948 case START_CLEANING_PACKAGE: { 949 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 950 final String packageName = (String)msg.obj; 951 final int userId = msg.arg1; 952 final boolean andCode = msg.arg2 != 0; 953 synchronized (mPackages) { 954 if (userId == UserHandle.USER_ALL) { 955 int[] users = sUserManager.getUserIds(); 956 for (int user : users) { 957 mSettings.addPackageToCleanLPw( 958 new PackageCleanItem(user, packageName, andCode)); 959 } 960 } else { 961 mSettings.addPackageToCleanLPw( 962 new PackageCleanItem(userId, packageName, andCode)); 963 } 964 } 965 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 966 startCleaningPackages(); 967 } break; 968 case POST_INSTALL: { 969 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 970 PostInstallData data = mRunningInstalls.get(msg.arg1); 971 mRunningInstalls.delete(msg.arg1); 972 boolean deleteOld = false; 973 974 if (data != null) { 975 InstallArgs args = data.args; 976 PackageInstalledInfo res = data.res; 977 978 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 979 res.removedInfo.sendBroadcast(false, true, false); 980 Bundle extras = new Bundle(1); 981 extras.putInt(Intent.EXTRA_UID, res.uid); 982 // Determine the set of users who are adding this 983 // package for the first time vs. those who are seeing 984 // an update. 985 int[] firstUsers; 986 int[] updateUsers = new int[0]; 987 if (res.origUsers == null || res.origUsers.length == 0) { 988 firstUsers = res.newUsers; 989 } else { 990 firstUsers = new int[0]; 991 for (int i=0; i<res.newUsers.length; i++) { 992 int user = res.newUsers[i]; 993 boolean isNew = true; 994 for (int j=0; j<res.origUsers.length; j++) { 995 if (res.origUsers[j] == user) { 996 isNew = false; 997 break; 998 } 999 } 1000 if (isNew) { 1001 int[] newFirst = new int[firstUsers.length+1]; 1002 System.arraycopy(firstUsers, 0, newFirst, 0, 1003 firstUsers.length); 1004 newFirst[firstUsers.length] = user; 1005 firstUsers = newFirst; 1006 } else { 1007 int[] newUpdate = new int[updateUsers.length+1]; 1008 System.arraycopy(updateUsers, 0, newUpdate, 0, 1009 updateUsers.length); 1010 newUpdate[updateUsers.length] = user; 1011 updateUsers = newUpdate; 1012 } 1013 } 1014 } 1015 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1016 res.pkg.applicationInfo.packageName, 1017 extras, null, null, firstUsers); 1018 final boolean update = res.removedInfo.removedPackage != null; 1019 if (update) { 1020 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1021 } 1022 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1023 res.pkg.applicationInfo.packageName, 1024 extras, null, null, updateUsers); 1025 if (update) { 1026 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1027 res.pkg.applicationInfo.packageName, 1028 extras, null, null, updateUsers); 1029 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1030 null, null, 1031 res.pkg.applicationInfo.packageName, null, updateUsers); 1032 1033 // treat asec-hosted packages like removable media on upgrade 1034 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1035 if (DEBUG_INSTALL) { 1036 Slog.i(TAG, "upgrading pkg " + res.pkg 1037 + " is ASEC-hosted -> AVAILABLE"); 1038 } 1039 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1040 ArrayList<String> pkgList = new ArrayList<String>(1); 1041 pkgList.add(res.pkg.applicationInfo.packageName); 1042 sendResourcesChangedBroadcast(true, true, 1043 pkgList,uidArray, null); 1044 } 1045 } 1046 if (res.removedInfo.args != null) { 1047 // Remove the replaced package's older resources safely now 1048 deleteOld = true; 1049 } 1050 1051 // Log current value of "unknown sources" setting 1052 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1053 getUnknownSourcesSettings()); 1054 } 1055 // Force a gc to clear up things 1056 Runtime.getRuntime().gc(); 1057 // We delete after a gc for applications on sdcard. 1058 if (deleteOld) { 1059 synchronized (mInstallLock) { 1060 res.removedInfo.args.doPostDeleteLI(true); 1061 } 1062 } 1063 if (args.observer != null) { 1064 try { 1065 Bundle extras = extrasForInstallResult(res); 1066 args.observer.onPackageInstalled(res.name, res.returnCode, 1067 res.returnMsg, extras); 1068 } catch (RemoteException e) { 1069 Slog.i(TAG, "Observer no longer exists."); 1070 } 1071 } 1072 } else { 1073 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1074 } 1075 } break; 1076 case UPDATED_MEDIA_STATUS: { 1077 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1078 boolean reportStatus = msg.arg1 == 1; 1079 boolean doGc = msg.arg2 == 1; 1080 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1081 if (doGc) { 1082 // Force a gc to clear up stale containers. 1083 Runtime.getRuntime().gc(); 1084 } 1085 if (msg.obj != null) { 1086 @SuppressWarnings("unchecked") 1087 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1088 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1089 // Unload containers 1090 unloadAllContainers(args); 1091 } 1092 if (reportStatus) { 1093 try { 1094 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1095 PackageHelper.getMountService().finishMediaUpdate(); 1096 } catch (RemoteException e) { 1097 Log.e(TAG, "MountService not running?"); 1098 } 1099 } 1100 } break; 1101 case WRITE_SETTINGS: { 1102 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1103 synchronized (mPackages) { 1104 removeMessages(WRITE_SETTINGS); 1105 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1106 mSettings.writeLPr(); 1107 mDirtyUsers.clear(); 1108 } 1109 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1110 } break; 1111 case WRITE_PACKAGE_RESTRICTIONS: { 1112 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1113 synchronized (mPackages) { 1114 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1115 for (int userId : mDirtyUsers) { 1116 mSettings.writePackageRestrictionsLPr(userId); 1117 } 1118 mDirtyUsers.clear(); 1119 } 1120 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1121 } break; 1122 case CHECK_PENDING_VERIFICATION: { 1123 final int verificationId = msg.arg1; 1124 final PackageVerificationState state = mPendingVerification.get(verificationId); 1125 1126 if ((state != null) && !state.timeoutExtended()) { 1127 final InstallArgs args = state.getInstallArgs(); 1128 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1129 1130 Slog.i(TAG, "Verification timed out for " + originUri); 1131 mPendingVerification.remove(verificationId); 1132 1133 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1134 1135 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1136 Slog.i(TAG, "Continuing with installation of " + originUri); 1137 state.setVerifierResponse(Binder.getCallingUid(), 1138 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1139 broadcastPackageVerified(verificationId, originUri, 1140 PackageManager.VERIFICATION_ALLOW, 1141 state.getInstallArgs().getUser()); 1142 try { 1143 ret = args.copyApk(mContainerService, true); 1144 } catch (RemoteException e) { 1145 Slog.e(TAG, "Could not contact the ContainerService"); 1146 } 1147 } else { 1148 broadcastPackageVerified(verificationId, originUri, 1149 PackageManager.VERIFICATION_REJECT, 1150 state.getInstallArgs().getUser()); 1151 } 1152 1153 processPendingInstall(args, ret); 1154 mHandler.sendEmptyMessage(MCS_UNBIND); 1155 } 1156 break; 1157 } 1158 case PACKAGE_VERIFIED: { 1159 final int verificationId = msg.arg1; 1160 1161 final PackageVerificationState state = mPendingVerification.get(verificationId); 1162 if (state == null) { 1163 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1164 break; 1165 } 1166 1167 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1168 1169 state.setVerifierResponse(response.callerUid, response.code); 1170 1171 if (state.isVerificationComplete()) { 1172 mPendingVerification.remove(verificationId); 1173 1174 final InstallArgs args = state.getInstallArgs(); 1175 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1176 1177 int ret; 1178 if (state.isInstallAllowed()) { 1179 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1180 broadcastPackageVerified(verificationId, originUri, 1181 response.code, state.getInstallArgs().getUser()); 1182 try { 1183 ret = args.copyApk(mContainerService, true); 1184 } catch (RemoteException e) { 1185 Slog.e(TAG, "Could not contact the ContainerService"); 1186 } 1187 } else { 1188 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1189 } 1190 1191 processPendingInstall(args, ret); 1192 1193 mHandler.sendEmptyMessage(MCS_UNBIND); 1194 } 1195 1196 break; 1197 } 1198 } 1199 } 1200 } 1201 1202 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1203 Bundle extras = null; 1204 switch (res.returnCode) { 1205 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1206 extras = new Bundle(); 1207 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1208 res.origPermission); 1209 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1210 res.origPackage); 1211 break; 1212 } 1213 } 1214 return extras; 1215 } 1216 1217 void scheduleWriteSettingsLocked() { 1218 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1219 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1220 } 1221 } 1222 1223 void scheduleWritePackageRestrictionsLocked(int userId) { 1224 if (!sUserManager.exists(userId)) return; 1225 mDirtyUsers.add(userId); 1226 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1227 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1228 } 1229 } 1230 1231 public static final PackageManagerService main(Context context, Installer installer, 1232 boolean factoryTest, boolean onlyCore) { 1233 PackageManagerService m = new PackageManagerService(context, installer, 1234 factoryTest, onlyCore); 1235 ServiceManager.addService("package", m); 1236 return m; 1237 } 1238 1239 static String[] splitString(String str, char sep) { 1240 int count = 1; 1241 int i = 0; 1242 while ((i=str.indexOf(sep, i)) >= 0) { 1243 count++; 1244 i++; 1245 } 1246 1247 String[] res = new String[count]; 1248 i=0; 1249 count = 0; 1250 int lastI=0; 1251 while ((i=str.indexOf(sep, i)) >= 0) { 1252 res[count] = str.substring(lastI, i); 1253 count++; 1254 i++; 1255 lastI = i; 1256 } 1257 res[count] = str.substring(lastI, str.length()); 1258 return res; 1259 } 1260 1261 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1262 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1263 Context.DISPLAY_SERVICE); 1264 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1265 } 1266 1267 public PackageManagerService(Context context, Installer installer, 1268 boolean factoryTest, boolean onlyCore) { 1269 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1270 SystemClock.uptimeMillis()); 1271 1272 if (mSdkVersion <= 0) { 1273 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1274 } 1275 1276 mContext = context; 1277 mFactoryTest = factoryTest; 1278 mOnlyCore = onlyCore; 1279 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1280 mMetrics = new DisplayMetrics(); 1281 mSettings = new Settings(context); 1282 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1283 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1284 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1285 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1286 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1287 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1288 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1289 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1290 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1291 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1292 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1293 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1294 1295 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1296 if (separateProcesses != null && separateProcesses.length() > 0) { 1297 if ("*".equals(separateProcesses)) { 1298 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1299 mSeparateProcesses = null; 1300 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1301 } else { 1302 mDefParseFlags = 0; 1303 mSeparateProcesses = separateProcesses.split(","); 1304 Slog.w(TAG, "Running with debug.separate_processes: " 1305 + separateProcesses); 1306 } 1307 } else { 1308 mDefParseFlags = 0; 1309 mSeparateProcesses = null; 1310 } 1311 1312 mInstaller = installer; 1313 1314 getDefaultDisplayMetrics(context, mMetrics); 1315 1316 SystemConfig systemConfig = SystemConfig.getInstance(); 1317 mGlobalGids = systemConfig.getGlobalGids(); 1318 mSystemPermissions = systemConfig.getSystemPermissions(); 1319 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1320 1321 synchronized (mInstallLock) { 1322 // writer 1323 synchronized (mPackages) { 1324 mHandlerThread = new ServiceThread(TAG, 1325 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1326 mHandlerThread.start(); 1327 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1328 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1329 1330 File dataDir = Environment.getDataDirectory(); 1331 mAppDataDir = new File(dataDir, "data"); 1332 mAppInstallDir = new File(dataDir, "app"); 1333 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1334 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1335 mUserAppDataDir = new File(dataDir, "user"); 1336 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1337 1338 sUserManager = new UserManagerService(context, this, 1339 mInstallLock, mPackages); 1340 1341 // Propagate permission configuration in to package manager. 1342 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1343 = systemConfig.getPermissions(); 1344 for (int i=0; i<permConfig.size(); i++) { 1345 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1346 BasePermission bp = mSettings.mPermissions.get(perm.name); 1347 if (bp == null) { 1348 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1349 mSettings.mPermissions.put(perm.name, bp); 1350 } 1351 if (perm.gids != null) { 1352 bp.gids = appendInts(bp.gids, perm.gids); 1353 } 1354 } 1355 1356 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1357 for (int i=0; i<libConfig.size(); i++) { 1358 mSharedLibraries.put(libConfig.keyAt(i), 1359 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1360 } 1361 1362 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1363 1364 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1365 mSdkVersion, mOnlyCore); 1366 1367 String customResolverActivity = Resources.getSystem().getString( 1368 R.string.config_customResolverActivity); 1369 if (TextUtils.isEmpty(customResolverActivity)) { 1370 customResolverActivity = null; 1371 } else { 1372 mCustomResolverComponentName = ComponentName.unflattenFromString( 1373 customResolverActivity); 1374 } 1375 1376 long startTime = SystemClock.uptimeMillis(); 1377 1378 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1379 startTime); 1380 1381 // Set flag to monitor and not change apk file paths when 1382 // scanning install directories. 1383 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1384 1385 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1386 1387 /** 1388 * Add everything in the in the boot class path to the 1389 * list of process files because dexopt will have been run 1390 * if necessary during zygote startup. 1391 */ 1392 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1393 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1394 1395 if (bootClassPath != null) { 1396 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1397 for (String element : bootClassPathElements) { 1398 alreadyDexOpted.add(element); 1399 } 1400 } else { 1401 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1402 } 1403 1404 if (systemServerClassPath != null) { 1405 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1406 for (String element : systemServerClassPathElements) { 1407 alreadyDexOpted.add(element); 1408 } 1409 } else { 1410 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1411 } 1412 1413 boolean didDexOptLibraryOrTool = false; 1414 1415 final List<String> allInstructionSets = getAllInstructionSets(); 1416 final String[] dexCodeInstructionSets = 1417 getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()])); 1418 1419 /** 1420 * Ensure all external libraries have had dexopt run on them. 1421 */ 1422 if (mSharedLibraries.size() > 0) { 1423 // NOTE: For now, we're compiling these system "shared libraries" 1424 // (and framework jars) into all available architectures. It's possible 1425 // to compile them only when we come across an app that uses them (there's 1426 // already logic for that in scanPackageLI) but that adds some complexity. 1427 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1428 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1429 final String lib = libEntry.path; 1430 if (lib == null) { 1431 continue; 1432 } 1433 1434 try { 1435 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1436 dexCodeInstructionSet, 1437 false); 1438 if (dexoptRequired != DexFile.UP_TO_DATE) { 1439 alreadyDexOpted.add(lib); 1440 1441 // The list of "shared libraries" we have at this point is 1442 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1443 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1444 } else { 1445 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1446 } 1447 didDexOptLibraryOrTool = true; 1448 } 1449 } catch (FileNotFoundException e) { 1450 Slog.w(TAG, "Library not found: " + lib); 1451 } catch (IOException e) { 1452 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1453 + e.getMessage()); 1454 } 1455 } 1456 } 1457 } 1458 1459 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1460 1461 // Gross hack for now: we know this file doesn't contain any 1462 // code, so don't dexopt it to avoid the resulting log spew. 1463 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1464 1465 // Gross hack for now: we know this file is only part of 1466 // the boot class path for art, so don't dexopt it to 1467 // avoid the resulting log spew. 1468 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1469 1470 /** 1471 * And there are a number of commands implemented in Java, which 1472 * we currently need to do the dexopt on so that they can be 1473 * run from a non-root shell. 1474 */ 1475 String[] frameworkFiles = frameworkDir.list(); 1476 if (frameworkFiles != null) { 1477 // TODO: We could compile these only for the most preferred ABI. We should 1478 // first double check that the dex files for these commands are not referenced 1479 // by other system apps. 1480 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1481 for (int i=0; i<frameworkFiles.length; i++) { 1482 File libPath = new File(frameworkDir, frameworkFiles[i]); 1483 String path = libPath.getPath(); 1484 // Skip the file if we already did it. 1485 if (alreadyDexOpted.contains(path)) { 1486 continue; 1487 } 1488 // Skip the file if it is not a type we want to dexopt. 1489 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1490 continue; 1491 } 1492 try { 1493 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1494 dexCodeInstructionSet, 1495 false); 1496 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1497 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1498 didDexOptLibraryOrTool = true; 1499 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1500 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1501 didDexOptLibraryOrTool = true; 1502 } 1503 } catch (FileNotFoundException e) { 1504 Slog.w(TAG, "Jar not found: " + path); 1505 } catch (IOException e) { 1506 Slog.w(TAG, "Exception reading jar: " + path, e); 1507 } 1508 } 1509 } 1510 } 1511 1512 // Collect vendor overlay packages. 1513 // (Do this before scanning any apps.) 1514 // For security and version matching reason, only consider 1515 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1516 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1517 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1518 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1519 1520 // Find base frameworks (resource packages without code). 1521 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1522 | PackageParser.PARSE_IS_SYSTEM_DIR 1523 | PackageParser.PARSE_IS_PRIVILEGED, 1524 scanFlags | SCAN_NO_DEX, 0); 1525 1526 // Collected privileged system packages. 1527 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1528 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1529 | PackageParser.PARSE_IS_SYSTEM_DIR 1530 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1531 1532 // Collect ordinary system packages. 1533 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1534 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1535 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1536 1537 // Collect all vendor packages. 1538 File vendorAppDir = new File("/vendor/app"); 1539 try { 1540 vendorAppDir = vendorAppDir.getCanonicalFile(); 1541 } catch (IOException e) { 1542 // failed to look up canonical path, continue with original one 1543 } 1544 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1545 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1546 1547 // Collect all OEM packages. 1548 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1549 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1550 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1551 1552 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1553 mInstaller.moveFiles(); 1554 1555 // Prune any system packages that no longer exist. 1556 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1557 if (!mOnlyCore) { 1558 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1559 while (psit.hasNext()) { 1560 PackageSetting ps = psit.next(); 1561 1562 /* 1563 * If this is not a system app, it can't be a 1564 * disable system app. 1565 */ 1566 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1567 continue; 1568 } 1569 1570 /* 1571 * If the package is scanned, it's not erased. 1572 */ 1573 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1574 if (scannedPkg != null) { 1575 /* 1576 * If the system app is both scanned and in the 1577 * disabled packages list, then it must have been 1578 * added via OTA. Remove it from the currently 1579 * scanned package so the previously user-installed 1580 * application can be scanned. 1581 */ 1582 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1583 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1584 + ps.name + "; removing system app. Last known codePath=" 1585 + ps.codePathString + ", installStatus=" + ps.installStatus 1586 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1587 + scannedPkg.mVersionCode); 1588 removePackageLI(ps, true); 1589 } 1590 1591 continue; 1592 } 1593 1594 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1595 psit.remove(); 1596 logCriticalInfo(Log.WARN, "System package " + ps.name 1597 + " no longer exists; wiping its data"); 1598 removeDataDirsLI(ps.name); 1599 } else { 1600 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1601 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1602 possiblyDeletedUpdatedSystemApps.add(ps.name); 1603 } 1604 } 1605 } 1606 } 1607 1608 //look for any incomplete package installations 1609 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1610 //clean up list 1611 for(int i = 0; i < deletePkgsList.size(); i++) { 1612 //clean up here 1613 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1614 } 1615 //delete tmp files 1616 deleteTempPackageFiles(); 1617 1618 // Remove any shared userIDs that have no associated packages 1619 mSettings.pruneSharedUsersLPw(); 1620 1621 if (!mOnlyCore) { 1622 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1623 SystemClock.uptimeMillis()); 1624 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1625 1626 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1627 scanFlags, 0); 1628 1629 /** 1630 * Remove disable package settings for any updated system 1631 * apps that were removed via an OTA. If they're not a 1632 * previously-updated app, remove them completely. 1633 * Otherwise, just revoke their system-level permissions. 1634 */ 1635 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1636 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1637 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1638 1639 String msg; 1640 if (deletedPkg == null) { 1641 msg = "Updated system package " + deletedAppName 1642 + " no longer exists; wiping its data"; 1643 removeDataDirsLI(deletedAppName); 1644 } else { 1645 msg = "Updated system app + " + deletedAppName 1646 + " no longer present; removing system privileges for " 1647 + deletedAppName; 1648 1649 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1650 1651 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1652 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1653 } 1654 logCriticalInfo(Log.WARN, msg); 1655 } 1656 } 1657 1658 // Now that we know all of the shared libraries, update all clients to have 1659 // the correct library paths. 1660 updateAllSharedLibrariesLPw(); 1661 1662 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1663 // NOTE: We ignore potential failures here during a system scan (like 1664 // the rest of the commands above) because there's precious little we 1665 // can do about it. A settings error is reported, though. 1666 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1667 false /* force dexopt */, false /* defer dexopt */); 1668 } 1669 1670 // Now that we know all the packages we are keeping, 1671 // read and update their last usage times. 1672 mPackageUsage.readLP(); 1673 1674 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1675 SystemClock.uptimeMillis()); 1676 Slog.i(TAG, "Time to scan packages: " 1677 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1678 + " seconds"); 1679 1680 // If the platform SDK has changed since the last time we booted, 1681 // we need to re-grant app permission to catch any new ones that 1682 // appear. This is really a hack, and means that apps can in some 1683 // cases get permissions that the user didn't initially explicitly 1684 // allow... it would be nice to have some better way to handle 1685 // this situation. 1686 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1687 != mSdkVersion; 1688 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1689 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1690 + "; regranting permissions for internal storage"); 1691 mSettings.mInternalSdkPlatform = mSdkVersion; 1692 1693 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1694 | (regrantPermissions 1695 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1696 : 0)); 1697 1698 // If this is the first boot, and it is a normal boot, then 1699 // we need to initialize the default preferred apps. 1700 if (!mRestoredSettings && !onlyCore) { 1701 mSettings.readDefaultPreferredAppsLPw(this, 0); 1702 } 1703 1704 // If this is first boot after an OTA, and a normal boot, then 1705 // we need to clear code cache directories. 1706 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1707 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1708 for (String pkgName : mSettings.mPackages.keySet()) { 1709 deleteCodeCacheDirsLI(pkgName); 1710 } 1711 mSettings.mFingerprint = Build.FINGERPRINT; 1712 } 1713 1714 // All the changes are done during package scanning. 1715 mSettings.updateInternalDatabaseVersion(); 1716 1717 // can downgrade to reader 1718 mSettings.writeLPr(); 1719 1720 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1721 SystemClock.uptimeMillis()); 1722 1723 1724 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1725 } // synchronized (mPackages) 1726 } // synchronized (mInstallLock) 1727 1728 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1729 1730 // Now after opening every single application zip, make sure they 1731 // are all flushed. Not really needed, but keeps things nice and 1732 // tidy. 1733 Runtime.getRuntime().gc(); 1734 } 1735 1736 @Override 1737 public boolean isFirstBoot() { 1738 return !mRestoredSettings; 1739 } 1740 1741 @Override 1742 public boolean isOnlyCoreApps() { 1743 return mOnlyCore; 1744 } 1745 1746 private String getRequiredVerifierLPr() { 1747 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1748 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1749 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1750 1751 String requiredVerifier = null; 1752 1753 final int N = receivers.size(); 1754 for (int i = 0; i < N; i++) { 1755 final ResolveInfo info = receivers.get(i); 1756 1757 if (info.activityInfo == null) { 1758 continue; 1759 } 1760 1761 final String packageName = info.activityInfo.packageName; 1762 1763 final PackageSetting ps = mSettings.mPackages.get(packageName); 1764 if (ps == null) { 1765 continue; 1766 } 1767 1768 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1769 if (!gp.grantedPermissions 1770 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1771 continue; 1772 } 1773 1774 if (requiredVerifier != null) { 1775 throw new RuntimeException("There can be only one required verifier"); 1776 } 1777 1778 requiredVerifier = packageName; 1779 } 1780 1781 return requiredVerifier; 1782 } 1783 1784 @Override 1785 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1786 throws RemoteException { 1787 try { 1788 return super.onTransact(code, data, reply, flags); 1789 } catch (RuntimeException e) { 1790 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1791 Slog.wtf(TAG, "Package Manager Crash", e); 1792 } 1793 throw e; 1794 } 1795 } 1796 1797 void cleanupInstallFailedPackage(PackageSetting ps) { 1798 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 1799 1800 removeDataDirsLI(ps.name); 1801 if (ps.codePath != null) { 1802 if (ps.codePath.isDirectory()) { 1803 FileUtils.deleteContents(ps.codePath); 1804 } 1805 ps.codePath.delete(); 1806 } 1807 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 1808 if (ps.resourcePath.isDirectory()) { 1809 FileUtils.deleteContents(ps.resourcePath); 1810 } 1811 ps.resourcePath.delete(); 1812 } 1813 mSettings.removePackageLPw(ps.name); 1814 } 1815 1816 static int[] appendInts(int[] cur, int[] add) { 1817 if (add == null) return cur; 1818 if (cur == null) return add; 1819 final int N = add.length; 1820 for (int i=0; i<N; i++) { 1821 cur = appendInt(cur, add[i]); 1822 } 1823 return cur; 1824 } 1825 1826 static int[] removeInts(int[] cur, int[] rem) { 1827 if (rem == null) return cur; 1828 if (cur == null) return cur; 1829 final int N = rem.length; 1830 for (int i=0; i<N; i++) { 1831 cur = removeInt(cur, rem[i]); 1832 } 1833 return cur; 1834 } 1835 1836 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1837 if (!sUserManager.exists(userId)) return null; 1838 final PackageSetting ps = (PackageSetting) p.mExtras; 1839 if (ps == null) { 1840 return null; 1841 } 1842 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1843 final PackageUserState state = ps.readUserState(userId); 1844 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1845 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1846 state, userId); 1847 } 1848 1849 @Override 1850 public boolean isPackageAvailable(String packageName, int userId) { 1851 if (!sUserManager.exists(userId)) return false; 1852 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 1853 synchronized (mPackages) { 1854 PackageParser.Package p = mPackages.get(packageName); 1855 if (p != null) { 1856 final PackageSetting ps = (PackageSetting) p.mExtras; 1857 if (ps != null) { 1858 final PackageUserState state = ps.readUserState(userId); 1859 if (state != null) { 1860 return PackageParser.isAvailable(state); 1861 } 1862 } 1863 } 1864 } 1865 return false; 1866 } 1867 1868 @Override 1869 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1870 if (!sUserManager.exists(userId)) return null; 1871 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 1872 // reader 1873 synchronized (mPackages) { 1874 PackageParser.Package p = mPackages.get(packageName); 1875 if (DEBUG_PACKAGE_INFO) 1876 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1877 if (p != null) { 1878 return generatePackageInfo(p, flags, userId); 1879 } 1880 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1881 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1882 } 1883 } 1884 return null; 1885 } 1886 1887 @Override 1888 public String[] currentToCanonicalPackageNames(String[] names) { 1889 String[] out = new String[names.length]; 1890 // reader 1891 synchronized (mPackages) { 1892 for (int i=names.length-1; i>=0; i--) { 1893 PackageSetting ps = mSettings.mPackages.get(names[i]); 1894 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1895 } 1896 } 1897 return out; 1898 } 1899 1900 @Override 1901 public String[] canonicalToCurrentPackageNames(String[] names) { 1902 String[] out = new String[names.length]; 1903 // reader 1904 synchronized (mPackages) { 1905 for (int i=names.length-1; i>=0; i--) { 1906 String cur = mSettings.mRenamedPackages.get(names[i]); 1907 out[i] = cur != null ? cur : names[i]; 1908 } 1909 } 1910 return out; 1911 } 1912 1913 @Override 1914 public int getPackageUid(String packageName, int userId) { 1915 if (!sUserManager.exists(userId)) return -1; 1916 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 1917 // reader 1918 synchronized (mPackages) { 1919 PackageParser.Package p = mPackages.get(packageName); 1920 if(p != null) { 1921 return UserHandle.getUid(userId, p.applicationInfo.uid); 1922 } 1923 PackageSetting ps = mSettings.mPackages.get(packageName); 1924 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1925 return -1; 1926 } 1927 p = ps.pkg; 1928 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1929 } 1930 } 1931 1932 @Override 1933 public int[] getPackageGids(String packageName) { 1934 // reader 1935 synchronized (mPackages) { 1936 PackageParser.Package p = mPackages.get(packageName); 1937 if (DEBUG_PACKAGE_INFO) 1938 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1939 if (p != null) { 1940 final PackageSetting ps = (PackageSetting)p.mExtras; 1941 return ps.getGids(); 1942 } 1943 } 1944 // stupid thing to indicate an error. 1945 return new int[0]; 1946 } 1947 1948 static final PermissionInfo generatePermissionInfo( 1949 BasePermission bp, int flags) { 1950 if (bp.perm != null) { 1951 return PackageParser.generatePermissionInfo(bp.perm, flags); 1952 } 1953 PermissionInfo pi = new PermissionInfo(); 1954 pi.name = bp.name; 1955 pi.packageName = bp.sourcePackage; 1956 pi.nonLocalizedLabel = bp.name; 1957 pi.protectionLevel = bp.protectionLevel; 1958 return pi; 1959 } 1960 1961 @Override 1962 public PermissionInfo getPermissionInfo(String name, int flags) { 1963 // reader 1964 synchronized (mPackages) { 1965 final BasePermission p = mSettings.mPermissions.get(name); 1966 if (p != null) { 1967 return generatePermissionInfo(p, flags); 1968 } 1969 return null; 1970 } 1971 } 1972 1973 @Override 1974 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 1975 // reader 1976 synchronized (mPackages) { 1977 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 1978 for (BasePermission p : mSettings.mPermissions.values()) { 1979 if (group == null) { 1980 if (p.perm == null || p.perm.info.group == null) { 1981 out.add(generatePermissionInfo(p, flags)); 1982 } 1983 } else { 1984 if (p.perm != null && group.equals(p.perm.info.group)) { 1985 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 1986 } 1987 } 1988 } 1989 1990 if (out.size() > 0) { 1991 return out; 1992 } 1993 return mPermissionGroups.containsKey(group) ? out : null; 1994 } 1995 } 1996 1997 @Override 1998 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 1999 // reader 2000 synchronized (mPackages) { 2001 return PackageParser.generatePermissionGroupInfo( 2002 mPermissionGroups.get(name), flags); 2003 } 2004 } 2005 2006 @Override 2007 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2008 // reader 2009 synchronized (mPackages) { 2010 final int N = mPermissionGroups.size(); 2011 ArrayList<PermissionGroupInfo> out 2012 = new ArrayList<PermissionGroupInfo>(N); 2013 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2014 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2015 } 2016 return out; 2017 } 2018 } 2019 2020 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2021 int userId) { 2022 if (!sUserManager.exists(userId)) return null; 2023 PackageSetting ps = mSettings.mPackages.get(packageName); 2024 if (ps != null) { 2025 if (ps.pkg == null) { 2026 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2027 flags, userId); 2028 if (pInfo != null) { 2029 return pInfo.applicationInfo; 2030 } 2031 return null; 2032 } 2033 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2034 ps.readUserState(userId), userId); 2035 } 2036 return null; 2037 } 2038 2039 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2040 int userId) { 2041 if (!sUserManager.exists(userId)) return null; 2042 PackageSetting ps = mSettings.mPackages.get(packageName); 2043 if (ps != null) { 2044 PackageParser.Package pkg = ps.pkg; 2045 if (pkg == null) { 2046 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2047 return null; 2048 } 2049 // Only data remains, so we aren't worried about code paths 2050 pkg = new PackageParser.Package(packageName); 2051 pkg.applicationInfo.packageName = packageName; 2052 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2053 pkg.applicationInfo.dataDir = 2054 getDataPathForPackage(packageName, 0).getPath(); 2055 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2056 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2057 } 2058 return generatePackageInfo(pkg, flags, userId); 2059 } 2060 return null; 2061 } 2062 2063 @Override 2064 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2065 if (!sUserManager.exists(userId)) return null; 2066 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2067 // writer 2068 synchronized (mPackages) { 2069 PackageParser.Package p = mPackages.get(packageName); 2070 if (DEBUG_PACKAGE_INFO) Log.v( 2071 TAG, "getApplicationInfo " + packageName 2072 + ": " + p); 2073 if (p != null) { 2074 PackageSetting ps = mSettings.mPackages.get(packageName); 2075 if (ps == null) return null; 2076 // Note: isEnabledLP() does not apply here - always return info 2077 return PackageParser.generateApplicationInfo( 2078 p, flags, ps.readUserState(userId), userId); 2079 } 2080 if ("android".equals(packageName)||"system".equals(packageName)) { 2081 return mAndroidApplication; 2082 } 2083 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2084 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2085 } 2086 } 2087 return null; 2088 } 2089 2090 2091 @Override 2092 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2093 mContext.enforceCallingOrSelfPermission( 2094 android.Manifest.permission.CLEAR_APP_CACHE, null); 2095 // Queue up an async operation since clearing cache may take a little while. 2096 mHandler.post(new Runnable() { 2097 public void run() { 2098 mHandler.removeCallbacks(this); 2099 int retCode = -1; 2100 synchronized (mInstallLock) { 2101 retCode = mInstaller.freeCache(freeStorageSize); 2102 if (retCode < 0) { 2103 Slog.w(TAG, "Couldn't clear application caches"); 2104 } 2105 } 2106 if (observer != null) { 2107 try { 2108 observer.onRemoveCompleted(null, (retCode >= 0)); 2109 } catch (RemoteException e) { 2110 Slog.w(TAG, "RemoveException when invoking call back"); 2111 } 2112 } 2113 } 2114 }); 2115 } 2116 2117 @Override 2118 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2119 mContext.enforceCallingOrSelfPermission( 2120 android.Manifest.permission.CLEAR_APP_CACHE, null); 2121 // Queue up an async operation since clearing cache may take a little while. 2122 mHandler.post(new Runnable() { 2123 public void run() { 2124 mHandler.removeCallbacks(this); 2125 int retCode = -1; 2126 synchronized (mInstallLock) { 2127 retCode = mInstaller.freeCache(freeStorageSize); 2128 if (retCode < 0) { 2129 Slog.w(TAG, "Couldn't clear application caches"); 2130 } 2131 } 2132 if(pi != null) { 2133 try { 2134 // Callback via pending intent 2135 int code = (retCode >= 0) ? 1 : 0; 2136 pi.sendIntent(null, code, null, 2137 null, null); 2138 } catch (SendIntentException e1) { 2139 Slog.i(TAG, "Failed to send pending intent"); 2140 } 2141 } 2142 } 2143 }); 2144 } 2145 2146 void freeStorage(long freeStorageSize) throws IOException { 2147 synchronized (mInstallLock) { 2148 if (mInstaller.freeCache(freeStorageSize) < 0) { 2149 throw new IOException("Failed to free enough space"); 2150 } 2151 } 2152 } 2153 2154 @Override 2155 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2156 if (!sUserManager.exists(userId)) return null; 2157 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2158 synchronized (mPackages) { 2159 PackageParser.Activity a = mActivities.mActivities.get(component); 2160 2161 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2162 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2163 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2164 if (ps == null) return null; 2165 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2166 userId); 2167 } 2168 if (mResolveComponentName.equals(component)) { 2169 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2170 new PackageUserState(), userId); 2171 } 2172 } 2173 return null; 2174 } 2175 2176 @Override 2177 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2178 String resolvedType) { 2179 synchronized (mPackages) { 2180 PackageParser.Activity a = mActivities.mActivities.get(component); 2181 if (a == null) { 2182 return false; 2183 } 2184 for (int i=0; i<a.intents.size(); i++) { 2185 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2186 intent.getData(), intent.getCategories(), TAG) >= 0) { 2187 return true; 2188 } 2189 } 2190 return false; 2191 } 2192 } 2193 2194 @Override 2195 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2196 if (!sUserManager.exists(userId)) return null; 2197 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2198 synchronized (mPackages) { 2199 PackageParser.Activity a = mReceivers.mActivities.get(component); 2200 if (DEBUG_PACKAGE_INFO) Log.v( 2201 TAG, "getReceiverInfo " + component + ": " + a); 2202 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2203 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2204 if (ps == null) return null; 2205 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2206 userId); 2207 } 2208 } 2209 return null; 2210 } 2211 2212 @Override 2213 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2214 if (!sUserManager.exists(userId)) return null; 2215 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2216 synchronized (mPackages) { 2217 PackageParser.Service s = mServices.mServices.get(component); 2218 if (DEBUG_PACKAGE_INFO) Log.v( 2219 TAG, "getServiceInfo " + component + ": " + s); 2220 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2221 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2222 if (ps == null) return null; 2223 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2224 userId); 2225 } 2226 } 2227 return null; 2228 } 2229 2230 @Override 2231 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2232 if (!sUserManager.exists(userId)) return null; 2233 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2234 synchronized (mPackages) { 2235 PackageParser.Provider p = mProviders.mProviders.get(component); 2236 if (DEBUG_PACKAGE_INFO) Log.v( 2237 TAG, "getProviderInfo " + component + ": " + p); 2238 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2239 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2240 if (ps == null) return null; 2241 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2242 userId); 2243 } 2244 } 2245 return null; 2246 } 2247 2248 @Override 2249 public String[] getSystemSharedLibraryNames() { 2250 Set<String> libSet; 2251 synchronized (mPackages) { 2252 libSet = mSharedLibraries.keySet(); 2253 int size = libSet.size(); 2254 if (size > 0) { 2255 String[] libs = new String[size]; 2256 libSet.toArray(libs); 2257 return libs; 2258 } 2259 } 2260 return null; 2261 } 2262 2263 @Override 2264 public FeatureInfo[] getSystemAvailableFeatures() { 2265 Collection<FeatureInfo> featSet; 2266 synchronized (mPackages) { 2267 featSet = mAvailableFeatures.values(); 2268 int size = featSet.size(); 2269 if (size > 0) { 2270 FeatureInfo[] features = new FeatureInfo[size+1]; 2271 featSet.toArray(features); 2272 FeatureInfo fi = new FeatureInfo(); 2273 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2274 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2275 features[size] = fi; 2276 return features; 2277 } 2278 } 2279 return null; 2280 } 2281 2282 @Override 2283 public boolean hasSystemFeature(String name) { 2284 synchronized (mPackages) { 2285 return mAvailableFeatures.containsKey(name); 2286 } 2287 } 2288 2289 private void checkValidCaller(int uid, int userId) { 2290 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2291 return; 2292 2293 throw new SecurityException("Caller uid=" + uid 2294 + " is not privileged to communicate with user=" + userId); 2295 } 2296 2297 @Override 2298 public int checkPermission(String permName, String pkgName) { 2299 synchronized (mPackages) { 2300 PackageParser.Package p = mPackages.get(pkgName); 2301 if (p != null && p.mExtras != null) { 2302 PackageSetting ps = (PackageSetting)p.mExtras; 2303 if (ps.sharedUser != null) { 2304 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2305 return PackageManager.PERMISSION_GRANTED; 2306 } 2307 } else if (ps.grantedPermissions.contains(permName)) { 2308 return PackageManager.PERMISSION_GRANTED; 2309 } 2310 } 2311 } 2312 return PackageManager.PERMISSION_DENIED; 2313 } 2314 2315 @Override 2316 public int checkUidPermission(String permName, int uid) { 2317 synchronized (mPackages) { 2318 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2319 if (obj != null) { 2320 GrantedPermissions gp = (GrantedPermissions)obj; 2321 if (gp.grantedPermissions.contains(permName)) { 2322 return PackageManager.PERMISSION_GRANTED; 2323 } 2324 } else { 2325 HashSet<String> perms = mSystemPermissions.get(uid); 2326 if (perms != null && perms.contains(permName)) { 2327 return PackageManager.PERMISSION_GRANTED; 2328 } 2329 } 2330 } 2331 return PackageManager.PERMISSION_DENIED; 2332 } 2333 2334 /** 2335 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2336 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2337 * @param checkShell TODO(yamasani): 2338 * @param message the message to log on security exception 2339 */ 2340 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2341 boolean checkShell, String message) { 2342 if (userId < 0) { 2343 throw new IllegalArgumentException("Invalid userId " + userId); 2344 } 2345 if (checkShell) { 2346 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2347 } 2348 if (userId == UserHandle.getUserId(callingUid)) return; 2349 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2350 if (requireFullPermission) { 2351 mContext.enforceCallingOrSelfPermission( 2352 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2353 } else { 2354 try { 2355 mContext.enforceCallingOrSelfPermission( 2356 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2357 } catch (SecurityException se) { 2358 mContext.enforceCallingOrSelfPermission( 2359 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2360 } 2361 } 2362 } 2363 } 2364 2365 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2366 if (callingUid == Process.SHELL_UID) { 2367 if (userHandle >= 0 2368 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2369 throw new SecurityException("Shell does not have permission to access user " 2370 + userHandle); 2371 } else if (userHandle < 0) { 2372 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2373 + Debug.getCallers(3)); 2374 } 2375 } 2376 } 2377 2378 private BasePermission findPermissionTreeLP(String permName) { 2379 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2380 if (permName.startsWith(bp.name) && 2381 permName.length() > bp.name.length() && 2382 permName.charAt(bp.name.length()) == '.') { 2383 return bp; 2384 } 2385 } 2386 return null; 2387 } 2388 2389 private BasePermission checkPermissionTreeLP(String permName) { 2390 if (permName != null) { 2391 BasePermission bp = findPermissionTreeLP(permName); 2392 if (bp != null) { 2393 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2394 return bp; 2395 } 2396 throw new SecurityException("Calling uid " 2397 + Binder.getCallingUid() 2398 + " is not allowed to add to permission tree " 2399 + bp.name + " owned by uid " + bp.uid); 2400 } 2401 } 2402 throw new SecurityException("No permission tree found for " + permName); 2403 } 2404 2405 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2406 if (s1 == null) { 2407 return s2 == null; 2408 } 2409 if (s2 == null) { 2410 return false; 2411 } 2412 if (s1.getClass() != s2.getClass()) { 2413 return false; 2414 } 2415 return s1.equals(s2); 2416 } 2417 2418 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2419 if (pi1.icon != pi2.icon) return false; 2420 if (pi1.logo != pi2.logo) return false; 2421 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2422 if (!compareStrings(pi1.name, pi2.name)) return false; 2423 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2424 // We'll take care of setting this one. 2425 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2426 // These are not currently stored in settings. 2427 //if (!compareStrings(pi1.group, pi2.group)) return false; 2428 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2429 //if (pi1.labelRes != pi2.labelRes) return false; 2430 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2431 return true; 2432 } 2433 2434 int permissionInfoFootprint(PermissionInfo info) { 2435 int size = info.name.length(); 2436 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2437 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2438 return size; 2439 } 2440 2441 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2442 int size = 0; 2443 for (BasePermission perm : mSettings.mPermissions.values()) { 2444 if (perm.uid == tree.uid) { 2445 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2446 } 2447 } 2448 return size; 2449 } 2450 2451 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2452 // We calculate the max size of permissions defined by this uid and throw 2453 // if that plus the size of 'info' would exceed our stated maximum. 2454 if (tree.uid != Process.SYSTEM_UID) { 2455 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2456 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2457 throw new SecurityException("Permission tree size cap exceeded"); 2458 } 2459 } 2460 } 2461 2462 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2463 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2464 throw new SecurityException("Label must be specified in permission"); 2465 } 2466 BasePermission tree = checkPermissionTreeLP(info.name); 2467 BasePermission bp = mSettings.mPermissions.get(info.name); 2468 boolean added = bp == null; 2469 boolean changed = true; 2470 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2471 if (added) { 2472 enforcePermissionCapLocked(info, tree); 2473 bp = new BasePermission(info.name, tree.sourcePackage, 2474 BasePermission.TYPE_DYNAMIC); 2475 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2476 throw new SecurityException( 2477 "Not allowed to modify non-dynamic permission " 2478 + info.name); 2479 } else { 2480 if (bp.protectionLevel == fixedLevel 2481 && bp.perm.owner.equals(tree.perm.owner) 2482 && bp.uid == tree.uid 2483 && comparePermissionInfos(bp.perm.info, info)) { 2484 changed = false; 2485 } 2486 } 2487 bp.protectionLevel = fixedLevel; 2488 info = new PermissionInfo(info); 2489 info.protectionLevel = fixedLevel; 2490 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2491 bp.perm.info.packageName = tree.perm.info.packageName; 2492 bp.uid = tree.uid; 2493 if (added) { 2494 mSettings.mPermissions.put(info.name, bp); 2495 } 2496 if (changed) { 2497 if (!async) { 2498 mSettings.writeLPr(); 2499 } else { 2500 scheduleWriteSettingsLocked(); 2501 } 2502 } 2503 return added; 2504 } 2505 2506 @Override 2507 public boolean addPermission(PermissionInfo info) { 2508 synchronized (mPackages) { 2509 return addPermissionLocked(info, false); 2510 } 2511 } 2512 2513 @Override 2514 public boolean addPermissionAsync(PermissionInfo info) { 2515 synchronized (mPackages) { 2516 return addPermissionLocked(info, true); 2517 } 2518 } 2519 2520 @Override 2521 public void removePermission(String name) { 2522 synchronized (mPackages) { 2523 checkPermissionTreeLP(name); 2524 BasePermission bp = mSettings.mPermissions.get(name); 2525 if (bp != null) { 2526 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2527 throw new SecurityException( 2528 "Not allowed to modify non-dynamic permission " 2529 + name); 2530 } 2531 mSettings.mPermissions.remove(name); 2532 mSettings.writeLPr(); 2533 } 2534 } 2535 } 2536 2537 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2538 int index = pkg.requestedPermissions.indexOf(bp.name); 2539 if (index == -1) { 2540 throw new SecurityException("Package " + pkg.packageName 2541 + " has not requested permission " + bp.name); 2542 } 2543 boolean isNormal = 2544 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2545 == PermissionInfo.PROTECTION_NORMAL); 2546 boolean isDangerous = 2547 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2548 == PermissionInfo.PROTECTION_DANGEROUS); 2549 boolean isDevelopment = 2550 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2551 2552 if (!isNormal && !isDangerous && !isDevelopment) { 2553 throw new SecurityException("Permission " + bp.name 2554 + " is not a changeable permission type"); 2555 } 2556 2557 if (isNormal || isDangerous) { 2558 if (pkg.requestedPermissionsRequired.get(index)) { 2559 throw new SecurityException("Can't change " + bp.name 2560 + ". It is required by the application"); 2561 } 2562 } 2563 } 2564 2565 @Override 2566 public void grantPermission(String packageName, String permissionName) { 2567 mContext.enforceCallingOrSelfPermission( 2568 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2569 synchronized (mPackages) { 2570 final PackageParser.Package pkg = mPackages.get(packageName); 2571 if (pkg == null) { 2572 throw new IllegalArgumentException("Unknown package: " + packageName); 2573 } 2574 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2575 if (bp == null) { 2576 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2577 } 2578 2579 checkGrantRevokePermissions(pkg, bp); 2580 2581 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2582 if (ps == null) { 2583 return; 2584 } 2585 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2586 if (gp.grantedPermissions.add(permissionName)) { 2587 if (ps.haveGids) { 2588 gp.gids = appendInts(gp.gids, bp.gids); 2589 } 2590 mSettings.writeLPr(); 2591 } 2592 } 2593 } 2594 2595 @Override 2596 public void revokePermission(String packageName, String permissionName) { 2597 int changedAppId = -1; 2598 2599 synchronized (mPackages) { 2600 final PackageParser.Package pkg = mPackages.get(packageName); 2601 if (pkg == null) { 2602 throw new IllegalArgumentException("Unknown package: " + packageName); 2603 } 2604 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2605 mContext.enforceCallingOrSelfPermission( 2606 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2607 } 2608 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2609 if (bp == null) { 2610 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2611 } 2612 2613 checkGrantRevokePermissions(pkg, bp); 2614 2615 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2616 if (ps == null) { 2617 return; 2618 } 2619 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2620 if (gp.grantedPermissions.remove(permissionName)) { 2621 gp.grantedPermissions.remove(permissionName); 2622 if (ps.haveGids) { 2623 gp.gids = removeInts(gp.gids, bp.gids); 2624 } 2625 mSettings.writeLPr(); 2626 changedAppId = ps.appId; 2627 } 2628 } 2629 2630 if (changedAppId >= 0) { 2631 // We changed the perm on someone, kill its processes. 2632 IActivityManager am = ActivityManagerNative.getDefault(); 2633 if (am != null) { 2634 final int callingUserId = UserHandle.getCallingUserId(); 2635 final long ident = Binder.clearCallingIdentity(); 2636 try { 2637 //XXX we should only revoke for the calling user's app permissions, 2638 // but for now we impact all users. 2639 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2640 // "revoke " + permissionName); 2641 int[] users = sUserManager.getUserIds(); 2642 for (int user : users) { 2643 am.killUid(UserHandle.getUid(user, changedAppId), 2644 "revoke " + permissionName); 2645 } 2646 } catch (RemoteException e) { 2647 } finally { 2648 Binder.restoreCallingIdentity(ident); 2649 } 2650 } 2651 } 2652 } 2653 2654 @Override 2655 public boolean isProtectedBroadcast(String actionName) { 2656 synchronized (mPackages) { 2657 return mProtectedBroadcasts.contains(actionName); 2658 } 2659 } 2660 2661 @Override 2662 public int checkSignatures(String pkg1, String pkg2) { 2663 synchronized (mPackages) { 2664 final PackageParser.Package p1 = mPackages.get(pkg1); 2665 final PackageParser.Package p2 = mPackages.get(pkg2); 2666 if (p1 == null || p1.mExtras == null 2667 || p2 == null || p2.mExtras == null) { 2668 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2669 } 2670 return compareSignatures(p1.mSignatures, p2.mSignatures); 2671 } 2672 } 2673 2674 @Override 2675 public int checkUidSignatures(int uid1, int uid2) { 2676 // Map to base uids. 2677 uid1 = UserHandle.getAppId(uid1); 2678 uid2 = UserHandle.getAppId(uid2); 2679 // reader 2680 synchronized (mPackages) { 2681 Signature[] s1; 2682 Signature[] s2; 2683 Object obj = mSettings.getUserIdLPr(uid1); 2684 if (obj != null) { 2685 if (obj instanceof SharedUserSetting) { 2686 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2687 } else if (obj instanceof PackageSetting) { 2688 s1 = ((PackageSetting)obj).signatures.mSignatures; 2689 } else { 2690 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2691 } 2692 } else { 2693 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2694 } 2695 obj = mSettings.getUserIdLPr(uid2); 2696 if (obj != null) { 2697 if (obj instanceof SharedUserSetting) { 2698 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2699 } else if (obj instanceof PackageSetting) { 2700 s2 = ((PackageSetting)obj).signatures.mSignatures; 2701 } else { 2702 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2703 } 2704 } else { 2705 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2706 } 2707 return compareSignatures(s1, s2); 2708 } 2709 } 2710 2711 /** 2712 * Compares two sets of signatures. Returns: 2713 * <br /> 2714 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2715 * <br /> 2716 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2717 * <br /> 2718 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2719 * <br /> 2720 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2721 * <br /> 2722 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2723 */ 2724 static int compareSignatures(Signature[] s1, Signature[] s2) { 2725 if (s1 == null) { 2726 return s2 == null 2727 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2728 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2729 } 2730 2731 if (s2 == null) { 2732 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2733 } 2734 2735 if (s1.length != s2.length) { 2736 return PackageManager.SIGNATURE_NO_MATCH; 2737 } 2738 2739 // Since both signature sets are of size 1, we can compare without HashSets. 2740 if (s1.length == 1) { 2741 return s1[0].equals(s2[0]) ? 2742 PackageManager.SIGNATURE_MATCH : 2743 PackageManager.SIGNATURE_NO_MATCH; 2744 } 2745 2746 HashSet<Signature> set1 = new HashSet<Signature>(); 2747 for (Signature sig : s1) { 2748 set1.add(sig); 2749 } 2750 HashSet<Signature> set2 = new HashSet<Signature>(); 2751 for (Signature sig : s2) { 2752 set2.add(sig); 2753 } 2754 // Make sure s2 contains all signatures in s1. 2755 if (set1.equals(set2)) { 2756 return PackageManager.SIGNATURE_MATCH; 2757 } 2758 return PackageManager.SIGNATURE_NO_MATCH; 2759 } 2760 2761 /** 2762 * If the database version for this type of package (internal storage or 2763 * external storage) is less than the version where package signatures 2764 * were updated, return true. 2765 */ 2766 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2767 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2768 DatabaseVersion.SIGNATURE_END_ENTITY)) 2769 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2770 DatabaseVersion.SIGNATURE_END_ENTITY)); 2771 } 2772 2773 /** 2774 * Used for backward compatibility to make sure any packages with 2775 * certificate chains get upgraded to the new style. {@code existingSigs} 2776 * will be in the old format (since they were stored on disk from before the 2777 * system upgrade) and {@code scannedSigs} will be in the newer format. 2778 */ 2779 private int compareSignaturesCompat(PackageSignatures existingSigs, 2780 PackageParser.Package scannedPkg) { 2781 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2782 return PackageManager.SIGNATURE_NO_MATCH; 2783 } 2784 2785 HashSet<Signature> existingSet = new HashSet<Signature>(); 2786 for (Signature sig : existingSigs.mSignatures) { 2787 existingSet.add(sig); 2788 } 2789 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2790 for (Signature sig : scannedPkg.mSignatures) { 2791 try { 2792 Signature[] chainSignatures = sig.getChainSignatures(); 2793 for (Signature chainSig : chainSignatures) { 2794 scannedCompatSet.add(chainSig); 2795 } 2796 } catch (CertificateEncodingException e) { 2797 scannedCompatSet.add(sig); 2798 } 2799 } 2800 /* 2801 * Make sure the expanded scanned set contains all signatures in the 2802 * existing one. 2803 */ 2804 if (scannedCompatSet.equals(existingSet)) { 2805 // Migrate the old signatures to the new scheme. 2806 existingSigs.assignSignatures(scannedPkg.mSignatures); 2807 // The new KeySets will be re-added later in the scanning process. 2808 synchronized (mPackages) { 2809 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2810 } 2811 return PackageManager.SIGNATURE_MATCH; 2812 } 2813 return PackageManager.SIGNATURE_NO_MATCH; 2814 } 2815 2816 @Override 2817 public String[] getPackagesForUid(int uid) { 2818 uid = UserHandle.getAppId(uid); 2819 // reader 2820 synchronized (mPackages) { 2821 Object obj = mSettings.getUserIdLPr(uid); 2822 if (obj instanceof SharedUserSetting) { 2823 final SharedUserSetting sus = (SharedUserSetting) obj; 2824 final int N = sus.packages.size(); 2825 final String[] res = new String[N]; 2826 final Iterator<PackageSetting> it = sus.packages.iterator(); 2827 int i = 0; 2828 while (it.hasNext()) { 2829 res[i++] = it.next().name; 2830 } 2831 return res; 2832 } else if (obj instanceof PackageSetting) { 2833 final PackageSetting ps = (PackageSetting) obj; 2834 return new String[] { ps.name }; 2835 } 2836 } 2837 return null; 2838 } 2839 2840 @Override 2841 public String getNameForUid(int uid) { 2842 // reader 2843 synchronized (mPackages) { 2844 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2845 if (obj instanceof SharedUserSetting) { 2846 final SharedUserSetting sus = (SharedUserSetting) obj; 2847 return sus.name + ":" + sus.userId; 2848 } else if (obj instanceof PackageSetting) { 2849 final PackageSetting ps = (PackageSetting) obj; 2850 return ps.name; 2851 } 2852 } 2853 return null; 2854 } 2855 2856 @Override 2857 public int getUidForSharedUser(String sharedUserName) { 2858 if(sharedUserName == null) { 2859 return -1; 2860 } 2861 // reader 2862 synchronized (mPackages) { 2863 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2864 if (suid == null) { 2865 return -1; 2866 } 2867 return suid.userId; 2868 } 2869 } 2870 2871 @Override 2872 public int getFlagsForUid(int uid) { 2873 synchronized (mPackages) { 2874 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2875 if (obj instanceof SharedUserSetting) { 2876 final SharedUserSetting sus = (SharedUserSetting) obj; 2877 return sus.pkgFlags; 2878 } else if (obj instanceof PackageSetting) { 2879 final PackageSetting ps = (PackageSetting) obj; 2880 return ps.pkgFlags; 2881 } 2882 } 2883 return 0; 2884 } 2885 2886 @Override 2887 public String[] getAppOpPermissionPackages(String permissionName) { 2888 synchronized (mPackages) { 2889 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 2890 if (pkgs == null) { 2891 return null; 2892 } 2893 return pkgs.toArray(new String[pkgs.size()]); 2894 } 2895 } 2896 2897 @Override 2898 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2899 int flags, int userId) { 2900 if (!sUserManager.exists(userId)) return null; 2901 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 2902 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2903 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2904 } 2905 2906 @Override 2907 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2908 IntentFilter filter, int match, ComponentName activity) { 2909 final int userId = UserHandle.getCallingUserId(); 2910 if (DEBUG_PREFERRED) { 2911 Log.v(TAG, "setLastChosenActivity intent=" + intent 2912 + " resolvedType=" + resolvedType 2913 + " flags=" + flags 2914 + " filter=" + filter 2915 + " match=" + match 2916 + " activity=" + activity); 2917 filter.dump(new PrintStreamPrinter(System.out), " "); 2918 } 2919 intent.setComponent(null); 2920 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2921 // Find any earlier preferred or last chosen entries and nuke them 2922 findPreferredActivity(intent, resolvedType, 2923 flags, query, 0, false, true, false, userId); 2924 // Add the new activity as the last chosen for this filter 2925 addPreferredActivityInternal(filter, match, null, activity, false, userId, 2926 "Setting last chosen"); 2927 } 2928 2929 @Override 2930 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2931 final int userId = UserHandle.getCallingUserId(); 2932 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2933 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2934 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2935 false, false, false, userId); 2936 } 2937 2938 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2939 int flags, List<ResolveInfo> query, int userId) { 2940 if (query != null) { 2941 final int N = query.size(); 2942 if (N == 1) { 2943 return query.get(0); 2944 } else if (N > 1) { 2945 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2946 // If there is more than one activity with the same priority, 2947 // then let the user decide between them. 2948 ResolveInfo r0 = query.get(0); 2949 ResolveInfo r1 = query.get(1); 2950 if (DEBUG_INTENT_MATCHING || debug) { 2951 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2952 + r1.activityInfo.name + "=" + r1.priority); 2953 } 2954 // If the first activity has a higher priority, or a different 2955 // default, then it is always desireable to pick it. 2956 if (r0.priority != r1.priority 2957 || r0.preferredOrder != r1.preferredOrder 2958 || r0.isDefault != r1.isDefault) { 2959 return query.get(0); 2960 } 2961 // If we have saved a preference for a preferred activity for 2962 // this Intent, use that. 2963 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2964 flags, query, r0.priority, true, false, debug, userId); 2965 if (ri != null) { 2966 return ri; 2967 } 2968 if (userId != 0) { 2969 ri = new ResolveInfo(mResolveInfo); 2970 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2971 ri.activityInfo.applicationInfo = new ApplicationInfo( 2972 ri.activityInfo.applicationInfo); 2973 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2974 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2975 return ri; 2976 } 2977 return mResolveInfo; 2978 } 2979 } 2980 return null; 2981 } 2982 2983 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2984 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2985 final int N = query.size(); 2986 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2987 .get(userId); 2988 // Get the list of persistent preferred activities that handle the intent 2989 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2990 List<PersistentPreferredActivity> pprefs = ppir != null 2991 ? ppir.queryIntent(intent, resolvedType, 2992 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2993 : null; 2994 if (pprefs != null && pprefs.size() > 0) { 2995 final int M = pprefs.size(); 2996 for (int i=0; i<M; i++) { 2997 final PersistentPreferredActivity ppa = pprefs.get(i); 2998 if (DEBUG_PREFERRED || debug) { 2999 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3000 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3001 + "\n component=" + ppa.mComponent); 3002 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3003 } 3004 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3005 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3006 if (DEBUG_PREFERRED || debug) { 3007 Slog.v(TAG, "Found persistent preferred activity:"); 3008 if (ai != null) { 3009 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3010 } else { 3011 Slog.v(TAG, " null"); 3012 } 3013 } 3014 if (ai == null) { 3015 // This previously registered persistent preferred activity 3016 // component is no longer known. Ignore it and do NOT remove it. 3017 continue; 3018 } 3019 for (int j=0; j<N; j++) { 3020 final ResolveInfo ri = query.get(j); 3021 if (!ri.activityInfo.applicationInfo.packageName 3022 .equals(ai.applicationInfo.packageName)) { 3023 continue; 3024 } 3025 if (!ri.activityInfo.name.equals(ai.name)) { 3026 continue; 3027 } 3028 // Found a persistent preference that can handle the intent. 3029 if (DEBUG_PREFERRED || debug) { 3030 Slog.v(TAG, "Returning persistent preferred activity: " + 3031 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3032 } 3033 return ri; 3034 } 3035 } 3036 } 3037 return null; 3038 } 3039 3040 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3041 List<ResolveInfo> query, int priority, boolean always, 3042 boolean removeMatches, boolean debug, int userId) { 3043 if (!sUserManager.exists(userId)) return null; 3044 // writer 3045 synchronized (mPackages) { 3046 if (intent.getSelector() != null) { 3047 intent = intent.getSelector(); 3048 } 3049 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3050 3051 // Try to find a matching persistent preferred activity. 3052 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3053 debug, userId); 3054 3055 // If a persistent preferred activity matched, use it. 3056 if (pri != null) { 3057 return pri; 3058 } 3059 3060 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3061 // Get the list of preferred activities that handle the intent 3062 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3063 List<PreferredActivity> prefs = pir != null 3064 ? pir.queryIntent(intent, resolvedType, 3065 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3066 : null; 3067 if (prefs != null && prefs.size() > 0) { 3068 boolean changed = false; 3069 try { 3070 // First figure out how good the original match set is. 3071 // We will only allow preferred activities that came 3072 // from the same match quality. 3073 int match = 0; 3074 3075 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3076 3077 final int N = query.size(); 3078 for (int j=0; j<N; j++) { 3079 final ResolveInfo ri = query.get(j); 3080 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3081 + ": 0x" + Integer.toHexString(match)); 3082 if (ri.match > match) { 3083 match = ri.match; 3084 } 3085 } 3086 3087 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3088 + Integer.toHexString(match)); 3089 3090 match &= IntentFilter.MATCH_CATEGORY_MASK; 3091 final int M = prefs.size(); 3092 for (int i=0; i<M; i++) { 3093 final PreferredActivity pa = prefs.get(i); 3094 if (DEBUG_PREFERRED || debug) { 3095 Slog.v(TAG, "Checking PreferredActivity ds=" 3096 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3097 + "\n component=" + pa.mPref.mComponent); 3098 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3099 } 3100 if (pa.mPref.mMatch != match) { 3101 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3102 + Integer.toHexString(pa.mPref.mMatch)); 3103 continue; 3104 } 3105 // If it's not an "always" type preferred activity and that's what we're 3106 // looking for, skip it. 3107 if (always && !pa.mPref.mAlways) { 3108 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3109 continue; 3110 } 3111 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3112 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3113 if (DEBUG_PREFERRED || debug) { 3114 Slog.v(TAG, "Found preferred activity:"); 3115 if (ai != null) { 3116 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3117 } else { 3118 Slog.v(TAG, " null"); 3119 } 3120 } 3121 if (ai == null) { 3122 // This previously registered preferred activity 3123 // component is no longer known. Most likely an update 3124 // to the app was installed and in the new version this 3125 // component no longer exists. Clean it up by removing 3126 // it from the preferred activities list, and skip it. 3127 Slog.w(TAG, "Removing dangling preferred activity: " 3128 + pa.mPref.mComponent); 3129 pir.removeFilter(pa); 3130 changed = true; 3131 continue; 3132 } 3133 for (int j=0; j<N; j++) { 3134 final ResolveInfo ri = query.get(j); 3135 if (!ri.activityInfo.applicationInfo.packageName 3136 .equals(ai.applicationInfo.packageName)) { 3137 continue; 3138 } 3139 if (!ri.activityInfo.name.equals(ai.name)) { 3140 continue; 3141 } 3142 3143 if (removeMatches) { 3144 pir.removeFilter(pa); 3145 changed = true; 3146 if (DEBUG_PREFERRED) { 3147 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3148 } 3149 break; 3150 } 3151 3152 // Okay we found a previously set preferred or last chosen app. 3153 // If the result set is different from when this 3154 // was created, we need to clear it and re-ask the 3155 // user their preference, if we're looking for an "always" type entry. 3156 if (always && !pa.mPref.sameSet(query, priority)) { 3157 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3158 + intent + " type " + resolvedType); 3159 if (DEBUG_PREFERRED) { 3160 Slog.v(TAG, "Removing preferred activity since set changed " 3161 + pa.mPref.mComponent); 3162 } 3163 pir.removeFilter(pa); 3164 // Re-add the filter as a "last chosen" entry (!always) 3165 PreferredActivity lastChosen = new PreferredActivity( 3166 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3167 pir.addFilter(lastChosen); 3168 changed = true; 3169 return null; 3170 } 3171 3172 // Yay! Either the set matched or we're looking for the last chosen 3173 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3174 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3175 return ri; 3176 } 3177 } 3178 } finally { 3179 if (changed) { 3180 if (DEBUG_PREFERRED) { 3181 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3182 } 3183 mSettings.writePackageRestrictionsLPr(userId); 3184 } 3185 } 3186 } 3187 } 3188 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3189 return null; 3190 } 3191 3192 /* 3193 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3194 */ 3195 @Override 3196 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3197 int targetUserId) { 3198 mContext.enforceCallingOrSelfPermission( 3199 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3200 List<CrossProfileIntentFilter> matches = 3201 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3202 if (matches != null) { 3203 int size = matches.size(); 3204 for (int i = 0; i < size; i++) { 3205 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3206 } 3207 } 3208 return false; 3209 } 3210 3211 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3212 String resolvedType, int userId) { 3213 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3214 if (resolver != null) { 3215 return resolver.queryIntent(intent, resolvedType, false, userId); 3216 } 3217 return null; 3218 } 3219 3220 @Override 3221 public List<ResolveInfo> queryIntentActivities(Intent intent, 3222 String resolvedType, int flags, int userId) { 3223 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3224 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3225 ComponentName comp = intent.getComponent(); 3226 if (comp == null) { 3227 if (intent.getSelector() != null) { 3228 intent = intent.getSelector(); 3229 comp = intent.getComponent(); 3230 } 3231 } 3232 3233 if (comp != null) { 3234 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3235 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3236 if (ai != null) { 3237 final ResolveInfo ri = new ResolveInfo(); 3238 ri.activityInfo = ai; 3239 list.add(ri); 3240 } 3241 return list; 3242 } 3243 3244 // reader 3245 synchronized (mPackages) { 3246 final String pkgName = intent.getPackage(); 3247 if (pkgName == null) { 3248 List<CrossProfileIntentFilter> matchingFilters = 3249 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3250 // Check for results that need to skip the current profile. 3251 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3252 resolvedType, flags, userId); 3253 if (resolveInfo != null) { 3254 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3255 result.add(resolveInfo); 3256 return result; 3257 } 3258 // Check for cross profile results. 3259 resolveInfo = queryCrossProfileIntents( 3260 matchingFilters, intent, resolvedType, flags, userId); 3261 3262 // Check for results in the current profile. 3263 List<ResolveInfo> result = mActivities.queryIntent( 3264 intent, resolvedType, flags, userId); 3265 if (resolveInfo != null) { 3266 result.add(resolveInfo); 3267 Collections.sort(result, mResolvePrioritySorter); 3268 } 3269 return result; 3270 } 3271 final PackageParser.Package pkg = mPackages.get(pkgName); 3272 if (pkg != null) { 3273 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3274 pkg.activities, userId); 3275 } 3276 return new ArrayList<ResolveInfo>(); 3277 } 3278 } 3279 3280 private ResolveInfo querySkipCurrentProfileIntents( 3281 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3282 int flags, int sourceUserId) { 3283 if (matchingFilters != null) { 3284 int size = matchingFilters.size(); 3285 for (int i = 0; i < size; i ++) { 3286 CrossProfileIntentFilter filter = matchingFilters.get(i); 3287 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3288 // Checking if there are activities in the target user that can handle the 3289 // intent. 3290 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3291 flags, sourceUserId); 3292 if (resolveInfo != null) { 3293 return resolveInfo; 3294 } 3295 } 3296 } 3297 } 3298 return null; 3299 } 3300 3301 // Return matching ResolveInfo if any for skip current profile intent filters. 3302 private ResolveInfo queryCrossProfileIntents( 3303 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3304 int flags, int sourceUserId) { 3305 if (matchingFilters != null) { 3306 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3307 // match the same intent. For performance reasons, it is better not to 3308 // run queryIntent twice for the same userId 3309 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3310 int size = matchingFilters.size(); 3311 for (int i = 0; i < size; i++) { 3312 CrossProfileIntentFilter filter = matchingFilters.get(i); 3313 int targetUserId = filter.getTargetUserId(); 3314 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3315 && !alreadyTriedUserIds.get(targetUserId)) { 3316 // Checking if there are activities in the target user that can handle the 3317 // intent. 3318 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3319 flags, sourceUserId); 3320 if (resolveInfo != null) return resolveInfo; 3321 alreadyTriedUserIds.put(targetUserId, true); 3322 } 3323 } 3324 } 3325 return null; 3326 } 3327 3328 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3329 String resolvedType, int flags, int sourceUserId) { 3330 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3331 resolvedType, flags, filter.getTargetUserId()); 3332 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3333 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3334 } 3335 return null; 3336 } 3337 3338 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3339 int sourceUserId, int targetUserId) { 3340 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3341 String className; 3342 if (targetUserId == UserHandle.USER_OWNER) { 3343 className = FORWARD_INTENT_TO_USER_OWNER; 3344 } else { 3345 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3346 } 3347 ComponentName forwardingActivityComponentName = new ComponentName( 3348 mAndroidApplication.packageName, className); 3349 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3350 sourceUserId); 3351 if (targetUserId == UserHandle.USER_OWNER) { 3352 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3353 forwardingResolveInfo.noResourceId = true; 3354 } 3355 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3356 forwardingResolveInfo.priority = 0; 3357 forwardingResolveInfo.preferredOrder = 0; 3358 forwardingResolveInfo.match = 0; 3359 forwardingResolveInfo.isDefault = true; 3360 forwardingResolveInfo.filter = filter; 3361 forwardingResolveInfo.targetUserId = targetUserId; 3362 return forwardingResolveInfo; 3363 } 3364 3365 @Override 3366 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3367 Intent[] specifics, String[] specificTypes, Intent intent, 3368 String resolvedType, int flags, int userId) { 3369 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3370 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3371 false, "query intent activity options"); 3372 final String resultsAction = intent.getAction(); 3373 3374 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3375 | PackageManager.GET_RESOLVED_FILTER, userId); 3376 3377 if (DEBUG_INTENT_MATCHING) { 3378 Log.v(TAG, "Query " + intent + ": " + results); 3379 } 3380 3381 int specificsPos = 0; 3382 int N; 3383 3384 // todo: note that the algorithm used here is O(N^2). This 3385 // isn't a problem in our current environment, but if we start running 3386 // into situations where we have more than 5 or 10 matches then this 3387 // should probably be changed to something smarter... 3388 3389 // First we go through and resolve each of the specific items 3390 // that were supplied, taking care of removing any corresponding 3391 // duplicate items in the generic resolve list. 3392 if (specifics != null) { 3393 for (int i=0; i<specifics.length; i++) { 3394 final Intent sintent = specifics[i]; 3395 if (sintent == null) { 3396 continue; 3397 } 3398 3399 if (DEBUG_INTENT_MATCHING) { 3400 Log.v(TAG, "Specific #" + i + ": " + sintent); 3401 } 3402 3403 String action = sintent.getAction(); 3404 if (resultsAction != null && resultsAction.equals(action)) { 3405 // If this action was explicitly requested, then don't 3406 // remove things that have it. 3407 action = null; 3408 } 3409 3410 ResolveInfo ri = null; 3411 ActivityInfo ai = null; 3412 3413 ComponentName comp = sintent.getComponent(); 3414 if (comp == null) { 3415 ri = resolveIntent( 3416 sintent, 3417 specificTypes != null ? specificTypes[i] : null, 3418 flags, userId); 3419 if (ri == null) { 3420 continue; 3421 } 3422 if (ri == mResolveInfo) { 3423 // ACK! Must do something better with this. 3424 } 3425 ai = ri.activityInfo; 3426 comp = new ComponentName(ai.applicationInfo.packageName, 3427 ai.name); 3428 } else { 3429 ai = getActivityInfo(comp, flags, userId); 3430 if (ai == null) { 3431 continue; 3432 } 3433 } 3434 3435 // Look for any generic query activities that are duplicates 3436 // of this specific one, and remove them from the results. 3437 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3438 N = results.size(); 3439 int j; 3440 for (j=specificsPos; j<N; j++) { 3441 ResolveInfo sri = results.get(j); 3442 if ((sri.activityInfo.name.equals(comp.getClassName()) 3443 && sri.activityInfo.applicationInfo.packageName.equals( 3444 comp.getPackageName())) 3445 || (action != null && sri.filter.matchAction(action))) { 3446 results.remove(j); 3447 if (DEBUG_INTENT_MATCHING) Log.v( 3448 TAG, "Removing duplicate item from " + j 3449 + " due to specific " + specificsPos); 3450 if (ri == null) { 3451 ri = sri; 3452 } 3453 j--; 3454 N--; 3455 } 3456 } 3457 3458 // Add this specific item to its proper place. 3459 if (ri == null) { 3460 ri = new ResolveInfo(); 3461 ri.activityInfo = ai; 3462 } 3463 results.add(specificsPos, ri); 3464 ri.specificIndex = i; 3465 specificsPos++; 3466 } 3467 } 3468 3469 // Now we go through the remaining generic results and remove any 3470 // duplicate actions that are found here. 3471 N = results.size(); 3472 for (int i=specificsPos; i<N-1; i++) { 3473 final ResolveInfo rii = results.get(i); 3474 if (rii.filter == null) { 3475 continue; 3476 } 3477 3478 // Iterate over all of the actions of this result's intent 3479 // filter... typically this should be just one. 3480 final Iterator<String> it = rii.filter.actionsIterator(); 3481 if (it == null) { 3482 continue; 3483 } 3484 while (it.hasNext()) { 3485 final String action = it.next(); 3486 if (resultsAction != null && resultsAction.equals(action)) { 3487 // If this action was explicitly requested, then don't 3488 // remove things that have it. 3489 continue; 3490 } 3491 for (int j=i+1; j<N; j++) { 3492 final ResolveInfo rij = results.get(j); 3493 if (rij.filter != null && rij.filter.hasAction(action)) { 3494 results.remove(j); 3495 if (DEBUG_INTENT_MATCHING) Log.v( 3496 TAG, "Removing duplicate item from " + j 3497 + " due to action " + action + " at " + i); 3498 j--; 3499 N--; 3500 } 3501 } 3502 } 3503 3504 // If the caller didn't request filter information, drop it now 3505 // so we don't have to marshall/unmarshall it. 3506 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3507 rii.filter = null; 3508 } 3509 } 3510 3511 // Filter out the caller activity if so requested. 3512 if (caller != null) { 3513 N = results.size(); 3514 for (int i=0; i<N; i++) { 3515 ActivityInfo ainfo = results.get(i).activityInfo; 3516 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3517 && caller.getClassName().equals(ainfo.name)) { 3518 results.remove(i); 3519 break; 3520 } 3521 } 3522 } 3523 3524 // If the caller didn't request filter information, 3525 // drop them now so we don't have to 3526 // marshall/unmarshall it. 3527 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3528 N = results.size(); 3529 for (int i=0; i<N; i++) { 3530 results.get(i).filter = null; 3531 } 3532 } 3533 3534 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3535 return results; 3536 } 3537 3538 @Override 3539 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3540 int userId) { 3541 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3542 ComponentName comp = intent.getComponent(); 3543 if (comp == null) { 3544 if (intent.getSelector() != null) { 3545 intent = intent.getSelector(); 3546 comp = intent.getComponent(); 3547 } 3548 } 3549 if (comp != null) { 3550 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3551 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3552 if (ai != null) { 3553 ResolveInfo ri = new ResolveInfo(); 3554 ri.activityInfo = ai; 3555 list.add(ri); 3556 } 3557 return list; 3558 } 3559 3560 // reader 3561 synchronized (mPackages) { 3562 String pkgName = intent.getPackage(); 3563 if (pkgName == null) { 3564 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3565 } 3566 final PackageParser.Package pkg = mPackages.get(pkgName); 3567 if (pkg != null) { 3568 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3569 userId); 3570 } 3571 return null; 3572 } 3573 } 3574 3575 @Override 3576 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3577 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3578 if (!sUserManager.exists(userId)) return null; 3579 if (query != null) { 3580 if (query.size() >= 1) { 3581 // If there is more than one service with the same priority, 3582 // just arbitrarily pick the first one. 3583 return query.get(0); 3584 } 3585 } 3586 return null; 3587 } 3588 3589 @Override 3590 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3591 int userId) { 3592 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3593 ComponentName comp = intent.getComponent(); 3594 if (comp == null) { 3595 if (intent.getSelector() != null) { 3596 intent = intent.getSelector(); 3597 comp = intent.getComponent(); 3598 } 3599 } 3600 if (comp != null) { 3601 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3602 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3603 if (si != null) { 3604 final ResolveInfo ri = new ResolveInfo(); 3605 ri.serviceInfo = si; 3606 list.add(ri); 3607 } 3608 return list; 3609 } 3610 3611 // reader 3612 synchronized (mPackages) { 3613 String pkgName = intent.getPackage(); 3614 if (pkgName == null) { 3615 return mServices.queryIntent(intent, resolvedType, flags, userId); 3616 } 3617 final PackageParser.Package pkg = mPackages.get(pkgName); 3618 if (pkg != null) { 3619 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3620 userId); 3621 } 3622 return null; 3623 } 3624 } 3625 3626 @Override 3627 public List<ResolveInfo> queryIntentContentProviders( 3628 Intent intent, String resolvedType, int flags, int userId) { 3629 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3630 ComponentName comp = intent.getComponent(); 3631 if (comp == null) { 3632 if (intent.getSelector() != null) { 3633 intent = intent.getSelector(); 3634 comp = intent.getComponent(); 3635 } 3636 } 3637 if (comp != null) { 3638 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3639 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3640 if (pi != null) { 3641 final ResolveInfo ri = new ResolveInfo(); 3642 ri.providerInfo = pi; 3643 list.add(ri); 3644 } 3645 return list; 3646 } 3647 3648 // reader 3649 synchronized (mPackages) { 3650 String pkgName = intent.getPackage(); 3651 if (pkgName == null) { 3652 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3653 } 3654 final PackageParser.Package pkg = mPackages.get(pkgName); 3655 if (pkg != null) { 3656 return mProviders.queryIntentForPackage( 3657 intent, resolvedType, flags, pkg.providers, userId); 3658 } 3659 return null; 3660 } 3661 } 3662 3663 @Override 3664 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3665 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3666 3667 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 3668 3669 // writer 3670 synchronized (mPackages) { 3671 ArrayList<PackageInfo> list; 3672 if (listUninstalled) { 3673 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3674 for (PackageSetting ps : mSettings.mPackages.values()) { 3675 PackageInfo pi; 3676 if (ps.pkg != null) { 3677 pi = generatePackageInfo(ps.pkg, flags, userId); 3678 } else { 3679 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3680 } 3681 if (pi != null) { 3682 list.add(pi); 3683 } 3684 } 3685 } else { 3686 list = new ArrayList<PackageInfo>(mPackages.size()); 3687 for (PackageParser.Package p : mPackages.values()) { 3688 PackageInfo pi = generatePackageInfo(p, flags, userId); 3689 if (pi != null) { 3690 list.add(pi); 3691 } 3692 } 3693 } 3694 3695 return new ParceledListSlice<PackageInfo>(list); 3696 } 3697 } 3698 3699 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3700 String[] permissions, boolean[] tmp, int flags, int userId) { 3701 int numMatch = 0; 3702 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3703 for (int i=0; i<permissions.length; i++) { 3704 if (gp.grantedPermissions.contains(permissions[i])) { 3705 tmp[i] = true; 3706 numMatch++; 3707 } else { 3708 tmp[i] = false; 3709 } 3710 } 3711 if (numMatch == 0) { 3712 return; 3713 } 3714 PackageInfo pi; 3715 if (ps.pkg != null) { 3716 pi = generatePackageInfo(ps.pkg, flags, userId); 3717 } else { 3718 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3719 } 3720 // The above might return null in cases of uninstalled apps or install-state 3721 // skew across users/profiles. 3722 if (pi != null) { 3723 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3724 if (numMatch == permissions.length) { 3725 pi.requestedPermissions = permissions; 3726 } else { 3727 pi.requestedPermissions = new String[numMatch]; 3728 numMatch = 0; 3729 for (int i=0; i<permissions.length; i++) { 3730 if (tmp[i]) { 3731 pi.requestedPermissions[numMatch] = permissions[i]; 3732 numMatch++; 3733 } 3734 } 3735 } 3736 } 3737 list.add(pi); 3738 } 3739 } 3740 3741 @Override 3742 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3743 String[] permissions, int flags, int userId) { 3744 if (!sUserManager.exists(userId)) return null; 3745 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3746 3747 // writer 3748 synchronized (mPackages) { 3749 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3750 boolean[] tmpBools = new boolean[permissions.length]; 3751 if (listUninstalled) { 3752 for (PackageSetting ps : mSettings.mPackages.values()) { 3753 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3754 } 3755 } else { 3756 for (PackageParser.Package pkg : mPackages.values()) { 3757 PackageSetting ps = (PackageSetting)pkg.mExtras; 3758 if (ps != null) { 3759 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3760 userId); 3761 } 3762 } 3763 } 3764 3765 return new ParceledListSlice<PackageInfo>(list); 3766 } 3767 } 3768 3769 @Override 3770 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3771 if (!sUserManager.exists(userId)) return null; 3772 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3773 3774 // writer 3775 synchronized (mPackages) { 3776 ArrayList<ApplicationInfo> list; 3777 if (listUninstalled) { 3778 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3779 for (PackageSetting ps : mSettings.mPackages.values()) { 3780 ApplicationInfo ai; 3781 if (ps.pkg != null) { 3782 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3783 ps.readUserState(userId), userId); 3784 } else { 3785 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3786 } 3787 if (ai != null) { 3788 list.add(ai); 3789 } 3790 } 3791 } else { 3792 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3793 for (PackageParser.Package p : mPackages.values()) { 3794 if (p.mExtras != null) { 3795 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3796 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3797 if (ai != null) { 3798 list.add(ai); 3799 } 3800 } 3801 } 3802 } 3803 3804 return new ParceledListSlice<ApplicationInfo>(list); 3805 } 3806 } 3807 3808 public List<ApplicationInfo> getPersistentApplications(int flags) { 3809 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3810 3811 // reader 3812 synchronized (mPackages) { 3813 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3814 final int userId = UserHandle.getCallingUserId(); 3815 while (i.hasNext()) { 3816 final PackageParser.Package p = i.next(); 3817 if (p.applicationInfo != null 3818 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3819 && (!mSafeMode || isSystemApp(p))) { 3820 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3821 if (ps != null) { 3822 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3823 ps.readUserState(userId), userId); 3824 if (ai != null) { 3825 finalList.add(ai); 3826 } 3827 } 3828 } 3829 } 3830 } 3831 3832 return finalList; 3833 } 3834 3835 @Override 3836 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3837 if (!sUserManager.exists(userId)) return null; 3838 // reader 3839 synchronized (mPackages) { 3840 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3841 PackageSetting ps = provider != null 3842 ? mSettings.mPackages.get(provider.owner.packageName) 3843 : null; 3844 return ps != null 3845 && mSettings.isEnabledLPr(provider.info, flags, userId) 3846 && (!mSafeMode || (provider.info.applicationInfo.flags 3847 &ApplicationInfo.FLAG_SYSTEM) != 0) 3848 ? PackageParser.generateProviderInfo(provider, flags, 3849 ps.readUserState(userId), userId) 3850 : null; 3851 } 3852 } 3853 3854 /** 3855 * @deprecated 3856 */ 3857 @Deprecated 3858 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3859 // reader 3860 synchronized (mPackages) { 3861 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3862 .entrySet().iterator(); 3863 final int userId = UserHandle.getCallingUserId(); 3864 while (i.hasNext()) { 3865 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3866 PackageParser.Provider p = entry.getValue(); 3867 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3868 3869 if (ps != null && p.syncable 3870 && (!mSafeMode || (p.info.applicationInfo.flags 3871 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3872 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3873 ps.readUserState(userId), userId); 3874 if (info != null) { 3875 outNames.add(entry.getKey()); 3876 outInfo.add(info); 3877 } 3878 } 3879 } 3880 } 3881 } 3882 3883 @Override 3884 public List<ProviderInfo> queryContentProviders(String processName, 3885 int uid, int flags) { 3886 ArrayList<ProviderInfo> finalList = null; 3887 // reader 3888 synchronized (mPackages) { 3889 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3890 final int userId = processName != null ? 3891 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3892 while (i.hasNext()) { 3893 final PackageParser.Provider p = i.next(); 3894 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3895 if (ps != null && p.info.authority != null 3896 && (processName == null 3897 || (p.info.processName.equals(processName) 3898 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3899 && mSettings.isEnabledLPr(p.info, flags, userId) 3900 && (!mSafeMode 3901 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3902 if (finalList == null) { 3903 finalList = new ArrayList<ProviderInfo>(3); 3904 } 3905 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3906 ps.readUserState(userId), userId); 3907 if (info != null) { 3908 finalList.add(info); 3909 } 3910 } 3911 } 3912 } 3913 3914 if (finalList != null) { 3915 Collections.sort(finalList, mProviderInitOrderSorter); 3916 } 3917 3918 return finalList; 3919 } 3920 3921 @Override 3922 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3923 int flags) { 3924 // reader 3925 synchronized (mPackages) { 3926 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3927 return PackageParser.generateInstrumentationInfo(i, flags); 3928 } 3929 } 3930 3931 @Override 3932 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3933 int flags) { 3934 ArrayList<InstrumentationInfo> finalList = 3935 new ArrayList<InstrumentationInfo>(); 3936 3937 // reader 3938 synchronized (mPackages) { 3939 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 3940 while (i.hasNext()) { 3941 final PackageParser.Instrumentation p = i.next(); 3942 if (targetPackage == null 3943 || targetPackage.equals(p.info.targetPackage)) { 3944 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 3945 flags); 3946 if (ii != null) { 3947 finalList.add(ii); 3948 } 3949 } 3950 } 3951 } 3952 3953 return finalList; 3954 } 3955 3956 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 3957 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 3958 if (overlays == null) { 3959 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 3960 return; 3961 } 3962 for (PackageParser.Package opkg : overlays.values()) { 3963 // Not much to do if idmap fails: we already logged the error 3964 // and we certainly don't want to abort installation of pkg simply 3965 // because an overlay didn't fit properly. For these reasons, 3966 // ignore the return value of createIdmapForPackagePairLI. 3967 createIdmapForPackagePairLI(pkg, opkg); 3968 } 3969 } 3970 3971 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 3972 PackageParser.Package opkg) { 3973 if (!opkg.mTrustedOverlay) { 3974 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 3975 opkg.baseCodePath + ": overlay not trusted"); 3976 return false; 3977 } 3978 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 3979 if (overlaySet == null) { 3980 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 3981 opkg.baseCodePath + " but target package has no known overlays"); 3982 return false; 3983 } 3984 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 3985 // TODO: generate idmap for split APKs 3986 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 3987 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 3988 + opkg.baseCodePath); 3989 return false; 3990 } 3991 PackageParser.Package[] overlayArray = 3992 overlaySet.values().toArray(new PackageParser.Package[0]); 3993 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 3994 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 3995 return p1.mOverlayPriority - p2.mOverlayPriority; 3996 } 3997 }; 3998 Arrays.sort(overlayArray, cmp); 3999 4000 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4001 int i = 0; 4002 for (PackageParser.Package p : overlayArray) { 4003 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4004 } 4005 return true; 4006 } 4007 4008 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4009 final File[] files = dir.listFiles(); 4010 if (ArrayUtils.isEmpty(files)) { 4011 Log.d(TAG, "No files in app dir " + dir); 4012 return; 4013 } 4014 4015 if (DEBUG_PACKAGE_SCANNING) { 4016 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4017 + " flags=0x" + Integer.toHexString(parseFlags)); 4018 } 4019 4020 for (File file : files) { 4021 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4022 && !PackageInstallerService.isStageName(file.getName()); 4023 if (!isPackage) { 4024 // Ignore entries which are not packages 4025 continue; 4026 } 4027 try { 4028 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4029 scanFlags, currentTime, null); 4030 } catch (PackageManagerException e) { 4031 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4032 4033 // Delete invalid userdata apps 4034 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4035 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4036 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4037 if (file.isDirectory()) { 4038 FileUtils.deleteContents(file); 4039 } 4040 file.delete(); 4041 } 4042 } 4043 } 4044 } 4045 4046 private static File getSettingsProblemFile() { 4047 File dataDir = Environment.getDataDirectory(); 4048 File systemDir = new File(dataDir, "system"); 4049 File fname = new File(systemDir, "uiderrors.txt"); 4050 return fname; 4051 } 4052 4053 static void reportSettingsProblem(int priority, String msg) { 4054 logCriticalInfo(priority, msg); 4055 } 4056 4057 static void logCriticalInfo(int priority, String msg) { 4058 Slog.println(priority, TAG, msg); 4059 EventLogTags.writePmCriticalInfo(msg); 4060 try { 4061 File fname = getSettingsProblemFile(); 4062 FileOutputStream out = new FileOutputStream(fname, true); 4063 PrintWriter pw = new FastPrintWriter(out); 4064 SimpleDateFormat formatter = new SimpleDateFormat(); 4065 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4066 pw.println(dateString + ": " + msg); 4067 pw.close(); 4068 FileUtils.setPermissions( 4069 fname.toString(), 4070 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4071 -1, -1); 4072 } catch (java.io.IOException e) { 4073 } 4074 } 4075 4076 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4077 PackageParser.Package pkg, File srcFile, int parseFlags) 4078 throws PackageManagerException { 4079 if (ps != null 4080 && ps.codePath.equals(srcFile) 4081 && ps.timeStamp == srcFile.lastModified() 4082 && !isCompatSignatureUpdateNeeded(pkg)) { 4083 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4084 if (ps.signatures.mSignatures != null 4085 && ps.signatures.mSignatures.length != 0 4086 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4087 // Optimization: reuse the existing cached certificates 4088 // if the package appears to be unchanged. 4089 pkg.mSignatures = ps.signatures.mSignatures; 4090 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4091 synchronized (mPackages) { 4092 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4093 } 4094 return; 4095 } 4096 4097 Slog.w(TAG, "PackageSetting for " + ps.name 4098 + " is missing signatures. Collecting certs again to recover them."); 4099 } else { 4100 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4101 } 4102 4103 try { 4104 pp.collectCertificates(pkg, parseFlags); 4105 pp.collectManifestDigest(pkg); 4106 } catch (PackageParserException e) { 4107 throw PackageManagerException.from(e); 4108 } 4109 } 4110 4111 /* 4112 * Scan a package and return the newly parsed package. 4113 * Returns null in case of errors and the error code is stored in mLastScanError 4114 */ 4115 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4116 long currentTime, UserHandle user) throws PackageManagerException { 4117 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4118 parseFlags |= mDefParseFlags; 4119 PackageParser pp = new PackageParser(); 4120 pp.setSeparateProcesses(mSeparateProcesses); 4121 pp.setOnlyCoreApps(mOnlyCore); 4122 pp.setDisplayMetrics(mMetrics); 4123 4124 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4125 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4126 } 4127 4128 final PackageParser.Package pkg; 4129 try { 4130 pkg = pp.parsePackage(scanFile, parseFlags); 4131 } catch (PackageParserException e) { 4132 throw PackageManagerException.from(e); 4133 } 4134 4135 PackageSetting ps = null; 4136 PackageSetting updatedPkg; 4137 // reader 4138 synchronized (mPackages) { 4139 // Look to see if we already know about this package. 4140 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4141 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4142 // This package has been renamed to its original name. Let's 4143 // use that. 4144 ps = mSettings.peekPackageLPr(oldName); 4145 } 4146 // If there was no original package, see one for the real package name. 4147 if (ps == null) { 4148 ps = mSettings.peekPackageLPr(pkg.packageName); 4149 } 4150 // Check to see if this package could be hiding/updating a system 4151 // package. Must look for it either under the original or real 4152 // package name depending on our state. 4153 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4154 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4155 } 4156 boolean updatedPkgBetter = false; 4157 // First check if this is a system package that may involve an update 4158 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4159 if (ps != null && !ps.codePath.equals(scanFile)) { 4160 // The path has changed from what was last scanned... check the 4161 // version of the new path against what we have stored to determine 4162 // what to do. 4163 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4164 if (pkg.mVersionCode < ps.versionCode) { 4165 // The system package has been updated and the code path does not match 4166 // Ignore entry. Skip it. 4167 logCriticalInfo(Log.INFO, "Package " + ps.name + " at " + scanFile 4168 + " ignored: updated version " + ps.versionCode 4169 + " better than this " + pkg.mVersionCode); 4170 if (!updatedPkg.codePath.equals(scanFile)) { 4171 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4172 + ps.name + " changing from " + updatedPkg.codePathString 4173 + " to " + scanFile); 4174 updatedPkg.codePath = scanFile; 4175 updatedPkg.codePathString = scanFile.toString(); 4176 // This is the point at which we know that the system-disk APK 4177 // for this package has moved during a reboot (e.g. due to an OTA), 4178 // so we need to reevaluate it for privilege policy. 4179 if (locationIsPrivileged(scanFile)) { 4180 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4181 } 4182 } 4183 updatedPkg.pkg = pkg; 4184 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4185 } else { 4186 // The current app on the system partition is better than 4187 // what we have updated to on the data partition; switch 4188 // back to the system partition version. 4189 // At this point, its safely assumed that package installation for 4190 // apps in system partition will go through. If not there won't be a working 4191 // version of the app 4192 // writer 4193 synchronized (mPackages) { 4194 // Just remove the loaded entries from package lists. 4195 mPackages.remove(ps.name); 4196 } 4197 4198 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4199 + "reverting from " + ps.codePathString 4200 + ": new version " + pkg.mVersionCode 4201 + " better than installed " + ps.versionCode); 4202 4203 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4204 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4205 getAppDexInstructionSets(ps)); 4206 synchronized (mInstallLock) { 4207 args.cleanUpResourcesLI(); 4208 } 4209 synchronized (mPackages) { 4210 mSettings.enableSystemPackageLPw(ps.name); 4211 } 4212 updatedPkgBetter = true; 4213 } 4214 } 4215 } 4216 4217 if (updatedPkg != null) { 4218 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4219 // initially 4220 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4221 4222 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4223 // flag set initially 4224 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4225 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4226 } 4227 } 4228 4229 // Verify certificates against what was last scanned 4230 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4231 4232 /* 4233 * A new system app appeared, but we already had a non-system one of the 4234 * same name installed earlier. 4235 */ 4236 boolean shouldHideSystemApp = false; 4237 if (updatedPkg == null && ps != null 4238 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4239 /* 4240 * Check to make sure the signatures match first. If they don't, 4241 * wipe the installed application and its data. 4242 */ 4243 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4244 != PackageManager.SIGNATURE_MATCH) { 4245 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4246 + " signatures don't match existing userdata copy; removing"); 4247 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4248 ps = null; 4249 } else { 4250 /* 4251 * If the newly-added system app is an older version than the 4252 * already installed version, hide it. It will be scanned later 4253 * and re-added like an update. 4254 */ 4255 if (pkg.mVersionCode < ps.versionCode) { 4256 shouldHideSystemApp = true; 4257 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4258 + " but new version " + pkg.mVersionCode + " better than installed " 4259 + ps.versionCode + "; hiding system"); 4260 } else { 4261 /* 4262 * The newly found system app is a newer version that the 4263 * one previously installed. Simply remove the 4264 * already-installed application and replace it with our own 4265 * while keeping the application data. 4266 */ 4267 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4268 + " reverting from " + ps.codePathString + ": new version " 4269 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4270 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4271 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4272 getAppDexInstructionSets(ps)); 4273 synchronized (mInstallLock) { 4274 args.cleanUpResourcesLI(); 4275 } 4276 } 4277 } 4278 } 4279 4280 // The apk is forward locked (not public) if its code and resources 4281 // are kept in different files. (except for app in either system or 4282 // vendor path). 4283 // TODO grab this value from PackageSettings 4284 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4285 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4286 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4287 } 4288 } 4289 4290 // TODO: extend to support forward-locked splits 4291 String resourcePath = null; 4292 String baseResourcePath = null; 4293 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4294 if (ps != null && ps.resourcePathString != null) { 4295 resourcePath = ps.resourcePathString; 4296 baseResourcePath = ps.resourcePathString; 4297 } else { 4298 // Should not happen at all. Just log an error. 4299 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4300 } 4301 } else { 4302 resourcePath = pkg.codePath; 4303 baseResourcePath = pkg.baseCodePath; 4304 } 4305 4306 // Set application objects path explicitly. 4307 pkg.applicationInfo.setCodePath(pkg.codePath); 4308 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4309 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4310 pkg.applicationInfo.setResourcePath(resourcePath); 4311 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4312 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4313 4314 // Note that we invoke the following method only if we are about to unpack an application 4315 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4316 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4317 4318 /* 4319 * If the system app should be overridden by a previously installed 4320 * data, hide the system app now and let the /data/app scan pick it up 4321 * again. 4322 */ 4323 if (shouldHideSystemApp) { 4324 synchronized (mPackages) { 4325 /* 4326 * We have to grant systems permissions before we hide, because 4327 * grantPermissions will assume the package update is trying to 4328 * expand its permissions. 4329 */ 4330 grantPermissionsLPw(pkg, true, pkg.packageName); 4331 mSettings.disableSystemPackageLPw(pkg.packageName); 4332 } 4333 } 4334 4335 return scannedPkg; 4336 } 4337 4338 private static String fixProcessName(String defProcessName, 4339 String processName, int uid) { 4340 if (processName == null) { 4341 return defProcessName; 4342 } 4343 return processName; 4344 } 4345 4346 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4347 throws PackageManagerException { 4348 if (pkgSetting.signatures.mSignatures != null) { 4349 // Already existing package. Make sure signatures match 4350 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4351 == PackageManager.SIGNATURE_MATCH; 4352 if (!match) { 4353 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4354 == PackageManager.SIGNATURE_MATCH; 4355 } 4356 if (!match) { 4357 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4358 + pkg.packageName + " signatures do not match the " 4359 + "previously installed version; ignoring!"); 4360 } 4361 } 4362 4363 // Check for shared user signatures 4364 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4365 // Already existing package. Make sure signatures match 4366 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4367 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4368 if (!match) { 4369 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4370 == PackageManager.SIGNATURE_MATCH; 4371 } 4372 if (!match) { 4373 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4374 "Package " + pkg.packageName 4375 + " has no signatures that match those in shared user " 4376 + pkgSetting.sharedUser.name + "; ignoring!"); 4377 } 4378 } 4379 } 4380 4381 /** 4382 * Enforces that only the system UID or root's UID can call a method exposed 4383 * via Binder. 4384 * 4385 * @param message used as message if SecurityException is thrown 4386 * @throws SecurityException if the caller is not system or root 4387 */ 4388 private static final void enforceSystemOrRoot(String message) { 4389 final int uid = Binder.getCallingUid(); 4390 if (uid != Process.SYSTEM_UID && uid != 0) { 4391 throw new SecurityException(message); 4392 } 4393 } 4394 4395 @Override 4396 public void performBootDexOpt() { 4397 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4398 4399 final HashSet<PackageParser.Package> pkgs; 4400 synchronized (mPackages) { 4401 pkgs = mDeferredDexOpt; 4402 mDeferredDexOpt = null; 4403 } 4404 4405 if (pkgs != null) { 4406 // Sort apps by importance for dexopt ordering. Important apps are given more priority 4407 // in case the device runs out of space. 4408 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 4409 // Give priority to system apps that listen for pre boot complete. 4410 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 4411 HashSet<String> pkgNames = getPackageNamesForIntent(intent); 4412 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4413 PackageParser.Package pkg = it.next(); 4414 if (pkgNames.contains(pkg.packageName)) { 4415 sortedPkgs.add(pkg); 4416 it.remove(); 4417 } 4418 } 4419 // Give priority to system apps. 4420 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4421 PackageParser.Package pkg = it.next(); 4422 if (isSystemApp(pkg)) { 4423 sortedPkgs.add(pkg); 4424 it.remove(); 4425 } 4426 } 4427 // Give priority to apps that listen for boot complete. 4428 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 4429 pkgNames = getPackageNamesForIntent(intent); 4430 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4431 PackageParser.Package pkg = it.next(); 4432 if (pkgNames.contains(pkg.packageName)) { 4433 sortedPkgs.add(pkg); 4434 it.remove(); 4435 } 4436 } 4437 // Filter out packages that aren't recently used. 4438 filterRecentlyUsedApps(pkgs); 4439 // Add all remaining apps. 4440 for (PackageParser.Package pkg : pkgs) { 4441 sortedPkgs.add(pkg); 4442 } 4443 4444 int i = 0; 4445 int total = sortedPkgs.size(); 4446 for (PackageParser.Package pkg : sortedPkgs) { 4447 performBootDexOpt(pkg, ++i, total); 4448 } 4449 } 4450 } 4451 4452 private void filterRecentlyUsedApps(HashSet<PackageParser.Package> pkgs) { 4453 // Filter out packages that aren't recently used. 4454 // 4455 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4456 // should do a full dexopt. 4457 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4458 // TODO: add a property to control this? 4459 long dexOptLRUThresholdInMinutes; 4460 if (mLazyDexOpt) { 4461 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4462 } else { 4463 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4464 } 4465 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4466 4467 int total = pkgs.size(); 4468 int skipped = 0; 4469 long now = System.currentTimeMillis(); 4470 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4471 PackageParser.Package pkg = i.next(); 4472 long then = pkg.mLastPackageUsageTimeInMills; 4473 if (then + dexOptLRUThresholdInMills < now) { 4474 if (DEBUG_DEXOPT) { 4475 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4476 ((then == 0) ? "never" : new Date(then))); 4477 } 4478 i.remove(); 4479 skipped++; 4480 } 4481 } 4482 if (DEBUG_DEXOPT) { 4483 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4484 } 4485 } 4486 } 4487 4488 private HashSet<String> getPackageNamesForIntent(Intent intent) { 4489 List<ResolveInfo> ris = null; 4490 try { 4491 ris = AppGlobals.getPackageManager().queryIntentReceivers( 4492 intent, null, 0, UserHandle.USER_OWNER); 4493 } catch (RemoteException e) { 4494 } 4495 HashSet<String> pkgNames = new HashSet<String>(); 4496 if (ris != null) { 4497 for (ResolveInfo ri : ris) { 4498 pkgNames.add(ri.activityInfo.packageName); 4499 } 4500 } 4501 return pkgNames; 4502 } 4503 4504 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 4505 if (DEBUG_DEXOPT) { 4506 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 4507 } 4508 if (!isFirstBoot()) { 4509 try { 4510 ActivityManagerNative.getDefault().showBootMessage( 4511 mContext.getResources().getString(R.string.android_upgrading_apk, 4512 curr, total), true); 4513 } catch (RemoteException e) { 4514 } 4515 } 4516 PackageParser.Package p = pkg; 4517 synchronized (mInstallLock) { 4518 performDexOptLI(p, null /* instruction sets */, false /* force dex */, 4519 false /* defer */, true /* include dependencies */); 4520 } 4521 } 4522 4523 @Override 4524 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4525 return performDexOpt(packageName, instructionSet, false); 4526 } 4527 4528 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4529 if (info.primaryCpuAbi == null) { 4530 return getPreferredInstructionSet(); 4531 } 4532 4533 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4534 } 4535 4536 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4537 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4538 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4539 if (!dexopt && !updateUsage) { 4540 // We aren't going to dexopt or update usage, so bail early. 4541 return false; 4542 } 4543 PackageParser.Package p; 4544 final String targetInstructionSet; 4545 synchronized (mPackages) { 4546 p = mPackages.get(packageName); 4547 if (p == null) { 4548 return false; 4549 } 4550 if (updateUsage) { 4551 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4552 } 4553 mPackageUsage.write(false); 4554 if (!dexopt) { 4555 // We aren't going to dexopt, so bail early. 4556 return false; 4557 } 4558 4559 targetInstructionSet = instructionSet != null ? instructionSet : 4560 getPrimaryInstructionSet(p.applicationInfo); 4561 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4562 return false; 4563 } 4564 } 4565 4566 synchronized (mInstallLock) { 4567 final String[] instructionSets = new String[] { targetInstructionSet }; 4568 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4569 true /* include dependencies */) == DEX_OPT_PERFORMED; 4570 } 4571 } 4572 4573 public HashSet<String> getPackagesThatNeedDexOpt() { 4574 HashSet<String> pkgs = null; 4575 synchronized (mPackages) { 4576 for (PackageParser.Package p : mPackages.values()) { 4577 if (DEBUG_DEXOPT) { 4578 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4579 } 4580 if (!p.mDexOptPerformed.isEmpty()) { 4581 continue; 4582 } 4583 if (pkgs == null) { 4584 pkgs = new HashSet<String>(); 4585 } 4586 pkgs.add(p.packageName); 4587 } 4588 } 4589 return pkgs; 4590 } 4591 4592 public void shutdown() { 4593 mPackageUsage.write(true); 4594 } 4595 4596 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4597 boolean forceDex, boolean defer, HashSet<String> done) { 4598 for (int i=0; i<libs.size(); i++) { 4599 PackageParser.Package libPkg; 4600 String libName; 4601 synchronized (mPackages) { 4602 libName = libs.get(i); 4603 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4604 if (lib != null && lib.apk != null) { 4605 libPkg = mPackages.get(lib.apk); 4606 } else { 4607 libPkg = null; 4608 } 4609 } 4610 if (libPkg != null && !done.contains(libName)) { 4611 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4612 } 4613 } 4614 } 4615 4616 static final int DEX_OPT_SKIPPED = 0; 4617 static final int DEX_OPT_PERFORMED = 1; 4618 static final int DEX_OPT_DEFERRED = 2; 4619 static final int DEX_OPT_FAILED = -1; 4620 4621 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4622 boolean forceDex, boolean defer, HashSet<String> done) { 4623 final String[] instructionSets = targetInstructionSets != null ? 4624 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4625 4626 if (done != null) { 4627 done.add(pkg.packageName); 4628 if (pkg.usesLibraries != null) { 4629 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4630 } 4631 if (pkg.usesOptionalLibraries != null) { 4632 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4633 } 4634 } 4635 4636 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4637 return DEX_OPT_SKIPPED; 4638 } 4639 4640 final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0; 4641 4642 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4643 boolean performedDexOpt = false; 4644 // There are three basic cases here: 4645 // 1.) we need to dexopt, either because we are forced or it is needed 4646 // 2.) we are defering a needed dexopt 4647 // 3.) we are skipping an unneeded dexopt 4648 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4649 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4650 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4651 continue; 4652 } 4653 4654 for (String path : paths) { 4655 try { 4656 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4657 // patckage or the one we find does not match the image checksum (i.e. it was 4658 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4659 // odex file and it matches the checksum of the image but not its base address, 4660 // meaning we need to move it. 4661 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4662 pkg.packageName, dexCodeInstructionSet, defer); 4663 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4664 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4665 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet 4666 + " vmSafeMode=" + vmSafeMode); 4667 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4668 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4669 pkg.packageName, dexCodeInstructionSet, vmSafeMode); 4670 4671 if (ret < 0) { 4672 // Don't bother running dexopt again if we failed, it will probably 4673 // just result in an error again. Also, don't bother dexopting for other 4674 // paths & ISAs. 4675 return DEX_OPT_FAILED; 4676 } 4677 4678 performedDexOpt = true; 4679 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4680 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4681 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4682 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4683 pkg.packageName, dexCodeInstructionSet); 4684 4685 if (ret < 0) { 4686 // Don't bother running patchoat again if we failed, it will probably 4687 // just result in an error again. Also, don't bother dexopting for other 4688 // paths & ISAs. 4689 return DEX_OPT_FAILED; 4690 } 4691 4692 performedDexOpt = true; 4693 } 4694 4695 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4696 // paths and instruction sets. We'll deal with them all together when we process 4697 // our list of deferred dexopts. 4698 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4699 if (mDeferredDexOpt == null) { 4700 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4701 } 4702 mDeferredDexOpt.add(pkg); 4703 return DEX_OPT_DEFERRED; 4704 } 4705 } catch (FileNotFoundException e) { 4706 Slog.w(TAG, "Apk not found for dexopt: " + path); 4707 return DEX_OPT_FAILED; 4708 } catch (IOException e) { 4709 Slog.w(TAG, "IOException reading apk: " + path, e); 4710 return DEX_OPT_FAILED; 4711 } catch (StaleDexCacheError e) { 4712 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4713 return DEX_OPT_FAILED; 4714 } catch (Exception e) { 4715 Slog.w(TAG, "Exception when doing dexopt : ", e); 4716 return DEX_OPT_FAILED; 4717 } 4718 } 4719 4720 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4721 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4722 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4723 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4724 // it. 4725 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4726 } 4727 4728 // If we've gotten here, we're sure that no error occurred and that we haven't 4729 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4730 // we've skipped all of them because they are up to date. In both cases this 4731 // package doesn't need dexopt any longer. 4732 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4733 } 4734 4735 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4736 if (info.primaryCpuAbi != null) { 4737 if (info.secondaryCpuAbi != null) { 4738 return new String[] { 4739 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4740 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4741 } else { 4742 return new String[] { 4743 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4744 } 4745 } 4746 4747 return new String[] { getPreferredInstructionSet() }; 4748 } 4749 4750 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4751 if (ps.primaryCpuAbiString != null) { 4752 if (ps.secondaryCpuAbiString != null) { 4753 return new String[] { 4754 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4755 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4756 } else { 4757 return new String[] { 4758 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4759 } 4760 } 4761 4762 return new String[] { getPreferredInstructionSet() }; 4763 } 4764 4765 private static String getPreferredInstructionSet() { 4766 if (sPreferredInstructionSet == null) { 4767 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4768 } 4769 4770 return sPreferredInstructionSet; 4771 } 4772 4773 private static List<String> getAllInstructionSets() { 4774 final String[] allAbis = Build.SUPPORTED_ABIS; 4775 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4776 4777 for (String abi : allAbis) { 4778 final String instructionSet = VMRuntime.getInstructionSet(abi); 4779 if (!allInstructionSets.contains(instructionSet)) { 4780 allInstructionSets.add(instructionSet); 4781 } 4782 } 4783 4784 return allInstructionSets; 4785 } 4786 4787 /** 4788 * Returns the instruction set that should be used to compile dex code. In the presence of 4789 * a native bridge this might be different than the one shared libraries use. 4790 */ 4791 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4792 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4793 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4794 } 4795 4796 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4797 HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length); 4798 for (String instructionSet : instructionSets) { 4799 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4800 } 4801 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4802 } 4803 4804 /** 4805 * Returns deduplicated list of supported instructions for dex code. 4806 */ 4807 public static String[] getAllDexCodeInstructionSets() { 4808 String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length]; 4809 for (int i = 0; i < supportedInstructionSets.length; i++) { 4810 String abi = Build.SUPPORTED_ABIS[i]; 4811 supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi); 4812 } 4813 return getDexCodeInstructionSets(supportedInstructionSets); 4814 } 4815 4816 @Override 4817 public void forceDexOpt(String packageName) { 4818 enforceSystemOrRoot("forceDexOpt"); 4819 4820 PackageParser.Package pkg; 4821 synchronized (mPackages) { 4822 pkg = mPackages.get(packageName); 4823 if (pkg == null) { 4824 throw new IllegalArgumentException("Missing package: " + packageName); 4825 } 4826 } 4827 4828 synchronized (mInstallLock) { 4829 final String[] instructionSets = new String[] { 4830 getPrimaryInstructionSet(pkg.applicationInfo) }; 4831 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4832 if (res != DEX_OPT_PERFORMED) { 4833 throw new IllegalStateException("Failed to dexopt: " + res); 4834 } 4835 } 4836 } 4837 4838 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4839 boolean forceDex, boolean defer, boolean inclDependencies) { 4840 HashSet<String> done; 4841 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4842 done = new HashSet<String>(); 4843 done.add(pkg.packageName); 4844 } else { 4845 done = null; 4846 } 4847 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4848 } 4849 4850 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4851 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4852 Slog.w(TAG, "Unable to update from " + oldPkg.name 4853 + " to " + newPkg.packageName 4854 + ": old package not in system partition"); 4855 return false; 4856 } else if (mPackages.get(oldPkg.name) != null) { 4857 Slog.w(TAG, "Unable to update from " + oldPkg.name 4858 + " to " + newPkg.packageName 4859 + ": old package still exists"); 4860 return false; 4861 } 4862 return true; 4863 } 4864 4865 File getDataPathForUser(int userId) { 4866 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4867 } 4868 4869 private File getDataPathForPackage(String packageName, int userId) { 4870 /* 4871 * Until we fully support multiple users, return the directory we 4872 * previously would have. The PackageManagerTests will need to be 4873 * revised when this is changed back.. 4874 */ 4875 if (userId == 0) { 4876 return new File(mAppDataDir, packageName); 4877 } else { 4878 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4879 + File.separator + packageName); 4880 } 4881 } 4882 4883 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4884 int[] users = sUserManager.getUserIds(); 4885 int res = mInstaller.install(packageName, uid, uid, seinfo); 4886 if (res < 0) { 4887 return res; 4888 } 4889 for (int user : users) { 4890 if (user != 0) { 4891 res = mInstaller.createUserData(packageName, 4892 UserHandle.getUid(user, uid), user, seinfo); 4893 if (res < 0) { 4894 return res; 4895 } 4896 } 4897 } 4898 return res; 4899 } 4900 4901 private int removeDataDirsLI(String packageName) { 4902 int[] users = sUserManager.getUserIds(); 4903 int res = 0; 4904 for (int user : users) { 4905 int resInner = mInstaller.remove(packageName, user); 4906 if (resInner < 0) { 4907 res = resInner; 4908 } 4909 } 4910 4911 return res; 4912 } 4913 4914 private int deleteCodeCacheDirsLI(String packageName) { 4915 int[] users = sUserManager.getUserIds(); 4916 int res = 0; 4917 for (int user : users) { 4918 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4919 if (resInner < 0) { 4920 res = resInner; 4921 } 4922 } 4923 return res; 4924 } 4925 4926 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4927 PackageParser.Package changingLib) { 4928 if (file.path != null) { 4929 usesLibraryFiles.add(file.path); 4930 return; 4931 } 4932 PackageParser.Package p = mPackages.get(file.apk); 4933 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4934 // If we are doing this while in the middle of updating a library apk, 4935 // then we need to make sure to use that new apk for determining the 4936 // dependencies here. (We haven't yet finished committing the new apk 4937 // to the package manager state.) 4938 if (p == null || p.packageName.equals(changingLib.packageName)) { 4939 p = changingLib; 4940 } 4941 } 4942 if (p != null) { 4943 usesLibraryFiles.addAll(p.getAllCodePaths()); 4944 } 4945 } 4946 4947 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4948 PackageParser.Package changingLib) throws PackageManagerException { 4949 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4950 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4951 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4952 for (int i=0; i<N; i++) { 4953 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4954 if (file == null) { 4955 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4956 "Package " + pkg.packageName + " requires unavailable shared library " 4957 + pkg.usesLibraries.get(i) + "; failing!"); 4958 } 4959 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4960 } 4961 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4962 for (int i=0; i<N; i++) { 4963 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4964 if (file == null) { 4965 Slog.w(TAG, "Package " + pkg.packageName 4966 + " desires unavailable shared library " 4967 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4968 } else { 4969 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4970 } 4971 } 4972 N = usesLibraryFiles.size(); 4973 if (N > 0) { 4974 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4975 } else { 4976 pkg.usesLibraryFiles = null; 4977 } 4978 } 4979 } 4980 4981 private static boolean hasString(List<String> list, List<String> which) { 4982 if (list == null) { 4983 return false; 4984 } 4985 for (int i=list.size()-1; i>=0; i--) { 4986 for (int j=which.size()-1; j>=0; j--) { 4987 if (which.get(j).equals(list.get(i))) { 4988 return true; 4989 } 4990 } 4991 } 4992 return false; 4993 } 4994 4995 private void updateAllSharedLibrariesLPw() { 4996 for (PackageParser.Package pkg : mPackages.values()) { 4997 try { 4998 updateSharedLibrariesLPw(pkg, null); 4999 } catch (PackageManagerException e) { 5000 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5001 } 5002 } 5003 } 5004 5005 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5006 PackageParser.Package changingPkg) { 5007 ArrayList<PackageParser.Package> res = null; 5008 for (PackageParser.Package pkg : mPackages.values()) { 5009 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5010 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5011 if (res == null) { 5012 res = new ArrayList<PackageParser.Package>(); 5013 } 5014 res.add(pkg); 5015 try { 5016 updateSharedLibrariesLPw(pkg, changingPkg); 5017 } catch (PackageManagerException e) { 5018 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5019 } 5020 } 5021 } 5022 return res; 5023 } 5024 5025 /** 5026 * Derive the value of the {@code cpuAbiOverride} based on the provided 5027 * value and an optional stored value from the package settings. 5028 */ 5029 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5030 String cpuAbiOverride = null; 5031 5032 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5033 cpuAbiOverride = null; 5034 } else if (abiOverride != null) { 5035 cpuAbiOverride = abiOverride; 5036 } else if (settings != null) { 5037 cpuAbiOverride = settings.cpuAbiOverrideString; 5038 } 5039 5040 return cpuAbiOverride; 5041 } 5042 5043 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5044 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5045 boolean success = false; 5046 try { 5047 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5048 currentTime, user); 5049 success = true; 5050 return res; 5051 } finally { 5052 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5053 removeDataDirsLI(pkg.packageName); 5054 } 5055 } 5056 } 5057 5058 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5059 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5060 final File scanFile = new File(pkg.codePath); 5061 if (pkg.applicationInfo.getCodePath() == null || 5062 pkg.applicationInfo.getResourcePath() == null) { 5063 // Bail out. The resource and code paths haven't been set. 5064 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5065 "Code and resource paths haven't been set correctly"); 5066 } 5067 5068 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5069 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5070 } 5071 5072 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5073 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5074 } 5075 5076 if (mCustomResolverComponentName != null && 5077 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5078 setUpCustomResolverActivity(pkg); 5079 } 5080 5081 if (pkg.packageName.equals("android")) { 5082 synchronized (mPackages) { 5083 if (mAndroidApplication != null) { 5084 Slog.w(TAG, "*************************************************"); 5085 Slog.w(TAG, "Core android package being redefined. Skipping."); 5086 Slog.w(TAG, " file=" + scanFile); 5087 Slog.w(TAG, "*************************************************"); 5088 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5089 "Core android package being redefined. Skipping."); 5090 } 5091 5092 // Set up information for our fall-back user intent resolution activity. 5093 mPlatformPackage = pkg; 5094 pkg.mVersionCode = mSdkVersion; 5095 mAndroidApplication = pkg.applicationInfo; 5096 5097 if (!mResolverReplaced) { 5098 mResolveActivity.applicationInfo = mAndroidApplication; 5099 mResolveActivity.name = ResolverActivity.class.getName(); 5100 mResolveActivity.packageName = mAndroidApplication.packageName; 5101 mResolveActivity.processName = "system:ui"; 5102 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5103 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5104 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5105 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5106 mResolveActivity.exported = true; 5107 mResolveActivity.enabled = true; 5108 mResolveInfo.activityInfo = mResolveActivity; 5109 mResolveInfo.priority = 0; 5110 mResolveInfo.preferredOrder = 0; 5111 mResolveInfo.match = 0; 5112 mResolveComponentName = new ComponentName( 5113 mAndroidApplication.packageName, mResolveActivity.name); 5114 } 5115 } 5116 } 5117 5118 if (DEBUG_PACKAGE_SCANNING) { 5119 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5120 Log.d(TAG, "Scanning package " + pkg.packageName); 5121 } 5122 5123 if (mPackages.containsKey(pkg.packageName) 5124 || mSharedLibraries.containsKey(pkg.packageName)) { 5125 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5126 "Application package " + pkg.packageName 5127 + " already installed. Skipping duplicate."); 5128 } 5129 5130 // Initialize package source and resource directories 5131 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5132 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5133 5134 SharedUserSetting suid = null; 5135 PackageSetting pkgSetting = null; 5136 5137 if (!isSystemApp(pkg)) { 5138 // Only system apps can use these features. 5139 pkg.mOriginalPackages = null; 5140 pkg.mRealPackage = null; 5141 pkg.mAdoptPermissions = null; 5142 } 5143 5144 // writer 5145 synchronized (mPackages) { 5146 if (pkg.mSharedUserId != null) { 5147 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5148 if (suid == null) { 5149 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5150 "Creating application package " + pkg.packageName 5151 + " for shared user failed"); 5152 } 5153 if (DEBUG_PACKAGE_SCANNING) { 5154 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5155 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5156 + "): packages=" + suid.packages); 5157 } 5158 } 5159 5160 // Check if we are renaming from an original package name. 5161 PackageSetting origPackage = null; 5162 String realName = null; 5163 if (pkg.mOriginalPackages != null) { 5164 // This package may need to be renamed to a previously 5165 // installed name. Let's check on that... 5166 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5167 if (pkg.mOriginalPackages.contains(renamed)) { 5168 // This package had originally been installed as the 5169 // original name, and we have already taken care of 5170 // transitioning to the new one. Just update the new 5171 // one to continue using the old name. 5172 realName = pkg.mRealPackage; 5173 if (!pkg.packageName.equals(renamed)) { 5174 // Callers into this function may have already taken 5175 // care of renaming the package; only do it here if 5176 // it is not already done. 5177 pkg.setPackageName(renamed); 5178 } 5179 5180 } else { 5181 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5182 if ((origPackage = mSettings.peekPackageLPr( 5183 pkg.mOriginalPackages.get(i))) != null) { 5184 // We do have the package already installed under its 5185 // original name... should we use it? 5186 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5187 // New package is not compatible with original. 5188 origPackage = null; 5189 continue; 5190 } else if (origPackage.sharedUser != null) { 5191 // Make sure uid is compatible between packages. 5192 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5193 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5194 + " to " + pkg.packageName + ": old uid " 5195 + origPackage.sharedUser.name 5196 + " differs from " + pkg.mSharedUserId); 5197 origPackage = null; 5198 continue; 5199 } 5200 } else { 5201 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5202 + pkg.packageName + " to old name " + origPackage.name); 5203 } 5204 break; 5205 } 5206 } 5207 } 5208 } 5209 5210 if (mTransferedPackages.contains(pkg.packageName)) { 5211 Slog.w(TAG, "Package " + pkg.packageName 5212 + " was transferred to another, but its .apk remains"); 5213 } 5214 5215 // Just create the setting, don't add it yet. For already existing packages 5216 // the PkgSetting exists already and doesn't have to be created. 5217 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5218 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5219 pkg.applicationInfo.primaryCpuAbi, 5220 pkg.applicationInfo.secondaryCpuAbi, 5221 pkg.applicationInfo.flags, user, false); 5222 if (pkgSetting == null) { 5223 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5224 "Creating application package " + pkg.packageName + " failed"); 5225 } 5226 5227 if (pkgSetting.origPackage != null) { 5228 // If we are first transitioning from an original package, 5229 // fix up the new package's name now. We need to do this after 5230 // looking up the package under its new name, so getPackageLP 5231 // can take care of fiddling things correctly. 5232 pkg.setPackageName(origPackage.name); 5233 5234 // File a report about this. 5235 String msg = "New package " + pkgSetting.realName 5236 + " renamed to replace old package " + pkgSetting.name; 5237 reportSettingsProblem(Log.WARN, msg); 5238 5239 // Make a note of it. 5240 mTransferedPackages.add(origPackage.name); 5241 5242 // No longer need to retain this. 5243 pkgSetting.origPackage = null; 5244 } 5245 5246 if (realName != null) { 5247 // Make a note of it. 5248 mTransferedPackages.add(pkg.packageName); 5249 } 5250 5251 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5252 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5253 } 5254 5255 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5256 // Check all shared libraries and map to their actual file path. 5257 // We only do this here for apps not on a system dir, because those 5258 // are the only ones that can fail an install due to this. We 5259 // will take care of the system apps by updating all of their 5260 // library paths after the scan is done. 5261 updateSharedLibrariesLPw(pkg, null); 5262 } 5263 5264 if (mFoundPolicyFile) { 5265 SELinuxMMAC.assignSeinfoValue(pkg); 5266 } 5267 5268 pkg.applicationInfo.uid = pkgSetting.appId; 5269 pkg.mExtras = pkgSetting; 5270 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5271 try { 5272 verifySignaturesLP(pkgSetting, pkg); 5273 } catch (PackageManagerException e) { 5274 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5275 throw e; 5276 } 5277 // The signature has changed, but this package is in the system 5278 // image... let's recover! 5279 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5280 // However... if this package is part of a shared user, but it 5281 // doesn't match the signature of the shared user, let's fail. 5282 // What this means is that you can't change the signatures 5283 // associated with an overall shared user, which doesn't seem all 5284 // that unreasonable. 5285 if (pkgSetting.sharedUser != null) { 5286 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5287 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5288 throw new PackageManagerException( 5289 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5290 "Signature mismatch for shared user : " 5291 + pkgSetting.sharedUser); 5292 } 5293 } 5294 // File a report about this. 5295 String msg = "System package " + pkg.packageName 5296 + " signature changed; retaining data."; 5297 reportSettingsProblem(Log.WARN, msg); 5298 } 5299 } else { 5300 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5301 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5302 + pkg.packageName + " upgrade keys do not match the " 5303 + "previously installed version"); 5304 } else { 5305 // signatures may have changed as result of upgrade 5306 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5307 } 5308 } 5309 // Verify that this new package doesn't have any content providers 5310 // that conflict with existing packages. Only do this if the 5311 // package isn't already installed, since we don't want to break 5312 // things that are installed. 5313 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5314 final int N = pkg.providers.size(); 5315 int i; 5316 for (i=0; i<N; i++) { 5317 PackageParser.Provider p = pkg.providers.get(i); 5318 if (p.info.authority != null) { 5319 String names[] = p.info.authority.split(";"); 5320 for (int j = 0; j < names.length; j++) { 5321 if (mProvidersByAuthority.containsKey(names[j])) { 5322 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5323 final String otherPackageName = 5324 ((other != null && other.getComponentName() != null) ? 5325 other.getComponentName().getPackageName() : "?"); 5326 throw new PackageManagerException( 5327 INSTALL_FAILED_CONFLICTING_PROVIDER, 5328 "Can't install because provider name " + names[j] 5329 + " (in package " + pkg.applicationInfo.packageName 5330 + ") is already used by " + otherPackageName); 5331 } 5332 } 5333 } 5334 } 5335 } 5336 5337 if (pkg.mAdoptPermissions != null) { 5338 // This package wants to adopt ownership of permissions from 5339 // another package. 5340 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5341 final String origName = pkg.mAdoptPermissions.get(i); 5342 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5343 if (orig != null) { 5344 if (verifyPackageUpdateLPr(orig, pkg)) { 5345 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5346 + pkg.packageName); 5347 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5348 } 5349 } 5350 } 5351 } 5352 } 5353 5354 final String pkgName = pkg.packageName; 5355 5356 final long scanFileTime = scanFile.lastModified(); 5357 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5358 pkg.applicationInfo.processName = fixProcessName( 5359 pkg.applicationInfo.packageName, 5360 pkg.applicationInfo.processName, 5361 pkg.applicationInfo.uid); 5362 5363 File dataPath; 5364 if (mPlatformPackage == pkg) { 5365 // The system package is special. 5366 dataPath = new File(Environment.getDataDirectory(), "system"); 5367 5368 pkg.applicationInfo.dataDir = dataPath.getPath(); 5369 5370 } else { 5371 // This is a normal package, need to make its data directory. 5372 dataPath = getDataPathForPackage(pkg.packageName, 0); 5373 5374 boolean uidError = false; 5375 if (dataPath.exists()) { 5376 int currentUid = 0; 5377 try { 5378 StructStat stat = Os.stat(dataPath.getPath()); 5379 currentUid = stat.st_uid; 5380 } catch (ErrnoException e) { 5381 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5382 } 5383 5384 // If we have mismatched owners for the data path, we have a problem. 5385 if (currentUid != pkg.applicationInfo.uid) { 5386 boolean recovered = false; 5387 if (currentUid == 0) { 5388 // The directory somehow became owned by root. Wow. 5389 // This is probably because the system was stopped while 5390 // installd was in the middle of messing with its libs 5391 // directory. Ask installd to fix that. 5392 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5393 pkg.applicationInfo.uid); 5394 if (ret >= 0) { 5395 recovered = true; 5396 String msg = "Package " + pkg.packageName 5397 + " unexpectedly changed to uid 0; recovered to " + 5398 + pkg.applicationInfo.uid; 5399 reportSettingsProblem(Log.WARN, msg); 5400 } 5401 } 5402 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5403 || (scanFlags&SCAN_BOOTING) != 0)) { 5404 // If this is a system app, we can at least delete its 5405 // current data so the application will still work. 5406 int ret = removeDataDirsLI(pkgName); 5407 if (ret >= 0) { 5408 // TODO: Kill the processes first 5409 // Old data gone! 5410 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5411 ? "System package " : "Third party package "; 5412 String msg = prefix + pkg.packageName 5413 + " has changed from uid: " 5414 + currentUid + " to " 5415 + pkg.applicationInfo.uid + "; old data erased"; 5416 reportSettingsProblem(Log.WARN, msg); 5417 recovered = true; 5418 5419 // And now re-install the app. 5420 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5421 pkg.applicationInfo.seinfo); 5422 if (ret == -1) { 5423 // Ack should not happen! 5424 msg = prefix + pkg.packageName 5425 + " could not have data directory re-created after delete."; 5426 reportSettingsProblem(Log.WARN, msg); 5427 throw new PackageManagerException( 5428 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5429 } 5430 } 5431 if (!recovered) { 5432 mHasSystemUidErrors = true; 5433 } 5434 } else if (!recovered) { 5435 // If we allow this install to proceed, we will be broken. 5436 // Abort, abort! 5437 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5438 "scanPackageLI"); 5439 } 5440 if (!recovered) { 5441 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5442 + pkg.applicationInfo.uid + "/fs_" 5443 + currentUid; 5444 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5445 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5446 String msg = "Package " + pkg.packageName 5447 + " has mismatched uid: " 5448 + currentUid + " on disk, " 5449 + pkg.applicationInfo.uid + " in settings"; 5450 // writer 5451 synchronized (mPackages) { 5452 mSettings.mReadMessages.append(msg); 5453 mSettings.mReadMessages.append('\n'); 5454 uidError = true; 5455 if (!pkgSetting.uidError) { 5456 reportSettingsProblem(Log.ERROR, msg); 5457 } 5458 } 5459 } 5460 } 5461 pkg.applicationInfo.dataDir = dataPath.getPath(); 5462 if (mShouldRestoreconData) { 5463 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5464 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5465 pkg.applicationInfo.uid); 5466 } 5467 } else { 5468 if (DEBUG_PACKAGE_SCANNING) { 5469 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5470 Log.v(TAG, "Want this data dir: " + dataPath); 5471 } 5472 //invoke installer to do the actual installation 5473 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5474 pkg.applicationInfo.seinfo); 5475 if (ret < 0) { 5476 // Error from installer 5477 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5478 "Unable to create data dirs [errorCode=" + ret + "]"); 5479 } 5480 5481 if (dataPath.exists()) { 5482 pkg.applicationInfo.dataDir = dataPath.getPath(); 5483 } else { 5484 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5485 pkg.applicationInfo.dataDir = null; 5486 } 5487 } 5488 5489 pkgSetting.uidError = uidError; 5490 } 5491 5492 final String path = scanFile.getPath(); 5493 final String codePath = pkg.applicationInfo.getCodePath(); 5494 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5495 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5496 setBundledAppAbisAndRoots(pkg, pkgSetting); 5497 5498 // If we haven't found any native libraries for the app, check if it has 5499 // renderscript code. We'll need to force the app to 32 bit if it has 5500 // renderscript bitcode. 5501 if (pkg.applicationInfo.primaryCpuAbi == null 5502 && pkg.applicationInfo.secondaryCpuAbi == null 5503 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5504 NativeLibraryHelper.Handle handle = null; 5505 try { 5506 handle = NativeLibraryHelper.Handle.create(scanFile); 5507 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5508 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5509 } 5510 } catch (IOException ioe) { 5511 Slog.w(TAG, "Error scanning system app : " + ioe); 5512 } finally { 5513 IoUtils.closeQuietly(handle); 5514 } 5515 } 5516 5517 setNativeLibraryPaths(pkg); 5518 } else { 5519 // TODO: We can probably be smarter about this stuff. For installed apps, 5520 // we can calculate this information at install time once and for all. For 5521 // system apps, we can probably assume that this information doesn't change 5522 // after the first boot scan. As things stand, we do lots of unnecessary work. 5523 5524 // Give ourselves some initial paths; we'll come back for another 5525 // pass once we've determined ABI below. 5526 setNativeLibraryPaths(pkg); 5527 5528 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5529 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5530 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5531 5532 NativeLibraryHelper.Handle handle = null; 5533 try { 5534 handle = NativeLibraryHelper.Handle.create(scanFile); 5535 // TODO(multiArch): This can be null for apps that didn't go through the 5536 // usual installation process. We can calculate it again, like we 5537 // do during install time. 5538 // 5539 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5540 // unnecessary. 5541 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5542 5543 // Null out the abis so that they can be recalculated. 5544 pkg.applicationInfo.primaryCpuAbi = null; 5545 pkg.applicationInfo.secondaryCpuAbi = null; 5546 if (isMultiArch(pkg.applicationInfo)) { 5547 // Warn if we've set an abiOverride for multi-lib packages.. 5548 // By definition, we need to copy both 32 and 64 bit libraries for 5549 // such packages. 5550 if (pkg.cpuAbiOverride != null 5551 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5552 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5553 } 5554 5555 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5556 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5557 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5558 if (isAsec) { 5559 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5560 } else { 5561 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5562 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5563 useIsaSpecificSubdirs); 5564 } 5565 } 5566 5567 maybeThrowExceptionForMultiArchCopy( 5568 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5569 5570 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5571 if (isAsec) { 5572 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5573 } else { 5574 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5575 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5576 useIsaSpecificSubdirs); 5577 } 5578 } 5579 5580 maybeThrowExceptionForMultiArchCopy( 5581 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5582 5583 if (abi64 >= 0) { 5584 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5585 } 5586 5587 if (abi32 >= 0) { 5588 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5589 if (abi64 >= 0) { 5590 pkg.applicationInfo.secondaryCpuAbi = abi; 5591 } else { 5592 pkg.applicationInfo.primaryCpuAbi = abi; 5593 } 5594 } 5595 } else { 5596 String[] abiList = (cpuAbiOverride != null) ? 5597 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5598 5599 // Enable gross and lame hacks for apps that are built with old 5600 // SDK tools. We must scan their APKs for renderscript bitcode and 5601 // not launch them if it's present. Don't bother checking on devices 5602 // that don't have 64 bit support. 5603 boolean needsRenderScriptOverride = false; 5604 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5605 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5606 abiList = Build.SUPPORTED_32_BIT_ABIS; 5607 needsRenderScriptOverride = true; 5608 } 5609 5610 final int copyRet; 5611 if (isAsec) { 5612 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5613 } else { 5614 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5615 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5616 } 5617 5618 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5619 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5620 "Error unpackaging native libs for app, errorCode=" + copyRet); 5621 } 5622 5623 if (copyRet >= 0) { 5624 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5625 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5626 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5627 } else if (needsRenderScriptOverride) { 5628 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5629 } 5630 } 5631 } catch (IOException ioe) { 5632 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5633 } finally { 5634 IoUtils.closeQuietly(handle); 5635 } 5636 5637 // Now that we've calculated the ABIs and determined if it's an internal app, 5638 // we will go ahead and populate the nativeLibraryPath. 5639 setNativeLibraryPaths(pkg); 5640 5641 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5642 final int[] userIds = sUserManager.getUserIds(); 5643 synchronized (mInstallLock) { 5644 // Create a native library symlink only if we have native libraries 5645 // and if the native libraries are 32 bit libraries. We do not provide 5646 // this symlink for 64 bit libraries. 5647 if (pkg.applicationInfo.primaryCpuAbi != null && 5648 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5649 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5650 for (int userId : userIds) { 5651 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5652 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5653 "Failed linking native library dir (user=" + userId + ")"); 5654 } 5655 } 5656 } 5657 } 5658 } 5659 5660 // This is a special case for the "system" package, where the ABI is 5661 // dictated by the zygote configuration (and init.rc). We should keep track 5662 // of this ABI so that we can deal with "normal" applications that run under 5663 // the same UID correctly. 5664 if (mPlatformPackage == pkg) { 5665 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5666 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5667 } 5668 5669 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5670 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5671 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5672 // Copy the derived override back to the parsed package, so that we can 5673 // update the package settings accordingly. 5674 pkg.cpuAbiOverride = cpuAbiOverride; 5675 5676 if (DEBUG_ABI_SELECTION) { 5677 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5678 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5679 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5680 } 5681 5682 // Push the derived path down into PackageSettings so we know what to 5683 // clean up at uninstall time. 5684 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5685 5686 if (DEBUG_ABI_SELECTION) { 5687 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5688 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5689 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5690 } 5691 5692 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5693 // We don't do this here during boot because we can do it all 5694 // at once after scanning all existing packages. 5695 // 5696 // We also do this *before* we perform dexopt on this package, so that 5697 // we can avoid redundant dexopts, and also to make sure we've got the 5698 // code and package path correct. 5699 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5700 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5701 } 5702 5703 if ((scanFlags & SCAN_NO_DEX) == 0) { 5704 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, 5705 (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { 5706 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5707 } 5708 } 5709 5710 if (mFactoryTest && pkg.requestedPermissions.contains( 5711 android.Manifest.permission.FACTORY_TEST)) { 5712 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5713 } 5714 5715 ArrayList<PackageParser.Package> clientLibPkgs = null; 5716 5717 // writer 5718 synchronized (mPackages) { 5719 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5720 // Only system apps can add new shared libraries. 5721 if (pkg.libraryNames != null) { 5722 for (int i=0; i<pkg.libraryNames.size(); i++) { 5723 String name = pkg.libraryNames.get(i); 5724 boolean allowed = false; 5725 if (isUpdatedSystemApp(pkg)) { 5726 // New library entries can only be added through the 5727 // system image. This is important to get rid of a lot 5728 // of nasty edge cases: for example if we allowed a non- 5729 // system update of the app to add a library, then uninstalling 5730 // the update would make the library go away, and assumptions 5731 // we made such as through app install filtering would now 5732 // have allowed apps on the device which aren't compatible 5733 // with it. Better to just have the restriction here, be 5734 // conservative, and create many fewer cases that can negatively 5735 // impact the user experience. 5736 final PackageSetting sysPs = mSettings 5737 .getDisabledSystemPkgLPr(pkg.packageName); 5738 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5739 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5740 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5741 allowed = true; 5742 allowed = true; 5743 break; 5744 } 5745 } 5746 } 5747 } else { 5748 allowed = true; 5749 } 5750 if (allowed) { 5751 if (!mSharedLibraries.containsKey(name)) { 5752 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5753 } else if (!name.equals(pkg.packageName)) { 5754 Slog.w(TAG, "Package " + pkg.packageName + " library " 5755 + name + " already exists; skipping"); 5756 } 5757 } else { 5758 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5759 + name + " that is not declared on system image; skipping"); 5760 } 5761 } 5762 if ((scanFlags&SCAN_BOOTING) == 0) { 5763 // If we are not booting, we need to update any applications 5764 // that are clients of our shared library. If we are booting, 5765 // this will all be done once the scan is complete. 5766 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5767 } 5768 } 5769 } 5770 } 5771 5772 // We also need to dexopt any apps that are dependent on this library. Note that 5773 // if these fail, we should abort the install since installing the library will 5774 // result in some apps being broken. 5775 if (clientLibPkgs != null) { 5776 if ((scanFlags & SCAN_NO_DEX) == 0) { 5777 for (int i = 0; i < clientLibPkgs.size(); i++) { 5778 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5779 if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex, 5780 (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { 5781 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5782 "scanPackageLI failed to dexopt clientLibPkgs"); 5783 } 5784 } 5785 } 5786 } 5787 5788 // Request the ActivityManager to kill the process(only for existing packages) 5789 // so that we do not end up in a confused state while the user is still using the older 5790 // version of the application while the new one gets installed. 5791 if ((scanFlags & SCAN_REPLACING) != 0) { 5792 killApplication(pkg.applicationInfo.packageName, 5793 pkg.applicationInfo.uid, "update pkg"); 5794 } 5795 5796 // Also need to kill any apps that are dependent on the library. 5797 if (clientLibPkgs != null) { 5798 for (int i=0; i<clientLibPkgs.size(); i++) { 5799 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5800 killApplication(clientPkg.applicationInfo.packageName, 5801 clientPkg.applicationInfo.uid, "update lib"); 5802 } 5803 } 5804 5805 // writer 5806 synchronized (mPackages) { 5807 // We don't expect installation to fail beyond this point 5808 5809 // Add the new setting to mSettings 5810 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5811 // Add the new setting to mPackages 5812 mPackages.put(pkg.applicationInfo.packageName, pkg); 5813 // Make sure we don't accidentally delete its data. 5814 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5815 while (iter.hasNext()) { 5816 PackageCleanItem item = iter.next(); 5817 if (pkgName.equals(item.packageName)) { 5818 iter.remove(); 5819 } 5820 } 5821 5822 // Take care of first install / last update times. 5823 if (currentTime != 0) { 5824 if (pkgSetting.firstInstallTime == 0) { 5825 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5826 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5827 pkgSetting.lastUpdateTime = currentTime; 5828 } 5829 } else if (pkgSetting.firstInstallTime == 0) { 5830 // We need *something*. Take time time stamp of the file. 5831 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5832 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5833 if (scanFileTime != pkgSetting.timeStamp) { 5834 // A package on the system image has changed; consider this 5835 // to be an update. 5836 pkgSetting.lastUpdateTime = scanFileTime; 5837 } 5838 } 5839 5840 // Add the package's KeySets to the global KeySetManagerService 5841 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5842 try { 5843 // Old KeySetData no longer valid. 5844 ksms.removeAppKeySetDataLPw(pkg.packageName); 5845 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5846 if (pkg.mKeySetMapping != null) { 5847 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5848 pkg.mKeySetMapping.entrySet()) { 5849 if (entry.getValue() != null) { 5850 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5851 entry.getValue(), entry.getKey()); 5852 } 5853 } 5854 if (pkg.mUpgradeKeySets != null) { 5855 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5856 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5857 } 5858 } 5859 } 5860 } catch (NullPointerException e) { 5861 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5862 } catch (IllegalArgumentException e) { 5863 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5864 } 5865 5866 int N = pkg.providers.size(); 5867 StringBuilder r = null; 5868 int i; 5869 for (i=0; i<N; i++) { 5870 PackageParser.Provider p = pkg.providers.get(i); 5871 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5872 p.info.processName, pkg.applicationInfo.uid); 5873 mProviders.addProvider(p); 5874 p.syncable = p.info.isSyncable; 5875 if (p.info.authority != null) { 5876 String names[] = p.info.authority.split(";"); 5877 p.info.authority = null; 5878 for (int j = 0; j < names.length; j++) { 5879 if (j == 1 && p.syncable) { 5880 // We only want the first authority for a provider to possibly be 5881 // syncable, so if we already added this provider using a different 5882 // authority clear the syncable flag. We copy the provider before 5883 // changing it because the mProviders object contains a reference 5884 // to a provider that we don't want to change. 5885 // Only do this for the second authority since the resulting provider 5886 // object can be the same for all future authorities for this provider. 5887 p = new PackageParser.Provider(p); 5888 p.syncable = false; 5889 } 5890 if (!mProvidersByAuthority.containsKey(names[j])) { 5891 mProvidersByAuthority.put(names[j], p); 5892 if (p.info.authority == null) { 5893 p.info.authority = names[j]; 5894 } else { 5895 p.info.authority = p.info.authority + ";" + names[j]; 5896 } 5897 if (DEBUG_PACKAGE_SCANNING) { 5898 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5899 Log.d(TAG, "Registered content provider: " + names[j] 5900 + ", className = " + p.info.name + ", isSyncable = " 5901 + p.info.isSyncable); 5902 } 5903 } else { 5904 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5905 Slog.w(TAG, "Skipping provider name " + names[j] + 5906 " (in package " + pkg.applicationInfo.packageName + 5907 "): name already used by " 5908 + ((other != null && other.getComponentName() != null) 5909 ? other.getComponentName().getPackageName() : "?")); 5910 } 5911 } 5912 } 5913 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5914 if (r == null) { 5915 r = new StringBuilder(256); 5916 } else { 5917 r.append(' '); 5918 } 5919 r.append(p.info.name); 5920 } 5921 } 5922 if (r != null) { 5923 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5924 } 5925 5926 N = pkg.services.size(); 5927 r = null; 5928 for (i=0; i<N; i++) { 5929 PackageParser.Service s = pkg.services.get(i); 5930 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5931 s.info.processName, pkg.applicationInfo.uid); 5932 mServices.addService(s); 5933 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5934 if (r == null) { 5935 r = new StringBuilder(256); 5936 } else { 5937 r.append(' '); 5938 } 5939 r.append(s.info.name); 5940 } 5941 } 5942 if (r != null) { 5943 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5944 } 5945 5946 N = pkg.receivers.size(); 5947 r = null; 5948 for (i=0; i<N; i++) { 5949 PackageParser.Activity a = pkg.receivers.get(i); 5950 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5951 a.info.processName, pkg.applicationInfo.uid); 5952 mReceivers.addActivity(a, "receiver"); 5953 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5954 if (r == null) { 5955 r = new StringBuilder(256); 5956 } else { 5957 r.append(' '); 5958 } 5959 r.append(a.info.name); 5960 } 5961 } 5962 if (r != null) { 5963 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5964 } 5965 5966 N = pkg.activities.size(); 5967 r = null; 5968 for (i=0; i<N; i++) { 5969 PackageParser.Activity a = pkg.activities.get(i); 5970 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5971 a.info.processName, pkg.applicationInfo.uid); 5972 mActivities.addActivity(a, "activity"); 5973 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5974 if (r == null) { 5975 r = new StringBuilder(256); 5976 } else { 5977 r.append(' '); 5978 } 5979 r.append(a.info.name); 5980 } 5981 } 5982 if (r != null) { 5983 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5984 } 5985 5986 N = pkg.permissionGroups.size(); 5987 r = null; 5988 for (i=0; i<N; i++) { 5989 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5990 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5991 if (cur == null) { 5992 mPermissionGroups.put(pg.info.name, pg); 5993 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5994 if (r == null) { 5995 r = new StringBuilder(256); 5996 } else { 5997 r.append(' '); 5998 } 5999 r.append(pg.info.name); 6000 } 6001 } else { 6002 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6003 + pg.info.packageName + " ignored: original from " 6004 + cur.info.packageName); 6005 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6006 if (r == null) { 6007 r = new StringBuilder(256); 6008 } else { 6009 r.append(' '); 6010 } 6011 r.append("DUP:"); 6012 r.append(pg.info.name); 6013 } 6014 } 6015 } 6016 if (r != null) { 6017 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6018 } 6019 6020 N = pkg.permissions.size(); 6021 r = null; 6022 for (i=0; i<N; i++) { 6023 PackageParser.Permission p = pkg.permissions.get(i); 6024 HashMap<String, BasePermission> permissionMap = 6025 p.tree ? mSettings.mPermissionTrees 6026 : mSettings.mPermissions; 6027 p.group = mPermissionGroups.get(p.info.group); 6028 if (p.info.group == null || p.group != null) { 6029 BasePermission bp = permissionMap.get(p.info.name); 6030 6031 // Allow system apps to redefine non-system permissions 6032 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6033 final boolean currentOwnerIsSystem = (bp.perm != null 6034 && isSystemApp(bp.perm.owner)); 6035 if (isSystemApp(p.owner)) { 6036 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6037 // It's a built-in permission and no owner, take ownership now 6038 bp.packageSetting = pkgSetting; 6039 bp.perm = p; 6040 bp.uid = pkg.applicationInfo.uid; 6041 bp.sourcePackage = p.info.packageName; 6042 } else if (!currentOwnerIsSystem) { 6043 String msg = "New decl " + p.owner + " of permission " 6044 + p.info.name + " is system; overriding " + bp.sourcePackage; 6045 reportSettingsProblem(Log.WARN, msg); 6046 bp = null; 6047 } 6048 } 6049 } 6050 6051 if (bp == null) { 6052 bp = new BasePermission(p.info.name, p.info.packageName, 6053 BasePermission.TYPE_NORMAL); 6054 permissionMap.put(p.info.name, bp); 6055 } 6056 6057 if (bp.perm == null) { 6058 if (bp.sourcePackage == null 6059 || bp.sourcePackage.equals(p.info.packageName)) { 6060 BasePermission tree = findPermissionTreeLP(p.info.name); 6061 if (tree == null 6062 || tree.sourcePackage.equals(p.info.packageName)) { 6063 bp.packageSetting = pkgSetting; 6064 bp.perm = p; 6065 bp.uid = pkg.applicationInfo.uid; 6066 bp.sourcePackage = p.info.packageName; 6067 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6068 if (r == null) { 6069 r = new StringBuilder(256); 6070 } else { 6071 r.append(' '); 6072 } 6073 r.append(p.info.name); 6074 } 6075 } else { 6076 Slog.w(TAG, "Permission " + p.info.name + " from package " 6077 + p.info.packageName + " ignored: base tree " 6078 + tree.name + " is from package " 6079 + tree.sourcePackage); 6080 } 6081 } else { 6082 Slog.w(TAG, "Permission " + p.info.name + " from package " 6083 + p.info.packageName + " ignored: original from " 6084 + bp.sourcePackage); 6085 } 6086 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6087 if (r == null) { 6088 r = new StringBuilder(256); 6089 } else { 6090 r.append(' '); 6091 } 6092 r.append("DUP:"); 6093 r.append(p.info.name); 6094 } 6095 if (bp.perm == p) { 6096 bp.protectionLevel = p.info.protectionLevel; 6097 } 6098 } else { 6099 Slog.w(TAG, "Permission " + p.info.name + " from package " 6100 + p.info.packageName + " ignored: no group " 6101 + p.group); 6102 } 6103 } 6104 if (r != null) { 6105 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6106 } 6107 6108 N = pkg.instrumentation.size(); 6109 r = null; 6110 for (i=0; i<N; i++) { 6111 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6112 a.info.packageName = pkg.applicationInfo.packageName; 6113 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6114 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6115 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6116 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6117 a.info.dataDir = pkg.applicationInfo.dataDir; 6118 6119 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6120 // need other information about the application, like the ABI and what not ? 6121 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6122 mInstrumentation.put(a.getComponentName(), a); 6123 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6124 if (r == null) { 6125 r = new StringBuilder(256); 6126 } else { 6127 r.append(' '); 6128 } 6129 r.append(a.info.name); 6130 } 6131 } 6132 if (r != null) { 6133 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6134 } 6135 6136 if (pkg.protectedBroadcasts != null) { 6137 N = pkg.protectedBroadcasts.size(); 6138 for (i=0; i<N; i++) { 6139 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6140 } 6141 } 6142 6143 pkgSetting.setTimeStamp(scanFileTime); 6144 6145 // Create idmap files for pairs of (packages, overlay packages). 6146 // Note: "android", ie framework-res.apk, is handled by native layers. 6147 if (pkg.mOverlayTarget != null) { 6148 // This is an overlay package. 6149 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6150 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6151 mOverlays.put(pkg.mOverlayTarget, 6152 new HashMap<String, PackageParser.Package>()); 6153 } 6154 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6155 map.put(pkg.packageName, pkg); 6156 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6157 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6158 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6159 "scanPackageLI failed to createIdmap"); 6160 } 6161 } 6162 } else if (mOverlays.containsKey(pkg.packageName) && 6163 !pkg.packageName.equals("android")) { 6164 // This is a regular package, with one or more known overlay packages. 6165 createIdmapsForPackageLI(pkg); 6166 } 6167 } 6168 6169 return pkg; 6170 } 6171 6172 /** 6173 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6174 * i.e, so that all packages can be run inside a single process if required. 6175 * 6176 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6177 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6178 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6179 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6180 * updating a package that belongs to a shared user. 6181 * 6182 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6183 * adds unnecessary complexity. 6184 */ 6185 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6186 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6187 String requiredInstructionSet = null; 6188 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6189 requiredInstructionSet = VMRuntime.getInstructionSet( 6190 scannedPackage.applicationInfo.primaryCpuAbi); 6191 } 6192 6193 PackageSetting requirer = null; 6194 for (PackageSetting ps : packagesForUser) { 6195 // If packagesForUser contains scannedPackage, we skip it. This will happen 6196 // when scannedPackage is an update of an existing package. Without this check, 6197 // we will never be able to change the ABI of any package belonging to a shared 6198 // user, even if it's compatible with other packages. 6199 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6200 if (ps.primaryCpuAbiString == null) { 6201 continue; 6202 } 6203 6204 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6205 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6206 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6207 // this but there's not much we can do. 6208 String errorMessage = "Instruction set mismatch, " 6209 + ((requirer == null) ? "[caller]" : requirer) 6210 + " requires " + requiredInstructionSet + " whereas " + ps 6211 + " requires " + instructionSet; 6212 Slog.w(TAG, errorMessage); 6213 } 6214 6215 if (requiredInstructionSet == null) { 6216 requiredInstructionSet = instructionSet; 6217 requirer = ps; 6218 } 6219 } 6220 } 6221 6222 if (requiredInstructionSet != null) { 6223 String adjustedAbi; 6224 if (requirer != null) { 6225 // requirer != null implies that either scannedPackage was null or that scannedPackage 6226 // did not require an ABI, in which case we have to adjust scannedPackage to match 6227 // the ABI of the set (which is the same as requirer's ABI) 6228 adjustedAbi = requirer.primaryCpuAbiString; 6229 if (scannedPackage != null) { 6230 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6231 } 6232 } else { 6233 // requirer == null implies that we're updating all ABIs in the set to 6234 // match scannedPackage. 6235 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6236 } 6237 6238 for (PackageSetting ps : packagesForUser) { 6239 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6240 if (ps.primaryCpuAbiString != null) { 6241 continue; 6242 } 6243 6244 ps.primaryCpuAbiString = adjustedAbi; 6245 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6246 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6247 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6248 6249 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6250 deferDexOpt, true) == DEX_OPT_FAILED) { 6251 ps.primaryCpuAbiString = null; 6252 ps.pkg.applicationInfo.primaryCpuAbi = null; 6253 return; 6254 } else { 6255 mInstaller.rmdex(ps.codePathString, 6256 getDexCodeInstructionSet(getPreferredInstructionSet())); 6257 } 6258 } 6259 } 6260 } 6261 } 6262 } 6263 6264 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6265 synchronized (mPackages) { 6266 mResolverReplaced = true; 6267 // Set up information for custom user intent resolution activity. 6268 mResolveActivity.applicationInfo = pkg.applicationInfo; 6269 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6270 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6271 mResolveActivity.processName = null; 6272 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6273 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6274 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6275 mResolveActivity.theme = 0; 6276 mResolveActivity.exported = true; 6277 mResolveActivity.enabled = true; 6278 mResolveInfo.activityInfo = mResolveActivity; 6279 mResolveInfo.priority = 0; 6280 mResolveInfo.preferredOrder = 0; 6281 mResolveInfo.match = 0; 6282 mResolveComponentName = mCustomResolverComponentName; 6283 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6284 mResolveComponentName); 6285 } 6286 } 6287 6288 private static String calculateBundledApkRoot(final String codePathString) { 6289 final File codePath = new File(codePathString); 6290 final File codeRoot; 6291 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6292 codeRoot = Environment.getRootDirectory(); 6293 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6294 codeRoot = Environment.getOemDirectory(); 6295 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6296 codeRoot = Environment.getVendorDirectory(); 6297 } else { 6298 // Unrecognized code path; take its top real segment as the apk root: 6299 // e.g. /something/app/blah.apk => /something 6300 try { 6301 File f = codePath.getCanonicalFile(); 6302 File parent = f.getParentFile(); // non-null because codePath is a file 6303 File tmp; 6304 while ((tmp = parent.getParentFile()) != null) { 6305 f = parent; 6306 parent = tmp; 6307 } 6308 codeRoot = f; 6309 Slog.w(TAG, "Unrecognized code path " 6310 + codePath + " - using " + codeRoot); 6311 } catch (IOException e) { 6312 // Can't canonicalize the code path -- shenanigans? 6313 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6314 return Environment.getRootDirectory().getPath(); 6315 } 6316 } 6317 return codeRoot.getPath(); 6318 } 6319 6320 /** 6321 * Derive and set the location of native libraries for the given package, 6322 * which varies depending on where and how the package was installed. 6323 */ 6324 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6325 final ApplicationInfo info = pkg.applicationInfo; 6326 final String codePath = pkg.codePath; 6327 final File codeFile = new File(codePath); 6328 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6329 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6330 6331 info.nativeLibraryRootDir = null; 6332 info.nativeLibraryRootRequiresIsa = false; 6333 info.nativeLibraryDir = null; 6334 info.secondaryNativeLibraryDir = null; 6335 6336 if (isApkFile(codeFile)) { 6337 // Monolithic install 6338 if (bundledApp) { 6339 // If "/system/lib64/apkname" exists, assume that is the per-package 6340 // native library directory to use; otherwise use "/system/lib/apkname". 6341 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6342 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6343 getPrimaryInstructionSet(info)); 6344 6345 // This is a bundled system app so choose the path based on the ABI. 6346 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6347 // is just the default path. 6348 final String apkName = deriveCodePathName(codePath); 6349 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6350 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6351 apkName).getAbsolutePath(); 6352 6353 if (info.secondaryCpuAbi != null) { 6354 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6355 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6356 secondaryLibDir, apkName).getAbsolutePath(); 6357 } 6358 } else if (asecApp) { 6359 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6360 .getAbsolutePath(); 6361 } else { 6362 final String apkName = deriveCodePathName(codePath); 6363 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6364 .getAbsolutePath(); 6365 } 6366 6367 info.nativeLibraryRootRequiresIsa = false; 6368 info.nativeLibraryDir = info.nativeLibraryRootDir; 6369 } else { 6370 // Cluster install 6371 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6372 info.nativeLibraryRootRequiresIsa = true; 6373 6374 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6375 getPrimaryInstructionSet(info)).getAbsolutePath(); 6376 6377 if (info.secondaryCpuAbi != null) { 6378 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6379 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6380 } 6381 } 6382 } 6383 6384 /** 6385 * Calculate the abis and roots for a bundled app. These can uniquely 6386 * be determined from the contents of the system partition, i.e whether 6387 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6388 * of this information, and instead assume that the system was built 6389 * sensibly. 6390 */ 6391 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6392 PackageSetting pkgSetting) { 6393 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6394 6395 // If "/system/lib64/apkname" exists, assume that is the per-package 6396 // native library directory to use; otherwise use "/system/lib/apkname". 6397 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6398 setBundledAppAbi(pkg, apkRoot, apkName); 6399 // pkgSetting might be null during rescan following uninstall of updates 6400 // to a bundled app, so accommodate that possibility. The settings in 6401 // that case will be established later from the parsed package. 6402 // 6403 // If the settings aren't null, sync them up with what we've just derived. 6404 // note that apkRoot isn't stored in the package settings. 6405 if (pkgSetting != null) { 6406 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6407 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6408 } 6409 } 6410 6411 /** 6412 * Deduces the ABI of a bundled app and sets the relevant fields on the 6413 * parsed pkg object. 6414 * 6415 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6416 * under which system libraries are installed. 6417 * @param apkName the name of the installed package. 6418 */ 6419 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6420 final File codeFile = new File(pkg.codePath); 6421 6422 final boolean has64BitLibs; 6423 final boolean has32BitLibs; 6424 if (isApkFile(codeFile)) { 6425 // Monolithic install 6426 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6427 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6428 } else { 6429 // Cluster install 6430 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6431 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6432 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6433 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6434 has64BitLibs = (new File(rootDir, isa)).exists(); 6435 } else { 6436 has64BitLibs = false; 6437 } 6438 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6439 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6440 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6441 has32BitLibs = (new File(rootDir, isa)).exists(); 6442 } else { 6443 has32BitLibs = false; 6444 } 6445 } 6446 6447 if (has64BitLibs && !has32BitLibs) { 6448 // The package has 64 bit libs, but not 32 bit libs. Its primary 6449 // ABI should be 64 bit. We can safely assume here that the bundled 6450 // native libraries correspond to the most preferred ABI in the list. 6451 6452 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6453 pkg.applicationInfo.secondaryCpuAbi = null; 6454 } else if (has32BitLibs && !has64BitLibs) { 6455 // The package has 32 bit libs but not 64 bit libs. Its primary 6456 // ABI should be 32 bit. 6457 6458 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6459 pkg.applicationInfo.secondaryCpuAbi = null; 6460 } else if (has32BitLibs && has64BitLibs) { 6461 // The application has both 64 and 32 bit bundled libraries. We check 6462 // here that the app declares multiArch support, and warn if it doesn't. 6463 // 6464 // We will be lenient here and record both ABIs. The primary will be the 6465 // ABI that's higher on the list, i.e, a device that's configured to prefer 6466 // 64 bit apps will see a 64 bit primary ABI, 6467 6468 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6469 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6470 } 6471 6472 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6473 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6474 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6475 } else { 6476 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6477 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6478 } 6479 } else { 6480 pkg.applicationInfo.primaryCpuAbi = null; 6481 pkg.applicationInfo.secondaryCpuAbi = null; 6482 } 6483 } 6484 6485 private void killApplication(String pkgName, int appId, String reason) { 6486 // Request the ActivityManager to kill the process(only for existing packages) 6487 // so that we do not end up in a confused state while the user is still using the older 6488 // version of the application while the new one gets installed. 6489 IActivityManager am = ActivityManagerNative.getDefault(); 6490 if (am != null) { 6491 try { 6492 am.killApplicationWithAppId(pkgName, appId, reason); 6493 } catch (RemoteException e) { 6494 } 6495 } 6496 } 6497 6498 void removePackageLI(PackageSetting ps, boolean chatty) { 6499 if (DEBUG_INSTALL) { 6500 if (chatty) 6501 Log.d(TAG, "Removing package " + ps.name); 6502 } 6503 6504 // writer 6505 synchronized (mPackages) { 6506 mPackages.remove(ps.name); 6507 final PackageParser.Package pkg = ps.pkg; 6508 if (pkg != null) { 6509 cleanPackageDataStructuresLILPw(pkg, chatty); 6510 } 6511 } 6512 } 6513 6514 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6515 if (DEBUG_INSTALL) { 6516 if (chatty) 6517 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6518 } 6519 6520 // writer 6521 synchronized (mPackages) { 6522 mPackages.remove(pkg.applicationInfo.packageName); 6523 cleanPackageDataStructuresLILPw(pkg, chatty); 6524 } 6525 } 6526 6527 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6528 int N = pkg.providers.size(); 6529 StringBuilder r = null; 6530 int i; 6531 for (i=0; i<N; i++) { 6532 PackageParser.Provider p = pkg.providers.get(i); 6533 mProviders.removeProvider(p); 6534 if (p.info.authority == null) { 6535 6536 /* There was another ContentProvider with this authority when 6537 * this app was installed so this authority is null, 6538 * Ignore it as we don't have to unregister the provider. 6539 */ 6540 continue; 6541 } 6542 String names[] = p.info.authority.split(";"); 6543 for (int j = 0; j < names.length; j++) { 6544 if (mProvidersByAuthority.get(names[j]) == p) { 6545 mProvidersByAuthority.remove(names[j]); 6546 if (DEBUG_REMOVE) { 6547 if (chatty) 6548 Log.d(TAG, "Unregistered content provider: " + names[j] 6549 + ", className = " + p.info.name + ", isSyncable = " 6550 + p.info.isSyncable); 6551 } 6552 } 6553 } 6554 if (DEBUG_REMOVE && chatty) { 6555 if (r == null) { 6556 r = new StringBuilder(256); 6557 } else { 6558 r.append(' '); 6559 } 6560 r.append(p.info.name); 6561 } 6562 } 6563 if (r != null) { 6564 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6565 } 6566 6567 N = pkg.services.size(); 6568 r = null; 6569 for (i=0; i<N; i++) { 6570 PackageParser.Service s = pkg.services.get(i); 6571 mServices.removeService(s); 6572 if (chatty) { 6573 if (r == null) { 6574 r = new StringBuilder(256); 6575 } else { 6576 r.append(' '); 6577 } 6578 r.append(s.info.name); 6579 } 6580 } 6581 if (r != null) { 6582 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6583 } 6584 6585 N = pkg.receivers.size(); 6586 r = null; 6587 for (i=0; i<N; i++) { 6588 PackageParser.Activity a = pkg.receivers.get(i); 6589 mReceivers.removeActivity(a, "receiver"); 6590 if (DEBUG_REMOVE && chatty) { 6591 if (r == null) { 6592 r = new StringBuilder(256); 6593 } else { 6594 r.append(' '); 6595 } 6596 r.append(a.info.name); 6597 } 6598 } 6599 if (r != null) { 6600 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6601 } 6602 6603 N = pkg.activities.size(); 6604 r = null; 6605 for (i=0; i<N; i++) { 6606 PackageParser.Activity a = pkg.activities.get(i); 6607 mActivities.removeActivity(a, "activity"); 6608 if (DEBUG_REMOVE && chatty) { 6609 if (r == null) { 6610 r = new StringBuilder(256); 6611 } else { 6612 r.append(' '); 6613 } 6614 r.append(a.info.name); 6615 } 6616 } 6617 if (r != null) { 6618 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6619 } 6620 6621 N = pkg.permissions.size(); 6622 r = null; 6623 for (i=0; i<N; i++) { 6624 PackageParser.Permission p = pkg.permissions.get(i); 6625 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6626 if (bp == null) { 6627 bp = mSettings.mPermissionTrees.get(p.info.name); 6628 } 6629 if (bp != null && bp.perm == p) { 6630 bp.perm = null; 6631 if (DEBUG_REMOVE && chatty) { 6632 if (r == null) { 6633 r = new StringBuilder(256); 6634 } else { 6635 r.append(' '); 6636 } 6637 r.append(p.info.name); 6638 } 6639 } 6640 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6641 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6642 if (appOpPerms != null) { 6643 appOpPerms.remove(pkg.packageName); 6644 } 6645 } 6646 } 6647 if (r != null) { 6648 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6649 } 6650 6651 N = pkg.requestedPermissions.size(); 6652 r = null; 6653 for (i=0; i<N; i++) { 6654 String perm = pkg.requestedPermissions.get(i); 6655 BasePermission bp = mSettings.mPermissions.get(perm); 6656 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6657 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6658 if (appOpPerms != null) { 6659 appOpPerms.remove(pkg.packageName); 6660 if (appOpPerms.isEmpty()) { 6661 mAppOpPermissionPackages.remove(perm); 6662 } 6663 } 6664 } 6665 } 6666 if (r != null) { 6667 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6668 } 6669 6670 N = pkg.instrumentation.size(); 6671 r = null; 6672 for (i=0; i<N; i++) { 6673 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6674 mInstrumentation.remove(a.getComponentName()); 6675 if (DEBUG_REMOVE && chatty) { 6676 if (r == null) { 6677 r = new StringBuilder(256); 6678 } else { 6679 r.append(' '); 6680 } 6681 r.append(a.info.name); 6682 } 6683 } 6684 if (r != null) { 6685 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6686 } 6687 6688 r = null; 6689 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6690 // Only system apps can hold shared libraries. 6691 if (pkg.libraryNames != null) { 6692 for (i=0; i<pkg.libraryNames.size(); i++) { 6693 String name = pkg.libraryNames.get(i); 6694 SharedLibraryEntry cur = mSharedLibraries.get(name); 6695 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6696 mSharedLibraries.remove(name); 6697 if (DEBUG_REMOVE && chatty) { 6698 if (r == null) { 6699 r = new StringBuilder(256); 6700 } else { 6701 r.append(' '); 6702 } 6703 r.append(name); 6704 } 6705 } 6706 } 6707 } 6708 } 6709 if (r != null) { 6710 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6711 } 6712 } 6713 6714 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6715 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6716 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6717 return true; 6718 } 6719 } 6720 return false; 6721 } 6722 6723 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6724 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6725 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6726 6727 private void updatePermissionsLPw(String changingPkg, 6728 PackageParser.Package pkgInfo, int flags) { 6729 // Make sure there are no dangling permission trees. 6730 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6731 while (it.hasNext()) { 6732 final BasePermission bp = it.next(); 6733 if (bp.packageSetting == null) { 6734 // We may not yet have parsed the package, so just see if 6735 // we still know about its settings. 6736 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6737 } 6738 if (bp.packageSetting == null) { 6739 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6740 + " from package " + bp.sourcePackage); 6741 it.remove(); 6742 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6743 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6744 Slog.i(TAG, "Removing old permission tree: " + bp.name 6745 + " from package " + bp.sourcePackage); 6746 flags |= UPDATE_PERMISSIONS_ALL; 6747 it.remove(); 6748 } 6749 } 6750 } 6751 6752 // Make sure all dynamic permissions have been assigned to a package, 6753 // and make sure there are no dangling permissions. 6754 it = mSettings.mPermissions.values().iterator(); 6755 while (it.hasNext()) { 6756 final BasePermission bp = it.next(); 6757 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6758 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6759 + bp.name + " pkg=" + bp.sourcePackage 6760 + " info=" + bp.pendingInfo); 6761 if (bp.packageSetting == null && bp.pendingInfo != null) { 6762 final BasePermission tree = findPermissionTreeLP(bp.name); 6763 if (tree != null && tree.perm != null) { 6764 bp.packageSetting = tree.packageSetting; 6765 bp.perm = new PackageParser.Permission(tree.perm.owner, 6766 new PermissionInfo(bp.pendingInfo)); 6767 bp.perm.info.packageName = tree.perm.info.packageName; 6768 bp.perm.info.name = bp.name; 6769 bp.uid = tree.uid; 6770 } 6771 } 6772 } 6773 if (bp.packageSetting == null) { 6774 // We may not yet have parsed the package, so just see if 6775 // we still know about its settings. 6776 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6777 } 6778 if (bp.packageSetting == null) { 6779 Slog.w(TAG, "Removing dangling permission: " + bp.name 6780 + " from package " + bp.sourcePackage); 6781 it.remove(); 6782 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6783 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6784 Slog.i(TAG, "Removing old permission: " + bp.name 6785 + " from package " + bp.sourcePackage); 6786 flags |= UPDATE_PERMISSIONS_ALL; 6787 it.remove(); 6788 } 6789 } 6790 } 6791 6792 // Now update the permissions for all packages, in particular 6793 // replace the granted permissions of the system packages. 6794 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6795 for (PackageParser.Package pkg : mPackages.values()) { 6796 if (pkg != pkgInfo) { 6797 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 6798 changingPkg); 6799 } 6800 } 6801 } 6802 6803 if (pkgInfo != null) { 6804 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 6805 } 6806 } 6807 6808 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 6809 String packageOfInterest) { 6810 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6811 if (ps == null) { 6812 return; 6813 } 6814 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6815 HashSet<String> origPermissions = gp.grantedPermissions; 6816 boolean changedPermission = false; 6817 6818 if (replace) { 6819 ps.permissionsFixed = false; 6820 if (gp == ps) { 6821 origPermissions = new HashSet<String>(gp.grantedPermissions); 6822 gp.grantedPermissions.clear(); 6823 gp.gids = mGlobalGids; 6824 } 6825 } 6826 6827 if (gp.gids == null) { 6828 gp.gids = mGlobalGids; 6829 } 6830 6831 final int N = pkg.requestedPermissions.size(); 6832 for (int i=0; i<N; i++) { 6833 final String name = pkg.requestedPermissions.get(i); 6834 final boolean required = pkg.requestedPermissionsRequired.get(i); 6835 final BasePermission bp = mSettings.mPermissions.get(name); 6836 if (DEBUG_INSTALL) { 6837 if (gp != ps) { 6838 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6839 } 6840 } 6841 6842 if (bp == null || bp.packageSetting == null) { 6843 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6844 Slog.w(TAG, "Unknown permission " + name 6845 + " in package " + pkg.packageName); 6846 } 6847 continue; 6848 } 6849 6850 final String perm = bp.name; 6851 boolean allowed; 6852 boolean allowedSig = false; 6853 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6854 // Keep track of app op permissions. 6855 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6856 if (pkgs == null) { 6857 pkgs = new ArraySet<>(); 6858 mAppOpPermissionPackages.put(bp.name, pkgs); 6859 } 6860 pkgs.add(pkg.packageName); 6861 } 6862 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6863 if (level == PermissionInfo.PROTECTION_NORMAL 6864 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6865 // We grant a normal or dangerous permission if any of the following 6866 // are true: 6867 // 1) The permission is required 6868 // 2) The permission is optional, but was granted in the past 6869 // 3) The permission is optional, but was requested by an 6870 // app in /system (not /data) 6871 // 6872 // Otherwise, reject the permission. 6873 allowed = (required || origPermissions.contains(perm) 6874 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6875 } else if (bp.packageSetting == null) { 6876 // This permission is invalid; skip it. 6877 allowed = false; 6878 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6879 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6880 if (allowed) { 6881 allowedSig = true; 6882 } 6883 } else { 6884 allowed = false; 6885 } 6886 if (DEBUG_INSTALL) { 6887 if (gp != ps) { 6888 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6889 } 6890 } 6891 if (allowed) { 6892 if (!isSystemApp(ps) && ps.permissionsFixed) { 6893 // If this is an existing, non-system package, then 6894 // we can't add any new permissions to it. 6895 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6896 // Except... if this is a permission that was added 6897 // to the platform (note: need to only do this when 6898 // updating the platform). 6899 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6900 } 6901 } 6902 if (allowed) { 6903 if (!gp.grantedPermissions.contains(perm)) { 6904 changedPermission = true; 6905 gp.grantedPermissions.add(perm); 6906 gp.gids = appendInts(gp.gids, bp.gids); 6907 } else if (!ps.haveGids) { 6908 gp.gids = appendInts(gp.gids, bp.gids); 6909 } 6910 } else { 6911 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6912 Slog.w(TAG, "Not granting permission " + perm 6913 + " to package " + pkg.packageName 6914 + " because it was previously installed without"); 6915 } 6916 } 6917 } else { 6918 if (gp.grantedPermissions.remove(perm)) { 6919 changedPermission = true; 6920 gp.gids = removeInts(gp.gids, bp.gids); 6921 Slog.i(TAG, "Un-granting permission " + perm 6922 + " from package " + pkg.packageName 6923 + " (protectionLevel=" + bp.protectionLevel 6924 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6925 + ")"); 6926 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6927 // Don't print warning for app op permissions, since it is fine for them 6928 // not to be granted, there is a UI for the user to decide. 6929 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6930 Slog.w(TAG, "Not granting permission " + perm 6931 + " to package " + pkg.packageName 6932 + " (protectionLevel=" + bp.protectionLevel 6933 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6934 + ")"); 6935 } 6936 } 6937 } 6938 } 6939 6940 if ((changedPermission || replace) && !ps.permissionsFixed && 6941 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6942 // This is the first that we have heard about this package, so the 6943 // permissions we have now selected are fixed until explicitly 6944 // changed. 6945 ps.permissionsFixed = true; 6946 } 6947 ps.haveGids = true; 6948 } 6949 6950 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6951 boolean allowed = false; 6952 final int NP = PackageParser.NEW_PERMISSIONS.length; 6953 for (int ip=0; ip<NP; ip++) { 6954 final PackageParser.NewPermissionInfo npi 6955 = PackageParser.NEW_PERMISSIONS[ip]; 6956 if (npi.name.equals(perm) 6957 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6958 allowed = true; 6959 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6960 + pkg.packageName); 6961 break; 6962 } 6963 } 6964 return allowed; 6965 } 6966 6967 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6968 BasePermission bp, HashSet<String> origPermissions) { 6969 boolean allowed; 6970 allowed = (compareSignatures( 6971 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6972 == PackageManager.SIGNATURE_MATCH) 6973 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6974 == PackageManager.SIGNATURE_MATCH); 6975 if (!allowed && (bp.protectionLevel 6976 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6977 if (isSystemApp(pkg)) { 6978 // For updated system applications, a system permission 6979 // is granted only if it had been defined by the original application. 6980 if (isUpdatedSystemApp(pkg)) { 6981 final PackageSetting sysPs = mSettings 6982 .getDisabledSystemPkgLPr(pkg.packageName); 6983 final GrantedPermissions origGp = sysPs.sharedUser != null 6984 ? sysPs.sharedUser : sysPs; 6985 6986 if (origGp.grantedPermissions.contains(perm)) { 6987 // If the original was granted this permission, we take 6988 // that grant decision as read and propagate it to the 6989 // update. 6990 allowed = true; 6991 } else { 6992 // The system apk may have been updated with an older 6993 // version of the one on the data partition, but which 6994 // granted a new system permission that it didn't have 6995 // before. In this case we do want to allow the app to 6996 // now get the new permission if the ancestral apk is 6997 // privileged to get it. 6998 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6999 for (int j=0; 7000 j<sysPs.pkg.requestedPermissions.size(); j++) { 7001 if (perm.equals( 7002 sysPs.pkg.requestedPermissions.get(j))) { 7003 allowed = true; 7004 break; 7005 } 7006 } 7007 } 7008 } 7009 } else { 7010 allowed = isPrivilegedApp(pkg); 7011 } 7012 } 7013 } 7014 if (!allowed && (bp.protectionLevel 7015 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7016 // For development permissions, a development permission 7017 // is granted only if it was already granted. 7018 allowed = origPermissions.contains(perm); 7019 } 7020 return allowed; 7021 } 7022 7023 final class ActivityIntentResolver 7024 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7025 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7026 boolean defaultOnly, int userId) { 7027 if (!sUserManager.exists(userId)) return null; 7028 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7029 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7030 } 7031 7032 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7033 int userId) { 7034 if (!sUserManager.exists(userId)) return null; 7035 mFlags = flags; 7036 return super.queryIntent(intent, resolvedType, 7037 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7038 } 7039 7040 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7041 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7042 if (!sUserManager.exists(userId)) return null; 7043 if (packageActivities == null) { 7044 return null; 7045 } 7046 mFlags = flags; 7047 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7048 final int N = packageActivities.size(); 7049 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7050 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7051 7052 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7053 for (int i = 0; i < N; ++i) { 7054 intentFilters = packageActivities.get(i).intents; 7055 if (intentFilters != null && intentFilters.size() > 0) { 7056 PackageParser.ActivityIntentInfo[] array = 7057 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7058 intentFilters.toArray(array); 7059 listCut.add(array); 7060 } 7061 } 7062 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7063 } 7064 7065 public final void addActivity(PackageParser.Activity a, String type) { 7066 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7067 mActivities.put(a.getComponentName(), a); 7068 if (DEBUG_SHOW_INFO) 7069 Log.v( 7070 TAG, " " + type + " " + 7071 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7072 if (DEBUG_SHOW_INFO) 7073 Log.v(TAG, " Class=" + a.info.name); 7074 final int NI = a.intents.size(); 7075 for (int j=0; j<NI; j++) { 7076 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7077 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7078 intent.setPriority(0); 7079 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7080 + a.className + " with priority > 0, forcing to 0"); 7081 } 7082 if (DEBUG_SHOW_INFO) { 7083 Log.v(TAG, " IntentFilter:"); 7084 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7085 } 7086 if (!intent.debugCheck()) { 7087 Log.w(TAG, "==> For Activity " + a.info.name); 7088 } 7089 addFilter(intent); 7090 } 7091 } 7092 7093 public final void removeActivity(PackageParser.Activity a, String type) { 7094 mActivities.remove(a.getComponentName()); 7095 if (DEBUG_SHOW_INFO) { 7096 Log.v(TAG, " " + type + " " 7097 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7098 : a.info.name) + ":"); 7099 Log.v(TAG, " Class=" + a.info.name); 7100 } 7101 final int NI = a.intents.size(); 7102 for (int j=0; j<NI; j++) { 7103 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7104 if (DEBUG_SHOW_INFO) { 7105 Log.v(TAG, " IntentFilter:"); 7106 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7107 } 7108 removeFilter(intent); 7109 } 7110 } 7111 7112 @Override 7113 protected boolean allowFilterResult( 7114 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7115 ActivityInfo filterAi = filter.activity.info; 7116 for (int i=dest.size()-1; i>=0; i--) { 7117 ActivityInfo destAi = dest.get(i).activityInfo; 7118 if (destAi.name == filterAi.name 7119 && destAi.packageName == filterAi.packageName) { 7120 return false; 7121 } 7122 } 7123 return true; 7124 } 7125 7126 @Override 7127 protected ActivityIntentInfo[] newArray(int size) { 7128 return new ActivityIntentInfo[size]; 7129 } 7130 7131 @Override 7132 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7133 if (!sUserManager.exists(userId)) return true; 7134 PackageParser.Package p = filter.activity.owner; 7135 if (p != null) { 7136 PackageSetting ps = (PackageSetting)p.mExtras; 7137 if (ps != null) { 7138 // System apps are never considered stopped for purposes of 7139 // filtering, because there may be no way for the user to 7140 // actually re-launch them. 7141 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7142 && ps.getStopped(userId); 7143 } 7144 } 7145 return false; 7146 } 7147 7148 @Override 7149 protected boolean isPackageForFilter(String packageName, 7150 PackageParser.ActivityIntentInfo info) { 7151 return packageName.equals(info.activity.owner.packageName); 7152 } 7153 7154 @Override 7155 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7156 int match, int userId) { 7157 if (!sUserManager.exists(userId)) return null; 7158 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7159 return null; 7160 } 7161 final PackageParser.Activity activity = info.activity; 7162 if (mSafeMode && (activity.info.applicationInfo.flags 7163 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7164 return null; 7165 } 7166 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7167 if (ps == null) { 7168 return null; 7169 } 7170 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7171 ps.readUserState(userId), userId); 7172 if (ai == null) { 7173 return null; 7174 } 7175 final ResolveInfo res = new ResolveInfo(); 7176 res.activityInfo = ai; 7177 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7178 res.filter = info; 7179 } 7180 res.priority = info.getPriority(); 7181 res.preferredOrder = activity.owner.mPreferredOrder; 7182 //System.out.println("Result: " + res.activityInfo.className + 7183 // " = " + res.priority); 7184 res.match = match; 7185 res.isDefault = info.hasDefault; 7186 res.labelRes = info.labelRes; 7187 res.nonLocalizedLabel = info.nonLocalizedLabel; 7188 if (userNeedsBadging(userId)) { 7189 res.noResourceId = true; 7190 } else { 7191 res.icon = info.icon; 7192 } 7193 res.system = isSystemApp(res.activityInfo.applicationInfo); 7194 return res; 7195 } 7196 7197 @Override 7198 protected void sortResults(List<ResolveInfo> results) { 7199 Collections.sort(results, mResolvePrioritySorter); 7200 } 7201 7202 @Override 7203 protected void dumpFilter(PrintWriter out, String prefix, 7204 PackageParser.ActivityIntentInfo filter) { 7205 out.print(prefix); out.print( 7206 Integer.toHexString(System.identityHashCode(filter.activity))); 7207 out.print(' '); 7208 filter.activity.printComponentShortName(out); 7209 out.print(" filter "); 7210 out.println(Integer.toHexString(System.identityHashCode(filter))); 7211 } 7212 7213// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7214// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7215// final List<ResolveInfo> retList = Lists.newArrayList(); 7216// while (i.hasNext()) { 7217// final ResolveInfo resolveInfo = i.next(); 7218// if (isEnabledLP(resolveInfo.activityInfo)) { 7219// retList.add(resolveInfo); 7220// } 7221// } 7222// return retList; 7223// } 7224 7225 // Keys are String (activity class name), values are Activity. 7226 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7227 = new HashMap<ComponentName, PackageParser.Activity>(); 7228 private int mFlags; 7229 } 7230 7231 private final class ServiceIntentResolver 7232 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7233 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7234 boolean defaultOnly, int userId) { 7235 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7236 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7237 } 7238 7239 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7240 int userId) { 7241 if (!sUserManager.exists(userId)) return null; 7242 mFlags = flags; 7243 return super.queryIntent(intent, resolvedType, 7244 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7245 } 7246 7247 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7248 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7249 if (!sUserManager.exists(userId)) return null; 7250 if (packageServices == null) { 7251 return null; 7252 } 7253 mFlags = flags; 7254 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7255 final int N = packageServices.size(); 7256 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7257 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7258 7259 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7260 for (int i = 0; i < N; ++i) { 7261 intentFilters = packageServices.get(i).intents; 7262 if (intentFilters != null && intentFilters.size() > 0) { 7263 PackageParser.ServiceIntentInfo[] array = 7264 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7265 intentFilters.toArray(array); 7266 listCut.add(array); 7267 } 7268 } 7269 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7270 } 7271 7272 public final void addService(PackageParser.Service s) { 7273 mServices.put(s.getComponentName(), s); 7274 if (DEBUG_SHOW_INFO) { 7275 Log.v(TAG, " " 7276 + (s.info.nonLocalizedLabel != null 7277 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7278 Log.v(TAG, " Class=" + s.info.name); 7279 } 7280 final int NI = s.intents.size(); 7281 int j; 7282 for (j=0; j<NI; j++) { 7283 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7284 if (DEBUG_SHOW_INFO) { 7285 Log.v(TAG, " IntentFilter:"); 7286 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7287 } 7288 if (!intent.debugCheck()) { 7289 Log.w(TAG, "==> For Service " + s.info.name); 7290 } 7291 addFilter(intent); 7292 } 7293 } 7294 7295 public final void removeService(PackageParser.Service s) { 7296 mServices.remove(s.getComponentName()); 7297 if (DEBUG_SHOW_INFO) { 7298 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7299 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7300 Log.v(TAG, " Class=" + s.info.name); 7301 } 7302 final int NI = s.intents.size(); 7303 int j; 7304 for (j=0; j<NI; j++) { 7305 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7306 if (DEBUG_SHOW_INFO) { 7307 Log.v(TAG, " IntentFilter:"); 7308 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7309 } 7310 removeFilter(intent); 7311 } 7312 } 7313 7314 @Override 7315 protected boolean allowFilterResult( 7316 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7317 ServiceInfo filterSi = filter.service.info; 7318 for (int i=dest.size()-1; i>=0; i--) { 7319 ServiceInfo destAi = dest.get(i).serviceInfo; 7320 if (destAi.name == filterSi.name 7321 && destAi.packageName == filterSi.packageName) { 7322 return false; 7323 } 7324 } 7325 return true; 7326 } 7327 7328 @Override 7329 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7330 return new PackageParser.ServiceIntentInfo[size]; 7331 } 7332 7333 @Override 7334 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7335 if (!sUserManager.exists(userId)) return true; 7336 PackageParser.Package p = filter.service.owner; 7337 if (p != null) { 7338 PackageSetting ps = (PackageSetting)p.mExtras; 7339 if (ps != null) { 7340 // System apps are never considered stopped for purposes of 7341 // filtering, because there may be no way for the user to 7342 // actually re-launch them. 7343 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7344 && ps.getStopped(userId); 7345 } 7346 } 7347 return false; 7348 } 7349 7350 @Override 7351 protected boolean isPackageForFilter(String packageName, 7352 PackageParser.ServiceIntentInfo info) { 7353 return packageName.equals(info.service.owner.packageName); 7354 } 7355 7356 @Override 7357 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7358 int match, int userId) { 7359 if (!sUserManager.exists(userId)) return null; 7360 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7361 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7362 return null; 7363 } 7364 final PackageParser.Service service = info.service; 7365 if (mSafeMode && (service.info.applicationInfo.flags 7366 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7367 return null; 7368 } 7369 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7370 if (ps == null) { 7371 return null; 7372 } 7373 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7374 ps.readUserState(userId), userId); 7375 if (si == null) { 7376 return null; 7377 } 7378 final ResolveInfo res = new ResolveInfo(); 7379 res.serviceInfo = si; 7380 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7381 res.filter = filter; 7382 } 7383 res.priority = info.getPriority(); 7384 res.preferredOrder = service.owner.mPreferredOrder; 7385 //System.out.println("Result: " + res.activityInfo.className + 7386 // " = " + res.priority); 7387 res.match = match; 7388 res.isDefault = info.hasDefault; 7389 res.labelRes = info.labelRes; 7390 res.nonLocalizedLabel = info.nonLocalizedLabel; 7391 res.icon = info.icon; 7392 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7393 return res; 7394 } 7395 7396 @Override 7397 protected void sortResults(List<ResolveInfo> results) { 7398 Collections.sort(results, mResolvePrioritySorter); 7399 } 7400 7401 @Override 7402 protected void dumpFilter(PrintWriter out, String prefix, 7403 PackageParser.ServiceIntentInfo filter) { 7404 out.print(prefix); out.print( 7405 Integer.toHexString(System.identityHashCode(filter.service))); 7406 out.print(' '); 7407 filter.service.printComponentShortName(out); 7408 out.print(" filter "); 7409 out.println(Integer.toHexString(System.identityHashCode(filter))); 7410 } 7411 7412// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7413// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7414// final List<ResolveInfo> retList = Lists.newArrayList(); 7415// while (i.hasNext()) { 7416// final ResolveInfo resolveInfo = (ResolveInfo) i; 7417// if (isEnabledLP(resolveInfo.serviceInfo)) { 7418// retList.add(resolveInfo); 7419// } 7420// } 7421// return retList; 7422// } 7423 7424 // Keys are String (activity class name), values are Activity. 7425 private final HashMap<ComponentName, PackageParser.Service> mServices 7426 = new HashMap<ComponentName, PackageParser.Service>(); 7427 private int mFlags; 7428 }; 7429 7430 private final class ProviderIntentResolver 7431 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7432 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7433 boolean defaultOnly, int userId) { 7434 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7435 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7436 } 7437 7438 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7439 int userId) { 7440 if (!sUserManager.exists(userId)) 7441 return null; 7442 mFlags = flags; 7443 return super.queryIntent(intent, resolvedType, 7444 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7445 } 7446 7447 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7448 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7449 if (!sUserManager.exists(userId)) 7450 return null; 7451 if (packageProviders == null) { 7452 return null; 7453 } 7454 mFlags = flags; 7455 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7456 final int N = packageProviders.size(); 7457 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7458 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7459 7460 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7461 for (int i = 0; i < N; ++i) { 7462 intentFilters = packageProviders.get(i).intents; 7463 if (intentFilters != null && intentFilters.size() > 0) { 7464 PackageParser.ProviderIntentInfo[] array = 7465 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7466 intentFilters.toArray(array); 7467 listCut.add(array); 7468 } 7469 } 7470 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7471 } 7472 7473 public final void addProvider(PackageParser.Provider p) { 7474 if (mProviders.containsKey(p.getComponentName())) { 7475 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7476 return; 7477 } 7478 7479 mProviders.put(p.getComponentName(), p); 7480 if (DEBUG_SHOW_INFO) { 7481 Log.v(TAG, " " 7482 + (p.info.nonLocalizedLabel != null 7483 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7484 Log.v(TAG, " Class=" + p.info.name); 7485 } 7486 final int NI = p.intents.size(); 7487 int j; 7488 for (j = 0; j < NI; j++) { 7489 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7490 if (DEBUG_SHOW_INFO) { 7491 Log.v(TAG, " IntentFilter:"); 7492 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7493 } 7494 if (!intent.debugCheck()) { 7495 Log.w(TAG, "==> For Provider " + p.info.name); 7496 } 7497 addFilter(intent); 7498 } 7499 } 7500 7501 public final void removeProvider(PackageParser.Provider p) { 7502 mProviders.remove(p.getComponentName()); 7503 if (DEBUG_SHOW_INFO) { 7504 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7505 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7506 Log.v(TAG, " Class=" + p.info.name); 7507 } 7508 final int NI = p.intents.size(); 7509 int j; 7510 for (j = 0; j < NI; j++) { 7511 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7512 if (DEBUG_SHOW_INFO) { 7513 Log.v(TAG, " IntentFilter:"); 7514 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7515 } 7516 removeFilter(intent); 7517 } 7518 } 7519 7520 @Override 7521 protected boolean allowFilterResult( 7522 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7523 ProviderInfo filterPi = filter.provider.info; 7524 for (int i = dest.size() - 1; i >= 0; i--) { 7525 ProviderInfo destPi = dest.get(i).providerInfo; 7526 if (destPi.name == filterPi.name 7527 && destPi.packageName == filterPi.packageName) { 7528 return false; 7529 } 7530 } 7531 return true; 7532 } 7533 7534 @Override 7535 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7536 return new PackageParser.ProviderIntentInfo[size]; 7537 } 7538 7539 @Override 7540 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7541 if (!sUserManager.exists(userId)) 7542 return true; 7543 PackageParser.Package p = filter.provider.owner; 7544 if (p != null) { 7545 PackageSetting ps = (PackageSetting) p.mExtras; 7546 if (ps != null) { 7547 // System apps are never considered stopped for purposes of 7548 // filtering, because there may be no way for the user to 7549 // actually re-launch them. 7550 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7551 && ps.getStopped(userId); 7552 } 7553 } 7554 return false; 7555 } 7556 7557 @Override 7558 protected boolean isPackageForFilter(String packageName, 7559 PackageParser.ProviderIntentInfo info) { 7560 return packageName.equals(info.provider.owner.packageName); 7561 } 7562 7563 @Override 7564 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7565 int match, int userId) { 7566 if (!sUserManager.exists(userId)) 7567 return null; 7568 final PackageParser.ProviderIntentInfo info = filter; 7569 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7570 return null; 7571 } 7572 final PackageParser.Provider provider = info.provider; 7573 if (mSafeMode && (provider.info.applicationInfo.flags 7574 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7575 return null; 7576 } 7577 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7578 if (ps == null) { 7579 return null; 7580 } 7581 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7582 ps.readUserState(userId), userId); 7583 if (pi == null) { 7584 return null; 7585 } 7586 final ResolveInfo res = new ResolveInfo(); 7587 res.providerInfo = pi; 7588 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7589 res.filter = filter; 7590 } 7591 res.priority = info.getPriority(); 7592 res.preferredOrder = provider.owner.mPreferredOrder; 7593 res.match = match; 7594 res.isDefault = info.hasDefault; 7595 res.labelRes = info.labelRes; 7596 res.nonLocalizedLabel = info.nonLocalizedLabel; 7597 res.icon = info.icon; 7598 res.system = isSystemApp(res.providerInfo.applicationInfo); 7599 return res; 7600 } 7601 7602 @Override 7603 protected void sortResults(List<ResolveInfo> results) { 7604 Collections.sort(results, mResolvePrioritySorter); 7605 } 7606 7607 @Override 7608 protected void dumpFilter(PrintWriter out, String prefix, 7609 PackageParser.ProviderIntentInfo filter) { 7610 out.print(prefix); 7611 out.print( 7612 Integer.toHexString(System.identityHashCode(filter.provider))); 7613 out.print(' '); 7614 filter.provider.printComponentShortName(out); 7615 out.print(" filter "); 7616 out.println(Integer.toHexString(System.identityHashCode(filter))); 7617 } 7618 7619 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7620 = new HashMap<ComponentName, PackageParser.Provider>(); 7621 private int mFlags; 7622 }; 7623 7624 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7625 new Comparator<ResolveInfo>() { 7626 public int compare(ResolveInfo r1, ResolveInfo r2) { 7627 int v1 = r1.priority; 7628 int v2 = r2.priority; 7629 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7630 if (v1 != v2) { 7631 return (v1 > v2) ? -1 : 1; 7632 } 7633 v1 = r1.preferredOrder; 7634 v2 = r2.preferredOrder; 7635 if (v1 != v2) { 7636 return (v1 > v2) ? -1 : 1; 7637 } 7638 if (r1.isDefault != r2.isDefault) { 7639 return r1.isDefault ? -1 : 1; 7640 } 7641 v1 = r1.match; 7642 v2 = r2.match; 7643 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7644 if (v1 != v2) { 7645 return (v1 > v2) ? -1 : 1; 7646 } 7647 if (r1.system != r2.system) { 7648 return r1.system ? -1 : 1; 7649 } 7650 return 0; 7651 } 7652 }; 7653 7654 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7655 new Comparator<ProviderInfo>() { 7656 public int compare(ProviderInfo p1, ProviderInfo p2) { 7657 final int v1 = p1.initOrder; 7658 final int v2 = p2.initOrder; 7659 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7660 } 7661 }; 7662 7663 static final void sendPackageBroadcast(String action, String pkg, 7664 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7665 int[] userIds) { 7666 IActivityManager am = ActivityManagerNative.getDefault(); 7667 if (am != null) { 7668 try { 7669 if (userIds == null) { 7670 userIds = am.getRunningUserIds(); 7671 } 7672 for (int id : userIds) { 7673 final Intent intent = new Intent(action, 7674 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7675 if (extras != null) { 7676 intent.putExtras(extras); 7677 } 7678 if (targetPkg != null) { 7679 intent.setPackage(targetPkg); 7680 } 7681 // Modify the UID when posting to other users 7682 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7683 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7684 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7685 intent.putExtra(Intent.EXTRA_UID, uid); 7686 } 7687 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7688 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7689 if (DEBUG_BROADCASTS) { 7690 RuntimeException here = new RuntimeException("here"); 7691 here.fillInStackTrace(); 7692 Slog.d(TAG, "Sending to user " + id + ": " 7693 + intent.toShortString(false, true, false, false) 7694 + " " + intent.getExtras(), here); 7695 } 7696 am.broadcastIntent(null, intent, null, finishedReceiver, 7697 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7698 finishedReceiver != null, false, id); 7699 } 7700 } catch (RemoteException ex) { 7701 } 7702 } 7703 } 7704 7705 /** 7706 * Check if the external storage media is available. This is true if there 7707 * is a mounted external storage medium or if the external storage is 7708 * emulated. 7709 */ 7710 private boolean isExternalMediaAvailable() { 7711 return mMediaMounted || Environment.isExternalStorageEmulated(); 7712 } 7713 7714 @Override 7715 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7716 // writer 7717 synchronized (mPackages) { 7718 if (!isExternalMediaAvailable()) { 7719 // If the external storage is no longer mounted at this point, 7720 // the caller may not have been able to delete all of this 7721 // packages files and can not delete any more. Bail. 7722 return null; 7723 } 7724 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7725 if (lastPackage != null) { 7726 pkgs.remove(lastPackage); 7727 } 7728 if (pkgs.size() > 0) { 7729 return pkgs.get(0); 7730 } 7731 } 7732 return null; 7733 } 7734 7735 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7736 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 7737 userId, andCode ? 1 : 0, packageName); 7738 if (mSystemReady) { 7739 msg.sendToTarget(); 7740 } else { 7741 if (mPostSystemReadyMessages == null) { 7742 mPostSystemReadyMessages = new ArrayList<>(); 7743 } 7744 mPostSystemReadyMessages.add(msg); 7745 } 7746 } 7747 7748 void startCleaningPackages() { 7749 // reader 7750 synchronized (mPackages) { 7751 if (!isExternalMediaAvailable()) { 7752 return; 7753 } 7754 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7755 return; 7756 } 7757 } 7758 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7759 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7760 IActivityManager am = ActivityManagerNative.getDefault(); 7761 if (am != null) { 7762 try { 7763 am.startService(null, intent, null, UserHandle.USER_OWNER); 7764 } catch (RemoteException e) { 7765 } 7766 } 7767 } 7768 7769 @Override 7770 public void installPackage(String originPath, IPackageInstallObserver2 observer, 7771 int installFlags, String installerPackageName, VerificationParams verificationParams, 7772 String packageAbiOverride) { 7773 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 7774 packageAbiOverride, UserHandle.getCallingUserId()); 7775 } 7776 7777 @Override 7778 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 7779 int installFlags, String installerPackageName, VerificationParams verificationParams, 7780 String packageAbiOverride, int userId) { 7781 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 7782 7783 final int callingUid = Binder.getCallingUid(); 7784 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 7785 7786 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7787 try { 7788 if (observer != null) { 7789 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7790 } 7791 } catch (RemoteException re) { 7792 } 7793 return; 7794 } 7795 7796 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 7797 installFlags |= PackageManager.INSTALL_FROM_ADB; 7798 7799 } else { 7800 // Caller holds INSTALL_PACKAGES permission, so we're less strict 7801 // about installerPackageName. 7802 7803 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 7804 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 7805 } 7806 7807 UserHandle user; 7808 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 7809 user = UserHandle.ALL; 7810 } else { 7811 user = new UserHandle(userId); 7812 } 7813 7814 verificationParams.setInstallerUid(callingUid); 7815 7816 final File originFile = new File(originPath); 7817 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 7818 7819 final Message msg = mHandler.obtainMessage(INIT_COPY); 7820 msg.obj = new InstallParams(origin, observer, installFlags, 7821 installerPackageName, verificationParams, user, packageAbiOverride); 7822 mHandler.sendMessage(msg); 7823 } 7824 7825 void installStage(String packageName, File stagedDir, String stagedCid, 7826 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 7827 String installerPackageName, int installerUid, UserHandle user) { 7828 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7829 params.referrerUri, installerUid, null); 7830 7831 final OriginInfo origin; 7832 if (stagedDir != null) { 7833 origin = OriginInfo.fromStagedFile(stagedDir); 7834 } else { 7835 origin = OriginInfo.fromStagedContainer(stagedCid); 7836 } 7837 7838 final Message msg = mHandler.obtainMessage(INIT_COPY); 7839 msg.obj = new InstallParams(origin, observer, params.installFlags, 7840 installerPackageName, verifParams, user, params.abiOverride); 7841 mHandler.sendMessage(msg); 7842 } 7843 7844 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7845 Bundle extras = new Bundle(1); 7846 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7847 7848 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7849 packageName, extras, null, null, new int[] {userId}); 7850 try { 7851 IActivityManager am = ActivityManagerNative.getDefault(); 7852 final boolean isSystem = 7853 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7854 if (isSystem && am.isUserRunning(userId, false)) { 7855 // The just-installed/enabled app is bundled on the system, so presumed 7856 // to be able to run automatically without needing an explicit launch. 7857 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7858 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7859 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7860 .setPackage(packageName); 7861 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7862 android.app.AppOpsManager.OP_NONE, false, false, userId); 7863 } 7864 } catch (RemoteException e) { 7865 // shouldn't happen 7866 Slog.w(TAG, "Unable to bootstrap installed package", e); 7867 } 7868 } 7869 7870 @Override 7871 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7872 int userId) { 7873 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7874 PackageSetting pkgSetting; 7875 final int uid = Binder.getCallingUid(); 7876 enforceCrossUserPermission(uid, userId, true, true, 7877 "setApplicationHiddenSetting for user " + userId); 7878 7879 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7880 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7881 return false; 7882 } 7883 7884 long callingId = Binder.clearCallingIdentity(); 7885 try { 7886 boolean sendAdded = false; 7887 boolean sendRemoved = false; 7888 // writer 7889 synchronized (mPackages) { 7890 pkgSetting = mSettings.mPackages.get(packageName); 7891 if (pkgSetting == null) { 7892 return false; 7893 } 7894 if (pkgSetting.getHidden(userId) != hidden) { 7895 pkgSetting.setHidden(hidden, userId); 7896 mSettings.writePackageRestrictionsLPr(userId); 7897 if (hidden) { 7898 sendRemoved = true; 7899 } else { 7900 sendAdded = true; 7901 } 7902 } 7903 } 7904 if (sendAdded) { 7905 sendPackageAddedForUser(packageName, pkgSetting, userId); 7906 return true; 7907 } 7908 if (sendRemoved) { 7909 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7910 "hiding pkg"); 7911 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7912 } 7913 } finally { 7914 Binder.restoreCallingIdentity(callingId); 7915 } 7916 return false; 7917 } 7918 7919 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7920 int userId) { 7921 final PackageRemovedInfo info = new PackageRemovedInfo(); 7922 info.removedPackage = packageName; 7923 info.removedUsers = new int[] {userId}; 7924 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7925 info.sendBroadcast(false, false, false); 7926 } 7927 7928 /** 7929 * Returns true if application is not found or there was an error. Otherwise it returns 7930 * the hidden state of the package for the given user. 7931 */ 7932 @Override 7933 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 7934 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7935 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7936 false, "getApplicationHidden for user " + userId); 7937 PackageSetting pkgSetting; 7938 long callingId = Binder.clearCallingIdentity(); 7939 try { 7940 // writer 7941 synchronized (mPackages) { 7942 pkgSetting = mSettings.mPackages.get(packageName); 7943 if (pkgSetting == null) { 7944 return true; 7945 } 7946 return pkgSetting.getHidden(userId); 7947 } 7948 } finally { 7949 Binder.restoreCallingIdentity(callingId); 7950 } 7951 } 7952 7953 /** 7954 * @hide 7955 */ 7956 @Override 7957 public int installExistingPackageAsUser(String packageName, int userId) { 7958 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7959 null); 7960 PackageSetting pkgSetting; 7961 final int uid = Binder.getCallingUid(); 7962 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 7963 + userId); 7964 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7965 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7966 } 7967 7968 long callingId = Binder.clearCallingIdentity(); 7969 try { 7970 boolean sendAdded = false; 7971 Bundle extras = new Bundle(1); 7972 7973 // writer 7974 synchronized (mPackages) { 7975 pkgSetting = mSettings.mPackages.get(packageName); 7976 if (pkgSetting == null) { 7977 return PackageManager.INSTALL_FAILED_INVALID_URI; 7978 } 7979 if (!pkgSetting.getInstalled(userId)) { 7980 pkgSetting.setInstalled(true, userId); 7981 pkgSetting.setHidden(false, userId); 7982 mSettings.writePackageRestrictionsLPr(userId); 7983 sendAdded = true; 7984 } 7985 } 7986 7987 if (sendAdded) { 7988 sendPackageAddedForUser(packageName, pkgSetting, userId); 7989 } 7990 } finally { 7991 Binder.restoreCallingIdentity(callingId); 7992 } 7993 7994 return PackageManager.INSTALL_SUCCEEDED; 7995 } 7996 7997 boolean isUserRestricted(int userId, String restrictionKey) { 7998 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7999 if (restrictions.getBoolean(restrictionKey, false)) { 8000 Log.w(TAG, "User is restricted: " + restrictionKey); 8001 return true; 8002 } 8003 return false; 8004 } 8005 8006 @Override 8007 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8008 mContext.enforceCallingOrSelfPermission( 8009 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8010 "Only package verification agents can verify applications"); 8011 8012 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8013 final PackageVerificationResponse response = new PackageVerificationResponse( 8014 verificationCode, Binder.getCallingUid()); 8015 msg.arg1 = id; 8016 msg.obj = response; 8017 mHandler.sendMessage(msg); 8018 } 8019 8020 @Override 8021 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8022 long millisecondsToDelay) { 8023 mContext.enforceCallingOrSelfPermission( 8024 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8025 "Only package verification agents can extend verification timeouts"); 8026 8027 final PackageVerificationState state = mPendingVerification.get(id); 8028 final PackageVerificationResponse response = new PackageVerificationResponse( 8029 verificationCodeAtTimeout, Binder.getCallingUid()); 8030 8031 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8032 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8033 } 8034 if (millisecondsToDelay < 0) { 8035 millisecondsToDelay = 0; 8036 } 8037 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8038 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8039 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8040 } 8041 8042 if ((state != null) && !state.timeoutExtended()) { 8043 state.extendTimeout(); 8044 8045 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8046 msg.arg1 = id; 8047 msg.obj = response; 8048 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8049 } 8050 } 8051 8052 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8053 int verificationCode, UserHandle user) { 8054 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8055 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8056 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8057 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8058 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8059 8060 mContext.sendBroadcastAsUser(intent, user, 8061 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8062 } 8063 8064 private ComponentName matchComponentForVerifier(String packageName, 8065 List<ResolveInfo> receivers) { 8066 ActivityInfo targetReceiver = null; 8067 8068 final int NR = receivers.size(); 8069 for (int i = 0; i < NR; i++) { 8070 final ResolveInfo info = receivers.get(i); 8071 if (info.activityInfo == null) { 8072 continue; 8073 } 8074 8075 if (packageName.equals(info.activityInfo.packageName)) { 8076 targetReceiver = info.activityInfo; 8077 break; 8078 } 8079 } 8080 8081 if (targetReceiver == null) { 8082 return null; 8083 } 8084 8085 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8086 } 8087 8088 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8089 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8090 if (pkgInfo.verifiers.length == 0) { 8091 return null; 8092 } 8093 8094 final int N = pkgInfo.verifiers.length; 8095 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8096 for (int i = 0; i < N; i++) { 8097 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8098 8099 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8100 receivers); 8101 if (comp == null) { 8102 continue; 8103 } 8104 8105 final int verifierUid = getUidForVerifier(verifierInfo); 8106 if (verifierUid == -1) { 8107 continue; 8108 } 8109 8110 if (DEBUG_VERIFY) { 8111 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8112 + " with the correct signature"); 8113 } 8114 sufficientVerifiers.add(comp); 8115 verificationState.addSufficientVerifier(verifierUid); 8116 } 8117 8118 return sufficientVerifiers; 8119 } 8120 8121 private int getUidForVerifier(VerifierInfo verifierInfo) { 8122 synchronized (mPackages) { 8123 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8124 if (pkg == null) { 8125 return -1; 8126 } else if (pkg.mSignatures.length != 1) { 8127 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8128 + " has more than one signature; ignoring"); 8129 return -1; 8130 } 8131 8132 /* 8133 * If the public key of the package's signature does not match 8134 * our expected public key, then this is a different package and 8135 * we should skip. 8136 */ 8137 8138 final byte[] expectedPublicKey; 8139 try { 8140 final Signature verifierSig = pkg.mSignatures[0]; 8141 final PublicKey publicKey = verifierSig.getPublicKey(); 8142 expectedPublicKey = publicKey.getEncoded(); 8143 } catch (CertificateException e) { 8144 return -1; 8145 } 8146 8147 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8148 8149 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8150 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8151 + " does not have the expected public key; ignoring"); 8152 return -1; 8153 } 8154 8155 return pkg.applicationInfo.uid; 8156 } 8157 } 8158 8159 @Override 8160 public void finishPackageInstall(int token) { 8161 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8162 8163 if (DEBUG_INSTALL) { 8164 Slog.v(TAG, "BM finishing package install for " + token); 8165 } 8166 8167 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8168 mHandler.sendMessage(msg); 8169 } 8170 8171 /** 8172 * Get the verification agent timeout. 8173 * 8174 * @return verification timeout in milliseconds 8175 */ 8176 private long getVerificationTimeout() { 8177 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8178 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8179 DEFAULT_VERIFICATION_TIMEOUT); 8180 } 8181 8182 /** 8183 * Get the default verification agent response code. 8184 * 8185 * @return default verification response code 8186 */ 8187 private int getDefaultVerificationResponse() { 8188 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8189 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8190 DEFAULT_VERIFICATION_RESPONSE); 8191 } 8192 8193 /** 8194 * Check whether or not package verification has been enabled. 8195 * 8196 * @return true if verification should be performed 8197 */ 8198 private boolean isVerificationEnabled(int userId, int installFlags) { 8199 if (!DEFAULT_VERIFY_ENABLE) { 8200 return false; 8201 } 8202 8203 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8204 8205 // Check if installing from ADB 8206 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8207 // Do not run verification in a test harness environment 8208 if (ActivityManager.isRunningInTestHarness()) { 8209 return false; 8210 } 8211 if (ensureVerifyAppsEnabled) { 8212 return true; 8213 } 8214 // Check if the developer does not want package verification for ADB installs 8215 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8216 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8217 return false; 8218 } 8219 } 8220 8221 if (ensureVerifyAppsEnabled) { 8222 return true; 8223 } 8224 8225 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8226 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8227 } 8228 8229 /** 8230 * Get the "allow unknown sources" setting. 8231 * 8232 * @return the current "allow unknown sources" setting 8233 */ 8234 private int getUnknownSourcesSettings() { 8235 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8236 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8237 -1); 8238 } 8239 8240 @Override 8241 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8242 final int uid = Binder.getCallingUid(); 8243 // writer 8244 synchronized (mPackages) { 8245 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8246 if (targetPackageSetting == null) { 8247 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8248 } 8249 8250 PackageSetting installerPackageSetting; 8251 if (installerPackageName != null) { 8252 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8253 if (installerPackageSetting == null) { 8254 throw new IllegalArgumentException("Unknown installer package: " 8255 + installerPackageName); 8256 } 8257 } else { 8258 installerPackageSetting = null; 8259 } 8260 8261 Signature[] callerSignature; 8262 Object obj = mSettings.getUserIdLPr(uid); 8263 if (obj != null) { 8264 if (obj instanceof SharedUserSetting) { 8265 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8266 } else if (obj instanceof PackageSetting) { 8267 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8268 } else { 8269 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8270 } 8271 } else { 8272 throw new SecurityException("Unknown calling uid " + uid); 8273 } 8274 8275 // Verify: can't set installerPackageName to a package that is 8276 // not signed with the same cert as the caller. 8277 if (installerPackageSetting != null) { 8278 if (compareSignatures(callerSignature, 8279 installerPackageSetting.signatures.mSignatures) 8280 != PackageManager.SIGNATURE_MATCH) { 8281 throw new SecurityException( 8282 "Caller does not have same cert as new installer package " 8283 + installerPackageName); 8284 } 8285 } 8286 8287 // Verify: if target already has an installer package, it must 8288 // be signed with the same cert as the caller. 8289 if (targetPackageSetting.installerPackageName != null) { 8290 PackageSetting setting = mSettings.mPackages.get( 8291 targetPackageSetting.installerPackageName); 8292 // If the currently set package isn't valid, then it's always 8293 // okay to change it. 8294 if (setting != null) { 8295 if (compareSignatures(callerSignature, 8296 setting.signatures.mSignatures) 8297 != PackageManager.SIGNATURE_MATCH) { 8298 throw new SecurityException( 8299 "Caller does not have same cert as old installer package " 8300 + targetPackageSetting.installerPackageName); 8301 } 8302 } 8303 } 8304 8305 // Okay! 8306 targetPackageSetting.installerPackageName = installerPackageName; 8307 scheduleWriteSettingsLocked(); 8308 } 8309 } 8310 8311 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8312 // Queue up an async operation since the package installation may take a little while. 8313 mHandler.post(new Runnable() { 8314 public void run() { 8315 mHandler.removeCallbacks(this); 8316 // Result object to be returned 8317 PackageInstalledInfo res = new PackageInstalledInfo(); 8318 res.returnCode = currentStatus; 8319 res.uid = -1; 8320 res.pkg = null; 8321 res.removedInfo = new PackageRemovedInfo(); 8322 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8323 args.doPreInstall(res.returnCode); 8324 synchronized (mInstallLock) { 8325 installPackageLI(args, res); 8326 } 8327 args.doPostInstall(res.returnCode, res.uid); 8328 } 8329 8330 // A restore should be performed at this point if (a) the install 8331 // succeeded, (b) the operation is not an update, and (c) the new 8332 // package has not opted out of backup participation. 8333 final boolean update = res.removedInfo.removedPackage != null; 8334 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8335 boolean doRestore = !update 8336 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8337 8338 // Set up the post-install work request bookkeeping. This will be used 8339 // and cleaned up by the post-install event handling regardless of whether 8340 // there's a restore pass performed. Token values are >= 1. 8341 int token; 8342 if (mNextInstallToken < 0) mNextInstallToken = 1; 8343 token = mNextInstallToken++; 8344 8345 PostInstallData data = new PostInstallData(args, res); 8346 mRunningInstalls.put(token, data); 8347 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8348 8349 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8350 // Pass responsibility to the Backup Manager. It will perform a 8351 // restore if appropriate, then pass responsibility back to the 8352 // Package Manager to run the post-install observer callbacks 8353 // and broadcasts. 8354 IBackupManager bm = IBackupManager.Stub.asInterface( 8355 ServiceManager.getService(Context.BACKUP_SERVICE)); 8356 if (bm != null) { 8357 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8358 + " to BM for possible restore"); 8359 try { 8360 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8361 } catch (RemoteException e) { 8362 // can't happen; the backup manager is local 8363 } catch (Exception e) { 8364 Slog.e(TAG, "Exception trying to enqueue restore", e); 8365 doRestore = false; 8366 } 8367 } else { 8368 Slog.e(TAG, "Backup Manager not found!"); 8369 doRestore = false; 8370 } 8371 } 8372 8373 if (!doRestore) { 8374 // No restore possible, or the Backup Manager was mysteriously not 8375 // available -- just fire the post-install work request directly. 8376 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8377 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8378 mHandler.sendMessage(msg); 8379 } 8380 } 8381 }); 8382 } 8383 8384 private abstract class HandlerParams { 8385 private static final int MAX_RETRIES = 4; 8386 8387 /** 8388 * Number of times startCopy() has been attempted and had a non-fatal 8389 * error. 8390 */ 8391 private int mRetries = 0; 8392 8393 /** User handle for the user requesting the information or installation. */ 8394 private final UserHandle mUser; 8395 8396 HandlerParams(UserHandle user) { 8397 mUser = user; 8398 } 8399 8400 UserHandle getUser() { 8401 return mUser; 8402 } 8403 8404 final boolean startCopy() { 8405 boolean res; 8406 try { 8407 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8408 8409 if (++mRetries > MAX_RETRIES) { 8410 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8411 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8412 handleServiceError(); 8413 return false; 8414 } else { 8415 handleStartCopy(); 8416 res = true; 8417 } 8418 } catch (RemoteException e) { 8419 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8420 mHandler.sendEmptyMessage(MCS_RECONNECT); 8421 res = false; 8422 } 8423 handleReturnCode(); 8424 return res; 8425 } 8426 8427 final void serviceError() { 8428 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8429 handleServiceError(); 8430 handleReturnCode(); 8431 } 8432 8433 abstract void handleStartCopy() throws RemoteException; 8434 abstract void handleServiceError(); 8435 abstract void handleReturnCode(); 8436 } 8437 8438 class MeasureParams extends HandlerParams { 8439 private final PackageStats mStats; 8440 private boolean mSuccess; 8441 8442 private final IPackageStatsObserver mObserver; 8443 8444 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8445 super(new UserHandle(stats.userHandle)); 8446 mObserver = observer; 8447 mStats = stats; 8448 } 8449 8450 @Override 8451 public String toString() { 8452 return "MeasureParams{" 8453 + Integer.toHexString(System.identityHashCode(this)) 8454 + " " + mStats.packageName + "}"; 8455 } 8456 8457 @Override 8458 void handleStartCopy() throws RemoteException { 8459 synchronized (mInstallLock) { 8460 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8461 } 8462 8463 if (mSuccess) { 8464 final boolean mounted; 8465 if (Environment.isExternalStorageEmulated()) { 8466 mounted = true; 8467 } else { 8468 final String status = Environment.getExternalStorageState(); 8469 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8470 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8471 } 8472 8473 if (mounted) { 8474 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8475 8476 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8477 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8478 8479 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8480 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8481 8482 // Always subtract cache size, since it's a subdirectory 8483 mStats.externalDataSize -= mStats.externalCacheSize; 8484 8485 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8486 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8487 8488 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8489 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8490 } 8491 } 8492 } 8493 8494 @Override 8495 void handleReturnCode() { 8496 if (mObserver != null) { 8497 try { 8498 mObserver.onGetStatsCompleted(mStats, mSuccess); 8499 } catch (RemoteException e) { 8500 Slog.i(TAG, "Observer no longer exists."); 8501 } 8502 } 8503 } 8504 8505 @Override 8506 void handleServiceError() { 8507 Slog.e(TAG, "Could not measure application " + mStats.packageName 8508 + " external storage"); 8509 } 8510 } 8511 8512 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8513 throws RemoteException { 8514 long result = 0; 8515 for (File path : paths) { 8516 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8517 } 8518 return result; 8519 } 8520 8521 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8522 for (File path : paths) { 8523 try { 8524 mcs.clearDirectory(path.getAbsolutePath()); 8525 } catch (RemoteException e) { 8526 } 8527 } 8528 } 8529 8530 static class OriginInfo { 8531 /** 8532 * Location where install is coming from, before it has been 8533 * copied/renamed into place. This could be a single monolithic APK 8534 * file, or a cluster directory. This location may be untrusted. 8535 */ 8536 final File file; 8537 final String cid; 8538 8539 /** 8540 * Flag indicating that {@link #file} or {@link #cid} has already been 8541 * staged, meaning downstream users don't need to defensively copy the 8542 * contents. 8543 */ 8544 final boolean staged; 8545 8546 /** 8547 * Flag indicating that {@link #file} or {@link #cid} is an already 8548 * installed app that is being moved. 8549 */ 8550 final boolean existing; 8551 8552 final String resolvedPath; 8553 final File resolvedFile; 8554 8555 static OriginInfo fromNothing() { 8556 return new OriginInfo(null, null, false, false); 8557 } 8558 8559 static OriginInfo fromUntrustedFile(File file) { 8560 return new OriginInfo(file, null, false, false); 8561 } 8562 8563 static OriginInfo fromExistingFile(File file) { 8564 return new OriginInfo(file, null, false, true); 8565 } 8566 8567 static OriginInfo fromStagedFile(File file) { 8568 return new OriginInfo(file, null, true, false); 8569 } 8570 8571 static OriginInfo fromStagedContainer(String cid) { 8572 return new OriginInfo(null, cid, true, false); 8573 } 8574 8575 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8576 this.file = file; 8577 this.cid = cid; 8578 this.staged = staged; 8579 this.existing = existing; 8580 8581 if (cid != null) { 8582 resolvedPath = PackageHelper.getSdDir(cid); 8583 resolvedFile = new File(resolvedPath); 8584 } else if (file != null) { 8585 resolvedPath = file.getAbsolutePath(); 8586 resolvedFile = file; 8587 } else { 8588 resolvedPath = null; 8589 resolvedFile = null; 8590 } 8591 } 8592 } 8593 8594 class InstallParams extends HandlerParams { 8595 final OriginInfo origin; 8596 final IPackageInstallObserver2 observer; 8597 int installFlags; 8598 final String installerPackageName; 8599 final VerificationParams verificationParams; 8600 private InstallArgs mArgs; 8601 private int mRet; 8602 final String packageAbiOverride; 8603 8604 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8605 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8606 String packageAbiOverride) { 8607 super(user); 8608 this.origin = origin; 8609 this.observer = observer; 8610 this.installFlags = installFlags; 8611 this.installerPackageName = installerPackageName; 8612 this.verificationParams = verificationParams; 8613 this.packageAbiOverride = packageAbiOverride; 8614 } 8615 8616 @Override 8617 public String toString() { 8618 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8619 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8620 } 8621 8622 public ManifestDigest getManifestDigest() { 8623 if (verificationParams == null) { 8624 return null; 8625 } 8626 return verificationParams.getManifestDigest(); 8627 } 8628 8629 private int installLocationPolicy(PackageInfoLite pkgLite) { 8630 String packageName = pkgLite.packageName; 8631 int installLocation = pkgLite.installLocation; 8632 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8633 // reader 8634 synchronized (mPackages) { 8635 PackageParser.Package pkg = mPackages.get(packageName); 8636 if (pkg != null) { 8637 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8638 // Check for downgrading. 8639 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8640 if (pkgLite.versionCode < pkg.mVersionCode) { 8641 Slog.w(TAG, "Can't install update of " + packageName 8642 + " update version " + pkgLite.versionCode 8643 + " is older than installed version " 8644 + pkg.mVersionCode); 8645 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8646 } 8647 } 8648 // Check for updated system application. 8649 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8650 if (onSd) { 8651 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8652 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8653 } 8654 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8655 } else { 8656 if (onSd) { 8657 // Install flag overrides everything. 8658 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8659 } 8660 // If current upgrade specifies particular preference 8661 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8662 // Application explicitly specified internal. 8663 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8664 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8665 // App explictly prefers external. Let policy decide 8666 } else { 8667 // Prefer previous location 8668 if (isExternal(pkg)) { 8669 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8670 } 8671 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8672 } 8673 } 8674 } else { 8675 // Invalid install. Return error code 8676 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8677 } 8678 } 8679 } 8680 // All the special cases have been taken care of. 8681 // Return result based on recommended install location. 8682 if (onSd) { 8683 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8684 } 8685 return pkgLite.recommendedInstallLocation; 8686 } 8687 8688 /* 8689 * Invoke remote method to get package information and install 8690 * location values. Override install location based on default 8691 * policy if needed and then create install arguments based 8692 * on the install location. 8693 */ 8694 public void handleStartCopy() throws RemoteException { 8695 int ret = PackageManager.INSTALL_SUCCEEDED; 8696 8697 // If we're already staged, we've firmly committed to an install location 8698 if (origin.staged) { 8699 if (origin.file != null) { 8700 installFlags |= PackageManager.INSTALL_INTERNAL; 8701 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8702 } else if (origin.cid != null) { 8703 installFlags |= PackageManager.INSTALL_EXTERNAL; 8704 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8705 } else { 8706 throw new IllegalStateException("Invalid stage location"); 8707 } 8708 } 8709 8710 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8711 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8712 8713 PackageInfoLite pkgLite = null; 8714 8715 if (onInt && onSd) { 8716 // Check if both bits are set. 8717 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8718 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8719 } else { 8720 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8721 packageAbiOverride); 8722 8723 /* 8724 * If we have too little free space, try to free cache 8725 * before giving up. 8726 */ 8727 if (!origin.staged && pkgLite.recommendedInstallLocation 8728 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8729 // TODO: focus freeing disk space on the target device 8730 final StorageManager storage = StorageManager.from(mContext); 8731 final long lowThreshold = storage.getStorageLowBytes( 8732 Environment.getDataDirectory()); 8733 8734 final long sizeBytes = mContainerService.calculateInstalledSize( 8735 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8736 8737 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8738 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8739 installFlags, packageAbiOverride); 8740 } 8741 8742 /* 8743 * The cache free must have deleted the file we 8744 * downloaded to install. 8745 * 8746 * TODO: fix the "freeCache" call to not delete 8747 * the file we care about. 8748 */ 8749 if (pkgLite.recommendedInstallLocation 8750 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8751 pkgLite.recommendedInstallLocation 8752 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8753 } 8754 } 8755 } 8756 8757 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8758 int loc = pkgLite.recommendedInstallLocation; 8759 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8760 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8761 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8762 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8763 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8764 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8765 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8766 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8767 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8768 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8769 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8770 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8771 } else { 8772 // Override with defaults if needed. 8773 loc = installLocationPolicy(pkgLite); 8774 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8775 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8776 } else if (!onSd && !onInt) { 8777 // Override install location with flags 8778 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8779 // Set the flag to install on external media. 8780 installFlags |= PackageManager.INSTALL_EXTERNAL; 8781 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8782 } else { 8783 // Make sure the flag for installing on external 8784 // media is unset 8785 installFlags |= PackageManager.INSTALL_INTERNAL; 8786 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8787 } 8788 } 8789 } 8790 } 8791 8792 final InstallArgs args = createInstallArgs(this); 8793 mArgs = args; 8794 8795 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8796 /* 8797 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8798 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8799 */ 8800 int userIdentifier = getUser().getIdentifier(); 8801 if (userIdentifier == UserHandle.USER_ALL 8802 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8803 userIdentifier = UserHandle.USER_OWNER; 8804 } 8805 8806 /* 8807 * Determine if we have any installed package verifiers. If we 8808 * do, then we'll defer to them to verify the packages. 8809 */ 8810 final int requiredUid = mRequiredVerifierPackage == null ? -1 8811 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8812 if (!origin.existing && requiredUid != -1 8813 && isVerificationEnabled(userIdentifier, installFlags)) { 8814 final Intent verification = new Intent( 8815 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8816 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 8817 PACKAGE_MIME_TYPE); 8818 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8819 8820 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8821 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8822 0 /* TODO: Which userId? */); 8823 8824 if (DEBUG_VERIFY) { 8825 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8826 + verification.toString() + " with " + pkgLite.verifiers.length 8827 + " optional verifiers"); 8828 } 8829 8830 final int verificationId = mPendingVerificationToken++; 8831 8832 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8833 8834 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8835 installerPackageName); 8836 8837 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 8838 installFlags); 8839 8840 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8841 pkgLite.packageName); 8842 8843 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8844 pkgLite.versionCode); 8845 8846 if (verificationParams != null) { 8847 if (verificationParams.getVerificationURI() != null) { 8848 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8849 verificationParams.getVerificationURI()); 8850 } 8851 if (verificationParams.getOriginatingURI() != null) { 8852 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8853 verificationParams.getOriginatingURI()); 8854 } 8855 if (verificationParams.getReferrer() != null) { 8856 verification.putExtra(Intent.EXTRA_REFERRER, 8857 verificationParams.getReferrer()); 8858 } 8859 if (verificationParams.getOriginatingUid() >= 0) { 8860 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8861 verificationParams.getOriginatingUid()); 8862 } 8863 if (verificationParams.getInstallerUid() >= 0) { 8864 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8865 verificationParams.getInstallerUid()); 8866 } 8867 } 8868 8869 final PackageVerificationState verificationState = new PackageVerificationState( 8870 requiredUid, args); 8871 8872 mPendingVerification.append(verificationId, verificationState); 8873 8874 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8875 receivers, verificationState); 8876 8877 /* 8878 * If any sufficient verifiers were listed in the package 8879 * manifest, attempt to ask them. 8880 */ 8881 if (sufficientVerifiers != null) { 8882 final int N = sufficientVerifiers.size(); 8883 if (N == 0) { 8884 Slog.i(TAG, "Additional verifiers required, but none installed."); 8885 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8886 } else { 8887 for (int i = 0; i < N; i++) { 8888 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8889 8890 final Intent sufficientIntent = new Intent(verification); 8891 sufficientIntent.setComponent(verifierComponent); 8892 8893 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8894 } 8895 } 8896 } 8897 8898 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8899 mRequiredVerifierPackage, receivers); 8900 if (ret == PackageManager.INSTALL_SUCCEEDED 8901 && mRequiredVerifierPackage != null) { 8902 /* 8903 * Send the intent to the required verification agent, 8904 * but only start the verification timeout after the 8905 * target BroadcastReceivers have run. 8906 */ 8907 verification.setComponent(requiredVerifierComponent); 8908 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8909 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8910 new BroadcastReceiver() { 8911 @Override 8912 public void onReceive(Context context, Intent intent) { 8913 final Message msg = mHandler 8914 .obtainMessage(CHECK_PENDING_VERIFICATION); 8915 msg.arg1 = verificationId; 8916 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8917 } 8918 }, null, 0, null, null); 8919 8920 /* 8921 * We don't want the copy to proceed until verification 8922 * succeeds, so null out this field. 8923 */ 8924 mArgs = null; 8925 } 8926 } else { 8927 /* 8928 * No package verification is enabled, so immediately start 8929 * the remote call to initiate copy using temporary file. 8930 */ 8931 ret = args.copyApk(mContainerService, true); 8932 } 8933 } 8934 8935 mRet = ret; 8936 } 8937 8938 @Override 8939 void handleReturnCode() { 8940 // If mArgs is null, then MCS couldn't be reached. When it 8941 // reconnects, it will try again to install. At that point, this 8942 // will succeed. 8943 if (mArgs != null) { 8944 processPendingInstall(mArgs, mRet); 8945 } 8946 } 8947 8948 @Override 8949 void handleServiceError() { 8950 mArgs = createInstallArgs(this); 8951 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8952 } 8953 8954 public boolean isForwardLocked() { 8955 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8956 } 8957 } 8958 8959 /** 8960 * Used during creation of InstallArgs 8961 * 8962 * @param installFlags package installation flags 8963 * @return true if should be installed on external storage 8964 */ 8965 private static boolean installOnSd(int installFlags) { 8966 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 8967 return false; 8968 } 8969 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 8970 return true; 8971 } 8972 return false; 8973 } 8974 8975 /** 8976 * Used during creation of InstallArgs 8977 * 8978 * @param installFlags package installation flags 8979 * @return true if should be installed as forward locked 8980 */ 8981 private static boolean installForwardLocked(int installFlags) { 8982 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8983 } 8984 8985 private InstallArgs createInstallArgs(InstallParams params) { 8986 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 8987 return new AsecInstallArgs(params); 8988 } else { 8989 return new FileInstallArgs(params); 8990 } 8991 } 8992 8993 /** 8994 * Create args that describe an existing installed package. Typically used 8995 * when cleaning up old installs, or used as a move source. 8996 */ 8997 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 8998 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 8999 final boolean isInAsec; 9000 if (installOnSd(installFlags)) { 9001 /* Apps on SD card are always in ASEC containers. */ 9002 isInAsec = true; 9003 } else if (installForwardLocked(installFlags) 9004 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9005 /* 9006 * Forward-locked apps are only in ASEC containers if they're the 9007 * new style 9008 */ 9009 isInAsec = true; 9010 } else { 9011 isInAsec = false; 9012 } 9013 9014 if (isInAsec) { 9015 return new AsecInstallArgs(codePath, instructionSets, 9016 installOnSd(installFlags), installForwardLocked(installFlags)); 9017 } else { 9018 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9019 instructionSets); 9020 } 9021 } 9022 9023 static abstract class InstallArgs { 9024 /** @see InstallParams#origin */ 9025 final OriginInfo origin; 9026 9027 final IPackageInstallObserver2 observer; 9028 // Always refers to PackageManager flags only 9029 final int installFlags; 9030 final String installerPackageName; 9031 final ManifestDigest manifestDigest; 9032 final UserHandle user; 9033 final String abiOverride; 9034 9035 // The list of instruction sets supported by this app. This is currently 9036 // only used during the rmdex() phase to clean up resources. We can get rid of this 9037 // if we move dex files under the common app path. 9038 /* nullable */ String[] instructionSets; 9039 9040 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9041 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 9042 String[] instructionSets, String abiOverride) { 9043 this.origin = origin; 9044 this.installFlags = installFlags; 9045 this.observer = observer; 9046 this.installerPackageName = installerPackageName; 9047 this.manifestDigest = manifestDigest; 9048 this.user = user; 9049 this.instructionSets = instructionSets; 9050 this.abiOverride = abiOverride; 9051 } 9052 9053 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9054 abstract int doPreInstall(int status); 9055 9056 /** 9057 * Rename package into final resting place. All paths on the given 9058 * scanned package should be updated to reflect the rename. 9059 */ 9060 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9061 abstract int doPostInstall(int status, int uid); 9062 9063 /** @see PackageSettingBase#codePathString */ 9064 abstract String getCodePath(); 9065 /** @see PackageSettingBase#resourcePathString */ 9066 abstract String getResourcePath(); 9067 abstract String getLegacyNativeLibraryPath(); 9068 9069 // Need installer lock especially for dex file removal. 9070 abstract void cleanUpResourcesLI(); 9071 abstract boolean doPostDeleteLI(boolean delete); 9072 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9073 9074 /** 9075 * Called before the source arguments are copied. This is used mostly 9076 * for MoveParams when it needs to read the source file to put it in the 9077 * destination. 9078 */ 9079 int doPreCopy() { 9080 return PackageManager.INSTALL_SUCCEEDED; 9081 } 9082 9083 /** 9084 * Called after the source arguments are copied. This is used mostly for 9085 * MoveParams when it needs to read the source file to put it in the 9086 * destination. 9087 * 9088 * @return 9089 */ 9090 int doPostCopy(int uid) { 9091 return PackageManager.INSTALL_SUCCEEDED; 9092 } 9093 9094 protected boolean isFwdLocked() { 9095 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9096 } 9097 9098 protected boolean isExternal() { 9099 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9100 } 9101 9102 UserHandle getUser() { 9103 return user; 9104 } 9105 } 9106 9107 /** 9108 * Logic to handle installation of non-ASEC applications, including copying 9109 * and renaming logic. 9110 */ 9111 class FileInstallArgs extends InstallArgs { 9112 private File codeFile; 9113 private File resourceFile; 9114 private File legacyNativeLibraryPath; 9115 9116 // Example topology: 9117 // /data/app/com.example/base.apk 9118 // /data/app/com.example/split_foo.apk 9119 // /data/app/com.example/lib/arm/libfoo.so 9120 // /data/app/com.example/lib/arm64/libfoo.so 9121 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9122 9123 /** New install */ 9124 FileInstallArgs(InstallParams params) { 9125 super(params.origin, params.observer, params.installFlags, 9126 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9127 null /* instruction sets */, params.packageAbiOverride); 9128 if (isFwdLocked()) { 9129 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9130 } 9131 } 9132 9133 /** Existing install */ 9134 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9135 String[] instructionSets) { 9136 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9137 this.codeFile = (codePath != null) ? new File(codePath) : null; 9138 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9139 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9140 new File(legacyNativeLibraryPath) : null; 9141 } 9142 9143 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9144 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9145 isFwdLocked(), abiOverride); 9146 9147 final StorageManager storage = StorageManager.from(mContext); 9148 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9149 } 9150 9151 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9152 if (origin.staged) { 9153 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9154 codeFile = origin.file; 9155 resourceFile = origin.file; 9156 return PackageManager.INSTALL_SUCCEEDED; 9157 } 9158 9159 try { 9160 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9161 codeFile = tempDir; 9162 resourceFile = tempDir; 9163 } catch (IOException e) { 9164 Slog.w(TAG, "Failed to create copy file: " + e); 9165 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9166 } 9167 9168 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9169 @Override 9170 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9171 if (!FileUtils.isValidExtFilename(name)) { 9172 throw new IllegalArgumentException("Invalid filename: " + name); 9173 } 9174 try { 9175 final File file = new File(codeFile, name); 9176 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9177 O_RDWR | O_CREAT, 0644); 9178 Os.chmod(file.getAbsolutePath(), 0644); 9179 return new ParcelFileDescriptor(fd); 9180 } catch (ErrnoException e) { 9181 throw new RemoteException("Failed to open: " + e.getMessage()); 9182 } 9183 } 9184 }; 9185 9186 int ret = PackageManager.INSTALL_SUCCEEDED; 9187 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9188 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9189 Slog.e(TAG, "Failed to copy package"); 9190 return ret; 9191 } 9192 9193 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9194 NativeLibraryHelper.Handle handle = null; 9195 try { 9196 handle = NativeLibraryHelper.Handle.create(codeFile); 9197 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9198 abiOverride); 9199 } catch (IOException e) { 9200 Slog.e(TAG, "Copying native libraries failed", e); 9201 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9202 } finally { 9203 IoUtils.closeQuietly(handle); 9204 } 9205 9206 return ret; 9207 } 9208 9209 int doPreInstall(int status) { 9210 if (status != PackageManager.INSTALL_SUCCEEDED) { 9211 cleanUp(); 9212 } 9213 return status; 9214 } 9215 9216 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9217 if (status != PackageManager.INSTALL_SUCCEEDED) { 9218 cleanUp(); 9219 return false; 9220 } else { 9221 final File beforeCodeFile = codeFile; 9222 final File afterCodeFile = getNextCodePath(pkg.packageName); 9223 9224 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9225 try { 9226 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9227 } catch (ErrnoException e) { 9228 Slog.d(TAG, "Failed to rename", e); 9229 return false; 9230 } 9231 9232 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9233 Slog.d(TAG, "Failed to restorecon"); 9234 return false; 9235 } 9236 9237 // Reflect the rename internally 9238 codeFile = afterCodeFile; 9239 resourceFile = afterCodeFile; 9240 9241 // Reflect the rename in scanned details 9242 pkg.codePath = afterCodeFile.getAbsolutePath(); 9243 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9244 pkg.baseCodePath); 9245 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9246 pkg.splitCodePaths); 9247 9248 // Reflect the rename in app info 9249 pkg.applicationInfo.setCodePath(pkg.codePath); 9250 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9251 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9252 pkg.applicationInfo.setResourcePath(pkg.codePath); 9253 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9254 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9255 9256 return true; 9257 } 9258 } 9259 9260 int doPostInstall(int status, int uid) { 9261 if (status != PackageManager.INSTALL_SUCCEEDED) { 9262 cleanUp(); 9263 } 9264 return status; 9265 } 9266 9267 @Override 9268 String getCodePath() { 9269 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9270 } 9271 9272 @Override 9273 String getResourcePath() { 9274 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9275 } 9276 9277 @Override 9278 String getLegacyNativeLibraryPath() { 9279 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9280 } 9281 9282 private boolean cleanUp() { 9283 if (codeFile == null || !codeFile.exists()) { 9284 return false; 9285 } 9286 9287 if (codeFile.isDirectory()) { 9288 FileUtils.deleteContents(codeFile); 9289 } 9290 codeFile.delete(); 9291 9292 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9293 resourceFile.delete(); 9294 } 9295 9296 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9297 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9298 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9299 } 9300 legacyNativeLibraryPath.delete(); 9301 } 9302 9303 return true; 9304 } 9305 9306 void cleanUpResourcesLI() { 9307 // Try enumerating all code paths before deleting 9308 List<String> allCodePaths = Collections.EMPTY_LIST; 9309 if (codeFile != null && codeFile.exists()) { 9310 try { 9311 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9312 allCodePaths = pkg.getAllCodePaths(); 9313 } catch (PackageParserException e) { 9314 // Ignored; we tried our best 9315 } 9316 } 9317 9318 cleanUp(); 9319 9320 if (!allCodePaths.isEmpty()) { 9321 if (instructionSets == null) { 9322 throw new IllegalStateException("instructionSet == null"); 9323 } 9324 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9325 for (String codePath : allCodePaths) { 9326 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9327 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9328 if (retCode < 0) { 9329 Slog.w(TAG, "Couldn't remove dex file for package: " 9330 + " at location " + codePath + ", retcode=" + retCode); 9331 // we don't consider this to be a failure of the core package deletion 9332 } 9333 } 9334 } 9335 } 9336 } 9337 9338 boolean doPostDeleteLI(boolean delete) { 9339 // XXX err, shouldn't we respect the delete flag? 9340 cleanUpResourcesLI(); 9341 return true; 9342 } 9343 } 9344 9345 private boolean isAsecExternal(String cid) { 9346 final String asecPath = PackageHelper.getSdFilesystem(cid); 9347 return !asecPath.startsWith(mAsecInternalPath); 9348 } 9349 9350 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9351 PackageManagerException { 9352 if (copyRet < 0) { 9353 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9354 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9355 throw new PackageManagerException(copyRet, message); 9356 } 9357 } 9358 } 9359 9360 /** 9361 * Extract the MountService "container ID" from the full code path of an 9362 * .apk. 9363 */ 9364 static String cidFromCodePath(String fullCodePath) { 9365 int eidx = fullCodePath.lastIndexOf("/"); 9366 String subStr1 = fullCodePath.substring(0, eidx); 9367 int sidx = subStr1.lastIndexOf("/"); 9368 return subStr1.substring(sidx+1, eidx); 9369 } 9370 9371 /** 9372 * Logic to handle installation of ASEC applications, including copying and 9373 * renaming logic. 9374 */ 9375 class AsecInstallArgs extends InstallArgs { 9376 static final String RES_FILE_NAME = "pkg.apk"; 9377 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9378 9379 String cid; 9380 String packagePath; 9381 String resourcePath; 9382 String legacyNativeLibraryDir; 9383 9384 /** New install */ 9385 AsecInstallArgs(InstallParams params) { 9386 super(params.origin, params.observer, params.installFlags, 9387 params.installerPackageName, params.getManifestDigest(), 9388 params.getUser(), null /* instruction sets */, 9389 params.packageAbiOverride); 9390 } 9391 9392 /** Existing install */ 9393 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9394 boolean isExternal, boolean isForwardLocked) { 9395 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9396 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9397 instructionSets, null); 9398 // Hackily pretend we're still looking at a full code path 9399 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9400 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9401 } 9402 9403 // Extract cid from fullCodePath 9404 int eidx = fullCodePath.lastIndexOf("/"); 9405 String subStr1 = fullCodePath.substring(0, eidx); 9406 int sidx = subStr1.lastIndexOf("/"); 9407 cid = subStr1.substring(sidx+1, eidx); 9408 setMountPath(subStr1); 9409 } 9410 9411 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9412 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9413 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9414 instructionSets, null); 9415 this.cid = cid; 9416 setMountPath(PackageHelper.getSdDir(cid)); 9417 } 9418 9419 void createCopyFile() { 9420 cid = mInstallerService.allocateExternalStageCidLegacy(); 9421 } 9422 9423 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9424 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9425 abiOverride); 9426 9427 final File target; 9428 if (isExternal()) { 9429 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9430 } else { 9431 target = Environment.getDataDirectory(); 9432 } 9433 9434 final StorageManager storage = StorageManager.from(mContext); 9435 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9436 } 9437 9438 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9439 if (origin.staged) { 9440 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9441 cid = origin.cid; 9442 setMountPath(PackageHelper.getSdDir(cid)); 9443 return PackageManager.INSTALL_SUCCEEDED; 9444 } 9445 9446 if (temp) { 9447 createCopyFile(); 9448 } else { 9449 /* 9450 * Pre-emptively destroy the container since it's destroyed if 9451 * copying fails due to it existing anyway. 9452 */ 9453 PackageHelper.destroySdDir(cid); 9454 } 9455 9456 final String newMountPath = imcs.copyPackageToContainer( 9457 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9458 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9459 9460 if (newMountPath != null) { 9461 setMountPath(newMountPath); 9462 return PackageManager.INSTALL_SUCCEEDED; 9463 } else { 9464 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9465 } 9466 } 9467 9468 @Override 9469 String getCodePath() { 9470 return packagePath; 9471 } 9472 9473 @Override 9474 String getResourcePath() { 9475 return resourcePath; 9476 } 9477 9478 @Override 9479 String getLegacyNativeLibraryPath() { 9480 return legacyNativeLibraryDir; 9481 } 9482 9483 int doPreInstall(int status) { 9484 if (status != PackageManager.INSTALL_SUCCEEDED) { 9485 // Destroy container 9486 PackageHelper.destroySdDir(cid); 9487 } else { 9488 boolean mounted = PackageHelper.isContainerMounted(cid); 9489 if (!mounted) { 9490 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9491 Process.SYSTEM_UID); 9492 if (newMountPath != null) { 9493 setMountPath(newMountPath); 9494 } else { 9495 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9496 } 9497 } 9498 } 9499 return status; 9500 } 9501 9502 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9503 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9504 String newMountPath = null; 9505 if (PackageHelper.isContainerMounted(cid)) { 9506 // Unmount the container 9507 if (!PackageHelper.unMountSdDir(cid)) { 9508 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9509 return false; 9510 } 9511 } 9512 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9513 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9514 " which might be stale. Will try to clean up."); 9515 // Clean up the stale container and proceed to recreate. 9516 if (!PackageHelper.destroySdDir(newCacheId)) { 9517 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9518 return false; 9519 } 9520 // Successfully cleaned up stale container. Try to rename again. 9521 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9522 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9523 + " inspite of cleaning it up."); 9524 return false; 9525 } 9526 } 9527 if (!PackageHelper.isContainerMounted(newCacheId)) { 9528 Slog.w(TAG, "Mounting container " + newCacheId); 9529 newMountPath = PackageHelper.mountSdDir(newCacheId, 9530 getEncryptKey(), Process.SYSTEM_UID); 9531 } else { 9532 newMountPath = PackageHelper.getSdDir(newCacheId); 9533 } 9534 if (newMountPath == null) { 9535 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9536 return false; 9537 } 9538 Log.i(TAG, "Succesfully renamed " + cid + 9539 " to " + newCacheId + 9540 " at new path: " + newMountPath); 9541 cid = newCacheId; 9542 9543 final File beforeCodeFile = new File(packagePath); 9544 setMountPath(newMountPath); 9545 final File afterCodeFile = new File(packagePath); 9546 9547 // Reflect the rename in scanned details 9548 pkg.codePath = afterCodeFile.getAbsolutePath(); 9549 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9550 pkg.baseCodePath); 9551 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9552 pkg.splitCodePaths); 9553 9554 // Reflect the rename in app info 9555 pkg.applicationInfo.setCodePath(pkg.codePath); 9556 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9557 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9558 pkg.applicationInfo.setResourcePath(pkg.codePath); 9559 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9560 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9561 9562 return true; 9563 } 9564 9565 private void setMountPath(String mountPath) { 9566 final File mountFile = new File(mountPath); 9567 9568 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9569 if (monolithicFile.exists()) { 9570 packagePath = monolithicFile.getAbsolutePath(); 9571 if (isFwdLocked()) { 9572 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9573 } else { 9574 resourcePath = packagePath; 9575 } 9576 } else { 9577 packagePath = mountFile.getAbsolutePath(); 9578 resourcePath = packagePath; 9579 } 9580 9581 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9582 } 9583 9584 int doPostInstall(int status, int uid) { 9585 if (status != PackageManager.INSTALL_SUCCEEDED) { 9586 cleanUp(); 9587 } else { 9588 final int groupOwner; 9589 final String protectedFile; 9590 if (isFwdLocked()) { 9591 groupOwner = UserHandle.getSharedAppGid(uid); 9592 protectedFile = RES_FILE_NAME; 9593 } else { 9594 groupOwner = -1; 9595 protectedFile = null; 9596 } 9597 9598 if (uid < Process.FIRST_APPLICATION_UID 9599 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9600 Slog.e(TAG, "Failed to finalize " + cid); 9601 PackageHelper.destroySdDir(cid); 9602 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9603 } 9604 9605 boolean mounted = PackageHelper.isContainerMounted(cid); 9606 if (!mounted) { 9607 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9608 } 9609 } 9610 return status; 9611 } 9612 9613 private void cleanUp() { 9614 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9615 9616 // Destroy secure container 9617 PackageHelper.destroySdDir(cid); 9618 } 9619 9620 private List<String> getAllCodePaths() { 9621 final File codeFile = new File(getCodePath()); 9622 if (codeFile != null && codeFile.exists()) { 9623 try { 9624 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9625 return pkg.getAllCodePaths(); 9626 } catch (PackageParserException e) { 9627 // Ignored; we tried our best 9628 } 9629 } 9630 return Collections.EMPTY_LIST; 9631 } 9632 9633 void cleanUpResourcesLI() { 9634 // Enumerate all code paths before deleting 9635 cleanUpResourcesLI(getAllCodePaths()); 9636 } 9637 9638 private void cleanUpResourcesLI(List<String> allCodePaths) { 9639 cleanUp(); 9640 9641 if (!allCodePaths.isEmpty()) { 9642 if (instructionSets == null) { 9643 throw new IllegalStateException("instructionSet == null"); 9644 } 9645 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9646 for (String codePath : allCodePaths) { 9647 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9648 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9649 if (retCode < 0) { 9650 Slog.w(TAG, "Couldn't remove dex file for package: " 9651 + " at location " + codePath + ", retcode=" + retCode); 9652 // we don't consider this to be a failure of the core package deletion 9653 } 9654 } 9655 } 9656 } 9657 } 9658 9659 boolean matchContainer(String app) { 9660 if (cid.startsWith(app)) { 9661 return true; 9662 } 9663 return false; 9664 } 9665 9666 String getPackageName() { 9667 return getAsecPackageName(cid); 9668 } 9669 9670 boolean doPostDeleteLI(boolean delete) { 9671 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9672 final List<String> allCodePaths = getAllCodePaths(); 9673 boolean mounted = PackageHelper.isContainerMounted(cid); 9674 if (mounted) { 9675 // Unmount first 9676 if (PackageHelper.unMountSdDir(cid)) { 9677 mounted = false; 9678 } 9679 } 9680 if (!mounted && delete) { 9681 cleanUpResourcesLI(allCodePaths); 9682 } 9683 return !mounted; 9684 } 9685 9686 @Override 9687 int doPreCopy() { 9688 if (isFwdLocked()) { 9689 if (!PackageHelper.fixSdPermissions(cid, 9690 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9691 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9692 } 9693 } 9694 9695 return PackageManager.INSTALL_SUCCEEDED; 9696 } 9697 9698 @Override 9699 int doPostCopy(int uid) { 9700 if (isFwdLocked()) { 9701 if (uid < Process.FIRST_APPLICATION_UID 9702 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9703 RES_FILE_NAME)) { 9704 Slog.e(TAG, "Failed to finalize " + cid); 9705 PackageHelper.destroySdDir(cid); 9706 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9707 } 9708 } 9709 9710 return PackageManager.INSTALL_SUCCEEDED; 9711 } 9712 } 9713 9714 static String getAsecPackageName(String packageCid) { 9715 int idx = packageCid.lastIndexOf("-"); 9716 if (idx == -1) { 9717 return packageCid; 9718 } 9719 return packageCid.substring(0, idx); 9720 } 9721 9722 // Utility method used to create code paths based on package name and available index. 9723 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9724 String idxStr = ""; 9725 int idx = 1; 9726 // Fall back to default value of idx=1 if prefix is not 9727 // part of oldCodePath 9728 if (oldCodePath != null) { 9729 String subStr = oldCodePath; 9730 // Drop the suffix right away 9731 if (suffix != null && subStr.endsWith(suffix)) { 9732 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9733 } 9734 // If oldCodePath already contains prefix find out the 9735 // ending index to either increment or decrement. 9736 int sidx = subStr.lastIndexOf(prefix); 9737 if (sidx != -1) { 9738 subStr = subStr.substring(sidx + prefix.length()); 9739 if (subStr != null) { 9740 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9741 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9742 } 9743 try { 9744 idx = Integer.parseInt(subStr); 9745 if (idx <= 1) { 9746 idx++; 9747 } else { 9748 idx--; 9749 } 9750 } catch(NumberFormatException e) { 9751 } 9752 } 9753 } 9754 } 9755 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9756 return prefix + idxStr; 9757 } 9758 9759 private File getNextCodePath(String packageName) { 9760 int suffix = 1; 9761 File result; 9762 do { 9763 result = new File(mAppInstallDir, packageName + "-" + suffix); 9764 suffix++; 9765 } while (result.exists()); 9766 return result; 9767 } 9768 9769 // Utility method used to ignore ADD/REMOVE events 9770 // by directory observer. 9771 private static boolean ignoreCodePath(String fullPathStr) { 9772 String apkName = deriveCodePathName(fullPathStr); 9773 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9774 if (idx != -1 && ((idx+1) < apkName.length())) { 9775 // Make sure the package ends with a numeral 9776 String version = apkName.substring(idx+1); 9777 try { 9778 Integer.parseInt(version); 9779 return true; 9780 } catch (NumberFormatException e) {} 9781 } 9782 return false; 9783 } 9784 9785 // Utility method that returns the relative package path with respect 9786 // to the installation directory. Like say for /data/data/com.test-1.apk 9787 // string com.test-1 is returned. 9788 static String deriveCodePathName(String codePath) { 9789 if (codePath == null) { 9790 return null; 9791 } 9792 final File codeFile = new File(codePath); 9793 final String name = codeFile.getName(); 9794 if (codeFile.isDirectory()) { 9795 return name; 9796 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9797 final int lastDot = name.lastIndexOf('.'); 9798 return name.substring(0, lastDot); 9799 } else { 9800 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9801 return null; 9802 } 9803 } 9804 9805 class PackageInstalledInfo { 9806 String name; 9807 int uid; 9808 // The set of users that originally had this package installed. 9809 int[] origUsers; 9810 // The set of users that now have this package installed. 9811 int[] newUsers; 9812 PackageParser.Package pkg; 9813 int returnCode; 9814 String returnMsg; 9815 PackageRemovedInfo removedInfo; 9816 9817 public void setError(int code, String msg) { 9818 returnCode = code; 9819 returnMsg = msg; 9820 Slog.w(TAG, msg); 9821 } 9822 9823 public void setError(String msg, PackageParserException e) { 9824 returnCode = e.error; 9825 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9826 Slog.w(TAG, msg, e); 9827 } 9828 9829 public void setError(String msg, PackageManagerException e) { 9830 returnCode = e.error; 9831 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9832 Slog.w(TAG, msg, e); 9833 } 9834 9835 // In some error cases we want to convey more info back to the observer 9836 String origPackage; 9837 String origPermission; 9838 } 9839 9840 /* 9841 * Install a non-existing package. 9842 */ 9843 private void installNewPackageLI(PackageParser.Package pkg, 9844 int parseFlags, int scanFlags, UserHandle user, 9845 String installerPackageName, PackageInstalledInfo res) { 9846 // Remember this for later, in case we need to rollback this install 9847 String pkgName = pkg.packageName; 9848 9849 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9850 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9851 synchronized(mPackages) { 9852 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9853 // A package with the same name is already installed, though 9854 // it has been renamed to an older name. The package we 9855 // are trying to install should be installed as an update to 9856 // the existing one, but that has not been requested, so bail. 9857 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9858 + " without first uninstalling package running as " 9859 + mSettings.mRenamedPackages.get(pkgName)); 9860 return; 9861 } 9862 if (mPackages.containsKey(pkgName)) { 9863 // Don't allow installation over an existing package with the same name. 9864 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9865 + " without first uninstalling."); 9866 return; 9867 } 9868 } 9869 9870 try { 9871 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 9872 System.currentTimeMillis(), user); 9873 9874 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9875 // delete the partially installed application. the data directory will have to be 9876 // restored if it was already existing 9877 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9878 // remove package from internal structures. Note that we want deletePackageX to 9879 // delete the package data and cache directories that it created in 9880 // scanPackageLocked, unless those directories existed before we even tried to 9881 // install. 9882 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9883 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9884 res.removedInfo, true); 9885 } 9886 9887 } catch (PackageManagerException e) { 9888 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9889 } 9890 } 9891 9892 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9893 // Upgrade keysets are being used. Determine if new package has a superset of the 9894 // required keys. 9895 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9896 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9897 for (int i = 0; i < upgradeKeySets.length; i++) { 9898 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9899 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9900 return true; 9901 } 9902 } 9903 return false; 9904 } 9905 9906 private void replacePackageLI(PackageParser.Package pkg, 9907 int parseFlags, int scanFlags, UserHandle user, 9908 String installerPackageName, PackageInstalledInfo res) { 9909 PackageParser.Package oldPackage; 9910 String pkgName = pkg.packageName; 9911 int[] allUsers; 9912 boolean[] perUserInstalled; 9913 9914 // First find the old package info and check signatures 9915 synchronized(mPackages) { 9916 oldPackage = mPackages.get(pkgName); 9917 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9918 PackageSetting ps = mSettings.mPackages.get(pkgName); 9919 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9920 // default to original signature matching 9921 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9922 != PackageManager.SIGNATURE_MATCH) { 9923 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9924 "New package has a different signature: " + pkgName); 9925 return; 9926 } 9927 } else { 9928 if(!checkUpgradeKeySetLP(ps, pkg)) { 9929 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9930 "New package not signed by keys specified by upgrade-keysets: " 9931 + pkgName); 9932 return; 9933 } 9934 } 9935 9936 // In case of rollback, remember per-user/profile install state 9937 allUsers = sUserManager.getUserIds(); 9938 perUserInstalled = new boolean[allUsers.length]; 9939 for (int i = 0; i < allUsers.length; i++) { 9940 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9941 } 9942 } 9943 9944 boolean sysPkg = (isSystemApp(oldPackage)); 9945 if (sysPkg) { 9946 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9947 user, allUsers, perUserInstalled, installerPackageName, res); 9948 } else { 9949 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9950 user, allUsers, perUserInstalled, installerPackageName, res); 9951 } 9952 } 9953 9954 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9955 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 9956 int[] allUsers, boolean[] perUserInstalled, 9957 String installerPackageName, PackageInstalledInfo res) { 9958 String pkgName = deletedPackage.packageName; 9959 boolean deletedPkg = true; 9960 boolean updatedSettings = false; 9961 9962 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9963 + deletedPackage); 9964 long origUpdateTime; 9965 if (pkg.mExtras != null) { 9966 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9967 } else { 9968 origUpdateTime = 0; 9969 } 9970 9971 // First delete the existing package while retaining the data directory 9972 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9973 res.removedInfo, true)) { 9974 // If the existing package wasn't successfully deleted 9975 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 9976 deletedPkg = false; 9977 } else { 9978 // Successfully deleted the old package; proceed with replace. 9979 9980 // If deleted package lived in a container, give users a chance to 9981 // relinquish resources before killing. 9982 if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) { 9983 if (DEBUG_INSTALL) { 9984 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 9985 } 9986 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 9987 final ArrayList<String> pkgList = new ArrayList<String>(1); 9988 pkgList.add(deletedPackage.applicationInfo.packageName); 9989 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 9990 } 9991 9992 deleteCodeCacheDirsLI(pkgName); 9993 try { 9994 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 9995 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 9996 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9997 updatedSettings = true; 9998 } catch (PackageManagerException e) { 9999 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10000 } 10001 } 10002 10003 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10004 // remove package from internal structures. Note that we want deletePackageX to 10005 // delete the package data and cache directories that it created in 10006 // scanPackageLocked, unless those directories existed before we even tried to 10007 // install. 10008 if(updatedSettings) { 10009 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10010 deletePackageLI( 10011 pkgName, null, true, allUsers, perUserInstalled, 10012 PackageManager.DELETE_KEEP_DATA, 10013 res.removedInfo, true); 10014 } 10015 // Since we failed to install the new package we need to restore the old 10016 // package that we deleted. 10017 if (deletedPkg) { 10018 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10019 File restoreFile = new File(deletedPackage.codePath); 10020 // Parse old package 10021 boolean oldOnSd = isExternal(deletedPackage); 10022 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10023 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10024 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10025 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10026 try { 10027 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10028 } catch (PackageManagerException e) { 10029 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10030 + e.getMessage()); 10031 return; 10032 } 10033 // Restore of old package succeeded. Update permissions. 10034 // writer 10035 synchronized (mPackages) { 10036 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10037 UPDATE_PERMISSIONS_ALL); 10038 // can downgrade to reader 10039 mSettings.writeLPr(); 10040 } 10041 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10042 } 10043 } 10044 } 10045 10046 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10047 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10048 int[] allUsers, boolean[] perUserInstalled, 10049 String installerPackageName, PackageInstalledInfo res) { 10050 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10051 + ", old=" + deletedPackage); 10052 boolean updatedSettings = false; 10053 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10054 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10055 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10056 } 10057 String packageName = deletedPackage.packageName; 10058 if (packageName == null) { 10059 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10060 "Attempt to delete null packageName."); 10061 return; 10062 } 10063 PackageParser.Package oldPkg; 10064 PackageSetting oldPkgSetting; 10065 // reader 10066 synchronized (mPackages) { 10067 oldPkg = mPackages.get(packageName); 10068 oldPkgSetting = mSettings.mPackages.get(packageName); 10069 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10070 (oldPkgSetting == null)) { 10071 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10072 "Couldn't find package:" + packageName + " information"); 10073 return; 10074 } 10075 } 10076 10077 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10078 10079 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10080 res.removedInfo.removedPackage = packageName; 10081 // Remove existing system package 10082 removePackageLI(oldPkgSetting, true); 10083 // writer 10084 synchronized (mPackages) { 10085 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10086 // We didn't need to disable the .apk as a current system package, 10087 // which means we are replacing another update that is already 10088 // installed. We need to make sure to delete the older one's .apk. 10089 res.removedInfo.args = createInstallArgsForExisting(0, 10090 deletedPackage.applicationInfo.getCodePath(), 10091 deletedPackage.applicationInfo.getResourcePath(), 10092 deletedPackage.applicationInfo.nativeLibraryRootDir, 10093 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10094 } else { 10095 res.removedInfo.args = null; 10096 } 10097 } 10098 10099 // Successfully disabled the old package. Now proceed with re-installation 10100 deleteCodeCacheDirsLI(packageName); 10101 10102 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10103 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10104 10105 PackageParser.Package newPackage = null; 10106 try { 10107 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10108 if (newPackage.mExtras != null) { 10109 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10110 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10111 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10112 10113 // is the update attempting to change shared user? that isn't going to work... 10114 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10115 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10116 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10117 + " to " + newPkgSetting.sharedUser); 10118 updatedSettings = true; 10119 } 10120 } 10121 10122 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10123 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10124 updatedSettings = true; 10125 } 10126 10127 } catch (PackageManagerException e) { 10128 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10129 } 10130 10131 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10132 // Re installation failed. Restore old information 10133 // Remove new pkg information 10134 if (newPackage != null) { 10135 removeInstalledPackageLI(newPackage, true); 10136 } 10137 // Add back the old system package 10138 try { 10139 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10140 } catch (PackageManagerException e) { 10141 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10142 } 10143 // Restore the old system information in Settings 10144 synchronized(mPackages) { 10145 if (updatedSettings) { 10146 mSettings.enableSystemPackageLPw(packageName); 10147 mSettings.setInstallerPackageName(packageName, 10148 oldPkgSetting.installerPackageName); 10149 } 10150 mSettings.writeLPr(); 10151 } 10152 } 10153 } 10154 10155 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10156 int[] allUsers, boolean[] perUserInstalled, 10157 PackageInstalledInfo res) { 10158 String pkgName = newPackage.packageName; 10159 synchronized (mPackages) { 10160 //write settings. the installStatus will be incomplete at this stage. 10161 //note that the new package setting would have already been 10162 //added to mPackages. It hasn't been persisted yet. 10163 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10164 mSettings.writeLPr(); 10165 } 10166 10167 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10168 10169 synchronized (mPackages) { 10170 updatePermissionsLPw(newPackage.packageName, newPackage, 10171 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10172 ? UPDATE_PERMISSIONS_ALL : 0)); 10173 // For system-bundled packages, we assume that installing an upgraded version 10174 // of the package implies that the user actually wants to run that new code, 10175 // so we enable the package. 10176 if (isSystemApp(newPackage)) { 10177 // NB: implicit assumption that system package upgrades apply to all users 10178 if (DEBUG_INSTALL) { 10179 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10180 } 10181 PackageSetting ps = mSettings.mPackages.get(pkgName); 10182 if (ps != null) { 10183 if (res.origUsers != null) { 10184 for (int userHandle : res.origUsers) { 10185 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10186 userHandle, installerPackageName); 10187 } 10188 } 10189 // Also convey the prior install/uninstall state 10190 if (allUsers != null && perUserInstalled != null) { 10191 for (int i = 0; i < allUsers.length; i++) { 10192 if (DEBUG_INSTALL) { 10193 Slog.d(TAG, " user " + allUsers[i] 10194 + " => " + perUserInstalled[i]); 10195 } 10196 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10197 } 10198 // these install state changes will be persisted in the 10199 // upcoming call to mSettings.writeLPr(). 10200 } 10201 } 10202 } 10203 res.name = pkgName; 10204 res.uid = newPackage.applicationInfo.uid; 10205 res.pkg = newPackage; 10206 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10207 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10208 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10209 //to update install status 10210 mSettings.writeLPr(); 10211 } 10212 } 10213 10214 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10215 final int installFlags = args.installFlags; 10216 String installerPackageName = args.installerPackageName; 10217 File tmpPackageFile = new File(args.getCodePath()); 10218 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10219 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10220 boolean replace = false; 10221 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10222 // Result object to be returned 10223 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10224 10225 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10226 // Retrieve PackageSettings and parse package 10227 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10228 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10229 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10230 PackageParser pp = new PackageParser(); 10231 pp.setSeparateProcesses(mSeparateProcesses); 10232 pp.setDisplayMetrics(mMetrics); 10233 10234 final PackageParser.Package pkg; 10235 try { 10236 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10237 } catch (PackageParserException e) { 10238 res.setError("Failed parse during installPackageLI", e); 10239 return; 10240 } 10241 10242 // Mark that we have an install time CPU ABI override. 10243 pkg.cpuAbiOverride = args.abiOverride; 10244 10245 String pkgName = res.name = pkg.packageName; 10246 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10247 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10248 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10249 return; 10250 } 10251 } 10252 10253 try { 10254 pp.collectCertificates(pkg, parseFlags); 10255 pp.collectManifestDigest(pkg); 10256 } catch (PackageParserException e) { 10257 res.setError("Failed collect during installPackageLI", e); 10258 return; 10259 } 10260 10261 /* If the installer passed in a manifest digest, compare it now. */ 10262 if (args.manifestDigest != null) { 10263 if (DEBUG_INSTALL) { 10264 final String parsedManifest = pkg.manifestDigest == null ? "null" 10265 : pkg.manifestDigest.toString(); 10266 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10267 + parsedManifest); 10268 } 10269 10270 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10271 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10272 return; 10273 } 10274 } else if (DEBUG_INSTALL) { 10275 final String parsedManifest = pkg.manifestDigest == null 10276 ? "null" : pkg.manifestDigest.toString(); 10277 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10278 } 10279 10280 // Get rid of all references to package scan path via parser. 10281 pp = null; 10282 String oldCodePath = null; 10283 boolean systemApp = false; 10284 synchronized (mPackages) { 10285 // Check whether the newly-scanned package wants to define an already-defined perm 10286 int N = pkg.permissions.size(); 10287 for (int i = N-1; i >= 0; i--) { 10288 PackageParser.Permission perm = pkg.permissions.get(i); 10289 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10290 if (bp != null) { 10291 // If the defining package is signed with our cert, it's okay. This 10292 // also includes the "updating the same package" case, of course. 10293 // "updating same package" could also involve key-rotation. 10294 final boolean sigsOk; 10295 if (!bp.sourcePackage.equals(pkg.packageName) 10296 || !(bp.packageSetting instanceof PackageSetting) 10297 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10298 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10299 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10300 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 10301 } else { 10302 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10303 } 10304 if (!sigsOk) { 10305 // If the owning package is the system itself, we log but allow 10306 // install to proceed; we fail the install on all other permission 10307 // redefinitions. 10308 if (!bp.sourcePackage.equals("android")) { 10309 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10310 + pkg.packageName + " attempting to redeclare permission " 10311 + perm.info.name + " already owned by " + bp.sourcePackage); 10312 res.origPermission = perm.info.name; 10313 res.origPackage = bp.sourcePackage; 10314 return; 10315 } else { 10316 Slog.w(TAG, "Package " + pkg.packageName 10317 + " attempting to redeclare system permission " 10318 + perm.info.name + "; ignoring new declaration"); 10319 pkg.permissions.remove(i); 10320 } 10321 } 10322 } 10323 } 10324 10325 // Check if installing already existing package 10326 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10327 String oldName = mSettings.mRenamedPackages.get(pkgName); 10328 if (pkg.mOriginalPackages != null 10329 && pkg.mOriginalPackages.contains(oldName) 10330 && mPackages.containsKey(oldName)) { 10331 // This package is derived from an original package, 10332 // and this device has been updating from that original 10333 // name. We must continue using the original name, so 10334 // rename the new package here. 10335 pkg.setPackageName(oldName); 10336 pkgName = pkg.packageName; 10337 replace = true; 10338 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10339 + oldName + " pkgName=" + pkgName); 10340 } else if (mPackages.containsKey(pkgName)) { 10341 // This package, under its official name, already exists 10342 // on the device; we should replace it. 10343 replace = true; 10344 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10345 } 10346 } 10347 PackageSetting ps = mSettings.mPackages.get(pkgName); 10348 if (ps != null) { 10349 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10350 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10351 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10352 systemApp = (ps.pkg.applicationInfo.flags & 10353 ApplicationInfo.FLAG_SYSTEM) != 0; 10354 } 10355 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10356 } 10357 } 10358 10359 if (systemApp && onSd) { 10360 // Disable updates to system apps on sdcard 10361 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10362 "Cannot install updates to system apps on sdcard"); 10363 return; 10364 } 10365 10366 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10367 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10368 return; 10369 } 10370 10371 if (replace) { 10372 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10373 installerPackageName, res); 10374 } else { 10375 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10376 args.user, installerPackageName, res); 10377 } 10378 synchronized (mPackages) { 10379 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10380 if (ps != null) { 10381 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10382 } 10383 } 10384 } 10385 10386 private static boolean isForwardLocked(PackageParser.Package pkg) { 10387 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10388 } 10389 10390 private static boolean isForwardLocked(ApplicationInfo info) { 10391 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10392 } 10393 10394 private boolean isForwardLocked(PackageSetting ps) { 10395 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10396 } 10397 10398 private static boolean isMultiArch(PackageSetting ps) { 10399 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10400 } 10401 10402 private static boolean isMultiArch(ApplicationInfo info) { 10403 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10404 } 10405 10406 private static boolean isExternal(PackageParser.Package pkg) { 10407 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10408 } 10409 10410 private static boolean isExternal(PackageSetting ps) { 10411 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10412 } 10413 10414 private static boolean isExternal(ApplicationInfo info) { 10415 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10416 } 10417 10418 private static boolean isSystemApp(PackageParser.Package pkg) { 10419 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10420 } 10421 10422 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10423 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10424 } 10425 10426 private static boolean isSystemApp(ApplicationInfo info) { 10427 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10428 } 10429 10430 private static boolean isSystemApp(PackageSetting ps) { 10431 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10432 } 10433 10434 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10435 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10436 } 10437 10438 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10439 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10440 } 10441 10442 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10443 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10444 } 10445 10446 private int packageFlagsToInstallFlags(PackageSetting ps) { 10447 int installFlags = 0; 10448 if (isExternal(ps)) { 10449 installFlags |= PackageManager.INSTALL_EXTERNAL; 10450 } 10451 if (isForwardLocked(ps)) { 10452 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10453 } 10454 return installFlags; 10455 } 10456 10457 private void deleteTempPackageFiles() { 10458 final FilenameFilter filter = new FilenameFilter() { 10459 public boolean accept(File dir, String name) { 10460 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10461 } 10462 }; 10463 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10464 file.delete(); 10465 } 10466 } 10467 10468 @Override 10469 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10470 int flags) { 10471 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10472 flags); 10473 } 10474 10475 @Override 10476 public void deletePackage(final String packageName, 10477 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10478 mContext.enforceCallingOrSelfPermission( 10479 android.Manifest.permission.DELETE_PACKAGES, null); 10480 final int uid = Binder.getCallingUid(); 10481 if (UserHandle.getUserId(uid) != userId) { 10482 mContext.enforceCallingPermission( 10483 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10484 "deletePackage for user " + userId); 10485 } 10486 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10487 try { 10488 observer.onPackageDeleted(packageName, 10489 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10490 } catch (RemoteException re) { 10491 } 10492 return; 10493 } 10494 10495 boolean uninstallBlocked = false; 10496 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10497 int[] users = sUserManager.getUserIds(); 10498 for (int i = 0; i < users.length; ++i) { 10499 if (getBlockUninstallForUser(packageName, users[i])) { 10500 uninstallBlocked = true; 10501 break; 10502 } 10503 } 10504 } else { 10505 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10506 } 10507 if (uninstallBlocked) { 10508 try { 10509 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10510 null); 10511 } catch (RemoteException re) { 10512 } 10513 return; 10514 } 10515 10516 if (DEBUG_REMOVE) { 10517 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10518 } 10519 // Queue up an async operation since the package deletion may take a little while. 10520 mHandler.post(new Runnable() { 10521 public void run() { 10522 mHandler.removeCallbacks(this); 10523 final int returnCode = deletePackageX(packageName, userId, flags); 10524 if (observer != null) { 10525 try { 10526 observer.onPackageDeleted(packageName, returnCode, null); 10527 } catch (RemoteException e) { 10528 Log.i(TAG, "Observer no longer exists."); 10529 } //end catch 10530 } //end if 10531 } //end run 10532 }); 10533 } 10534 10535 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10536 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10537 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10538 try { 10539 if (dpm != null) { 10540 if (dpm.isDeviceOwner(packageName)) { 10541 return true; 10542 } 10543 int[] users; 10544 if (userId == UserHandle.USER_ALL) { 10545 users = sUserManager.getUserIds(); 10546 } else { 10547 users = new int[]{userId}; 10548 } 10549 for (int i = 0; i < users.length; ++i) { 10550 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 10551 return true; 10552 } 10553 } 10554 } 10555 } catch (RemoteException e) { 10556 } 10557 return false; 10558 } 10559 10560 /** 10561 * This method is an internal method that could be get invoked either 10562 * to delete an installed package or to clean up a failed installation. 10563 * After deleting an installed package, a broadcast is sent to notify any 10564 * listeners that the package has been installed. For cleaning up a failed 10565 * installation, the broadcast is not necessary since the package's 10566 * installation wouldn't have sent the initial broadcast either 10567 * The key steps in deleting a package are 10568 * deleting the package information in internal structures like mPackages, 10569 * deleting the packages base directories through installd 10570 * updating mSettings to reflect current status 10571 * persisting settings for later use 10572 * sending a broadcast if necessary 10573 */ 10574 private int deletePackageX(String packageName, int userId, int flags) { 10575 final PackageRemovedInfo info = new PackageRemovedInfo(); 10576 final boolean res; 10577 10578 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 10579 ? UserHandle.ALL : new UserHandle(userId); 10580 10581 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 10582 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10583 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10584 } 10585 10586 boolean removedForAllUsers = false; 10587 boolean systemUpdate = false; 10588 10589 // for the uninstall-updates case and restricted profiles, remember the per- 10590 // userhandle installed state 10591 int[] allUsers; 10592 boolean[] perUserInstalled; 10593 synchronized (mPackages) { 10594 PackageSetting ps = mSettings.mPackages.get(packageName); 10595 allUsers = sUserManager.getUserIds(); 10596 perUserInstalled = new boolean[allUsers.length]; 10597 for (int i = 0; i < allUsers.length; i++) { 10598 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10599 } 10600 } 10601 10602 synchronized (mInstallLock) { 10603 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10604 res = deletePackageLI(packageName, removeForUser, 10605 true, allUsers, perUserInstalled, 10606 flags | REMOVE_CHATTY, info, true); 10607 systemUpdate = info.isRemovedPackageSystemUpdate; 10608 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10609 removedForAllUsers = true; 10610 } 10611 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10612 + " removedForAllUsers=" + removedForAllUsers); 10613 } 10614 10615 if (res) { 10616 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10617 10618 // If the removed package was a system update, the old system package 10619 // was re-enabled; we need to broadcast this information 10620 if (systemUpdate) { 10621 Bundle extras = new Bundle(1); 10622 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10623 ? info.removedAppId : info.uid); 10624 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10625 10626 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10627 extras, null, null, null); 10628 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10629 extras, null, null, null); 10630 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10631 null, packageName, null, null); 10632 } 10633 } 10634 // Force a gc here. 10635 Runtime.getRuntime().gc(); 10636 // Delete the resources here after sending the broadcast to let 10637 // other processes clean up before deleting resources. 10638 if (info.args != null) { 10639 synchronized (mInstallLock) { 10640 info.args.doPostDeleteLI(true); 10641 } 10642 } 10643 10644 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10645 } 10646 10647 static class PackageRemovedInfo { 10648 String removedPackage; 10649 int uid = -1; 10650 int removedAppId = -1; 10651 int[] removedUsers = null; 10652 boolean isRemovedPackageSystemUpdate = false; 10653 // Clean up resources deleted packages. 10654 InstallArgs args = null; 10655 10656 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10657 Bundle extras = new Bundle(1); 10658 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10659 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10660 if (replacing) { 10661 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10662 } 10663 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10664 if (removedPackage != null) { 10665 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10666 extras, null, null, removedUsers); 10667 if (fullRemove && !replacing) { 10668 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10669 extras, null, null, removedUsers); 10670 } 10671 } 10672 if (removedAppId >= 0) { 10673 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10674 removedUsers); 10675 } 10676 } 10677 } 10678 10679 /* 10680 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10681 * flag is not set, the data directory is removed as well. 10682 * make sure this flag is set for partially installed apps. If not its meaningless to 10683 * delete a partially installed application. 10684 */ 10685 private void removePackageDataLI(PackageSetting ps, 10686 int[] allUserHandles, boolean[] perUserInstalled, 10687 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10688 String packageName = ps.name; 10689 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10690 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10691 // Retrieve object to delete permissions for shared user later on 10692 final PackageSetting deletedPs; 10693 // reader 10694 synchronized (mPackages) { 10695 deletedPs = mSettings.mPackages.get(packageName); 10696 if (outInfo != null) { 10697 outInfo.removedPackage = packageName; 10698 outInfo.removedUsers = deletedPs != null 10699 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10700 : null; 10701 } 10702 } 10703 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10704 removeDataDirsLI(packageName); 10705 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10706 } 10707 // writer 10708 synchronized (mPackages) { 10709 if (deletedPs != null) { 10710 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10711 if (outInfo != null) { 10712 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10713 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10714 } 10715 if (deletedPs != null) { 10716 updatePermissionsLPw(deletedPs.name, null, 0); 10717 if (deletedPs.sharedUser != null) { 10718 // remove permissions associated with package 10719 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10720 } 10721 } 10722 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10723 } 10724 // make sure to preserve per-user disabled state if this removal was just 10725 // a downgrade of a system app to the factory package 10726 if (allUserHandles != null && perUserInstalled != null) { 10727 if (DEBUG_REMOVE) { 10728 Slog.d(TAG, "Propagating install state across downgrade"); 10729 } 10730 for (int i = 0; i < allUserHandles.length; i++) { 10731 if (DEBUG_REMOVE) { 10732 Slog.d(TAG, " user " + allUserHandles[i] 10733 + " => " + perUserInstalled[i]); 10734 } 10735 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10736 } 10737 } 10738 } 10739 // can downgrade to reader 10740 if (writeSettings) { 10741 // Save settings now 10742 mSettings.writeLPr(); 10743 } 10744 } 10745 if (outInfo != null) { 10746 // A user ID was deleted here. Go through all users and remove it 10747 // from KeyStore. 10748 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10749 } 10750 } 10751 10752 static boolean locationIsPrivileged(File path) { 10753 try { 10754 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10755 .getCanonicalPath(); 10756 return path.getCanonicalPath().startsWith(privilegedAppDir); 10757 } catch (IOException e) { 10758 Slog.e(TAG, "Unable to access code path " + path); 10759 } 10760 return false; 10761 } 10762 10763 /* 10764 * Tries to delete system package. 10765 */ 10766 private boolean deleteSystemPackageLI(PackageSetting newPs, 10767 int[] allUserHandles, boolean[] perUserInstalled, 10768 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10769 final boolean applyUserRestrictions 10770 = (allUserHandles != null) && (perUserInstalled != null); 10771 PackageSetting disabledPs = null; 10772 // Confirm if the system package has been updated 10773 // An updated system app can be deleted. This will also have to restore 10774 // the system pkg from system partition 10775 // reader 10776 synchronized (mPackages) { 10777 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10778 } 10779 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10780 + " disabledPs=" + disabledPs); 10781 if (disabledPs == null) { 10782 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10783 return false; 10784 } else if (DEBUG_REMOVE) { 10785 Slog.d(TAG, "Deleting system pkg from data partition"); 10786 } 10787 if (DEBUG_REMOVE) { 10788 if (applyUserRestrictions) { 10789 Slog.d(TAG, "Remembering install states:"); 10790 for (int i = 0; i < allUserHandles.length; i++) { 10791 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10792 } 10793 } 10794 } 10795 // Delete the updated package 10796 outInfo.isRemovedPackageSystemUpdate = true; 10797 if (disabledPs.versionCode < newPs.versionCode) { 10798 // Delete data for downgrades 10799 flags &= ~PackageManager.DELETE_KEEP_DATA; 10800 } else { 10801 // Preserve data by setting flag 10802 flags |= PackageManager.DELETE_KEEP_DATA; 10803 } 10804 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10805 allUserHandles, perUserInstalled, outInfo, writeSettings); 10806 if (!ret) { 10807 return false; 10808 } 10809 // writer 10810 synchronized (mPackages) { 10811 // Reinstate the old system package 10812 mSettings.enableSystemPackageLPw(newPs.name); 10813 // Remove any native libraries from the upgraded package. 10814 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10815 } 10816 // Install the system package 10817 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10818 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10819 if (locationIsPrivileged(disabledPs.codePath)) { 10820 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10821 } 10822 10823 final PackageParser.Package newPkg; 10824 try { 10825 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 10826 } catch (PackageManagerException e) { 10827 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10828 return false; 10829 } 10830 10831 // writer 10832 synchronized (mPackages) { 10833 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10834 updatePermissionsLPw(newPkg.packageName, newPkg, 10835 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10836 if (applyUserRestrictions) { 10837 if (DEBUG_REMOVE) { 10838 Slog.d(TAG, "Propagating install state across reinstall"); 10839 } 10840 for (int i = 0; i < allUserHandles.length; i++) { 10841 if (DEBUG_REMOVE) { 10842 Slog.d(TAG, " user " + allUserHandles[i] 10843 + " => " + perUserInstalled[i]); 10844 } 10845 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10846 } 10847 // Regardless of writeSettings we need to ensure that this restriction 10848 // state propagation is persisted 10849 mSettings.writeAllUsersPackageRestrictionsLPr(); 10850 } 10851 // can downgrade to reader here 10852 if (writeSettings) { 10853 mSettings.writeLPr(); 10854 } 10855 } 10856 return true; 10857 } 10858 10859 private boolean deleteInstalledPackageLI(PackageSetting ps, 10860 boolean deleteCodeAndResources, int flags, 10861 int[] allUserHandles, boolean[] perUserInstalled, 10862 PackageRemovedInfo outInfo, boolean writeSettings) { 10863 if (outInfo != null) { 10864 outInfo.uid = ps.appId; 10865 } 10866 10867 // Delete package data from internal structures and also remove data if flag is set 10868 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10869 10870 // Delete application code and resources 10871 if (deleteCodeAndResources && (outInfo != null)) { 10872 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10873 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10874 getAppDexInstructionSets(ps)); 10875 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 10876 } 10877 return true; 10878 } 10879 10880 @Override 10881 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10882 int userId) { 10883 mContext.enforceCallingOrSelfPermission( 10884 android.Manifest.permission.DELETE_PACKAGES, null); 10885 synchronized (mPackages) { 10886 PackageSetting ps = mSettings.mPackages.get(packageName); 10887 if (ps == null) { 10888 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10889 return false; 10890 } 10891 if (!ps.getInstalled(userId)) { 10892 // Can't block uninstall for an app that is not installed or enabled. 10893 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10894 return false; 10895 } 10896 ps.setBlockUninstall(blockUninstall, userId); 10897 mSettings.writePackageRestrictionsLPr(userId); 10898 } 10899 return true; 10900 } 10901 10902 @Override 10903 public boolean getBlockUninstallForUser(String packageName, int userId) { 10904 synchronized (mPackages) { 10905 PackageSetting ps = mSettings.mPackages.get(packageName); 10906 if (ps == null) { 10907 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10908 return false; 10909 } 10910 return ps.getBlockUninstall(userId); 10911 } 10912 } 10913 10914 /* 10915 * This method handles package deletion in general 10916 */ 10917 private boolean deletePackageLI(String packageName, UserHandle user, 10918 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10919 int flags, PackageRemovedInfo outInfo, 10920 boolean writeSettings) { 10921 if (packageName == null) { 10922 Slog.w(TAG, "Attempt to delete null packageName."); 10923 return false; 10924 } 10925 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10926 PackageSetting ps; 10927 boolean dataOnly = false; 10928 int removeUser = -1; 10929 int appId = -1; 10930 synchronized (mPackages) { 10931 ps = mSettings.mPackages.get(packageName); 10932 if (ps == null) { 10933 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10934 return false; 10935 } 10936 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10937 && user.getIdentifier() != UserHandle.USER_ALL) { 10938 // The caller is asking that the package only be deleted for a single 10939 // user. To do this, we just mark its uninstalled state and delete 10940 // its data. If this is a system app, we only allow this to happen if 10941 // they have set the special DELETE_SYSTEM_APP which requests different 10942 // semantics than normal for uninstalling system apps. 10943 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10944 ps.setUserState(user.getIdentifier(), 10945 COMPONENT_ENABLED_STATE_DEFAULT, 10946 false, //installed 10947 true, //stopped 10948 true, //notLaunched 10949 false, //hidden 10950 null, null, null, 10951 false // blockUninstall 10952 ); 10953 if (!isSystemApp(ps)) { 10954 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10955 // Other user still have this package installed, so all 10956 // we need to do is clear this user's data and save that 10957 // it is uninstalled. 10958 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10959 removeUser = user.getIdentifier(); 10960 appId = ps.appId; 10961 mSettings.writePackageRestrictionsLPr(removeUser); 10962 } else { 10963 // We need to set it back to 'installed' so the uninstall 10964 // broadcasts will be sent correctly. 10965 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10966 ps.setInstalled(true, user.getIdentifier()); 10967 } 10968 } else { 10969 // This is a system app, so we assume that the 10970 // other users still have this package installed, so all 10971 // we need to do is clear this user's data and save that 10972 // it is uninstalled. 10973 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10974 removeUser = user.getIdentifier(); 10975 appId = ps.appId; 10976 mSettings.writePackageRestrictionsLPr(removeUser); 10977 } 10978 } 10979 } 10980 10981 if (removeUser >= 0) { 10982 // From above, we determined that we are deleting this only 10983 // for a single user. Continue the work here. 10984 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10985 if (outInfo != null) { 10986 outInfo.removedPackage = packageName; 10987 outInfo.removedAppId = appId; 10988 outInfo.removedUsers = new int[] {removeUser}; 10989 } 10990 mInstaller.clearUserData(packageName, removeUser); 10991 removeKeystoreDataIfNeeded(removeUser, appId); 10992 schedulePackageCleaning(packageName, removeUser, false); 10993 return true; 10994 } 10995 10996 if (dataOnly) { 10997 // Delete application data first 10998 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10999 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11000 return true; 11001 } 11002 11003 boolean ret = false; 11004 if (isSystemApp(ps)) { 11005 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11006 // When an updated system application is deleted we delete the existing resources as well and 11007 // fall back to existing code in system partition 11008 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11009 flags, outInfo, writeSettings); 11010 } else { 11011 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11012 // Kill application pre-emptively especially for apps on sd. 11013 killApplication(packageName, ps.appId, "uninstall pkg"); 11014 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11015 allUserHandles, perUserInstalled, 11016 outInfo, writeSettings); 11017 } 11018 11019 return ret; 11020 } 11021 11022 private final class ClearStorageConnection implements ServiceConnection { 11023 IMediaContainerService mContainerService; 11024 11025 @Override 11026 public void onServiceConnected(ComponentName name, IBinder service) { 11027 synchronized (this) { 11028 mContainerService = IMediaContainerService.Stub.asInterface(service); 11029 notifyAll(); 11030 } 11031 } 11032 11033 @Override 11034 public void onServiceDisconnected(ComponentName name) { 11035 } 11036 } 11037 11038 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11039 final boolean mounted; 11040 if (Environment.isExternalStorageEmulated()) { 11041 mounted = true; 11042 } else { 11043 final String status = Environment.getExternalStorageState(); 11044 11045 mounted = status.equals(Environment.MEDIA_MOUNTED) 11046 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11047 } 11048 11049 if (!mounted) { 11050 return; 11051 } 11052 11053 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11054 int[] users; 11055 if (userId == UserHandle.USER_ALL) { 11056 users = sUserManager.getUserIds(); 11057 } else { 11058 users = new int[] { userId }; 11059 } 11060 final ClearStorageConnection conn = new ClearStorageConnection(); 11061 if (mContext.bindServiceAsUser( 11062 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11063 try { 11064 for (int curUser : users) { 11065 long timeout = SystemClock.uptimeMillis() + 5000; 11066 synchronized (conn) { 11067 long now = SystemClock.uptimeMillis(); 11068 while (conn.mContainerService == null && now < timeout) { 11069 try { 11070 conn.wait(timeout - now); 11071 } catch (InterruptedException e) { 11072 } 11073 } 11074 } 11075 if (conn.mContainerService == null) { 11076 return; 11077 } 11078 11079 final UserEnvironment userEnv = new UserEnvironment(curUser); 11080 clearDirectory(conn.mContainerService, 11081 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11082 if (allData) { 11083 clearDirectory(conn.mContainerService, 11084 userEnv.buildExternalStorageAppDataDirs(packageName)); 11085 clearDirectory(conn.mContainerService, 11086 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11087 } 11088 } 11089 } finally { 11090 mContext.unbindService(conn); 11091 } 11092 } 11093 } 11094 11095 @Override 11096 public void clearApplicationUserData(final String packageName, 11097 final IPackageDataObserver observer, final int userId) { 11098 mContext.enforceCallingOrSelfPermission( 11099 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11100 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11101 // Queue up an async operation since the package deletion may take a little while. 11102 mHandler.post(new Runnable() { 11103 public void run() { 11104 mHandler.removeCallbacks(this); 11105 final boolean succeeded; 11106 synchronized (mInstallLock) { 11107 succeeded = clearApplicationUserDataLI(packageName, userId); 11108 } 11109 clearExternalStorageDataSync(packageName, userId, true); 11110 if (succeeded) { 11111 // invoke DeviceStorageMonitor's update method to clear any notifications 11112 DeviceStorageMonitorInternal 11113 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11114 if (dsm != null) { 11115 dsm.checkMemory(); 11116 } 11117 } 11118 if(observer != null) { 11119 try { 11120 observer.onRemoveCompleted(packageName, succeeded); 11121 } catch (RemoteException e) { 11122 Log.i(TAG, "Observer no longer exists."); 11123 } 11124 } //end if observer 11125 } //end run 11126 }); 11127 } 11128 11129 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11130 if (packageName == null) { 11131 Slog.w(TAG, "Attempt to delete null packageName."); 11132 return false; 11133 } 11134 11135 // Try finding details about the requested package 11136 PackageParser.Package pkg; 11137 synchronized (mPackages) { 11138 pkg = mPackages.get(packageName); 11139 if (pkg == null) { 11140 final PackageSetting ps = mSettings.mPackages.get(packageName); 11141 if (ps != null) { 11142 pkg = ps.pkg; 11143 } 11144 } 11145 } 11146 11147 if (pkg == null) { 11148 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11149 } 11150 11151 // Always delete data directories for package, even if we found no other 11152 // record of app. This helps users recover from UID mismatches without 11153 // resorting to a full data wipe. 11154 int retCode = mInstaller.clearUserData(packageName, userId); 11155 if (retCode < 0) { 11156 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 11157 return false; 11158 } 11159 11160 if (pkg == null) { 11161 return false; 11162 } 11163 11164 if (pkg != null && pkg.applicationInfo != null) { 11165 final int appId = pkg.applicationInfo.uid; 11166 removeKeystoreDataIfNeeded(userId, appId); 11167 } 11168 11169 // Create a native library symlink only if we have native libraries 11170 // and if the native libraries are 32 bit libraries. We do not provide 11171 // this symlink for 64 bit libraries. 11172 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11173 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11174 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11175 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11176 Slog.w(TAG, "Failed linking native library dir"); 11177 return false; 11178 } 11179 } 11180 11181 return true; 11182 } 11183 11184 /** 11185 * Remove entries from the keystore daemon. Will only remove it if the 11186 * {@code appId} is valid. 11187 */ 11188 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11189 if (appId < 0) { 11190 return; 11191 } 11192 11193 final KeyStore keyStore = KeyStore.getInstance(); 11194 if (keyStore != null) { 11195 if (userId == UserHandle.USER_ALL) { 11196 for (final int individual : sUserManager.getUserIds()) { 11197 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11198 } 11199 } else { 11200 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11201 } 11202 } else { 11203 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11204 } 11205 } 11206 11207 @Override 11208 public void deleteApplicationCacheFiles(final String packageName, 11209 final IPackageDataObserver observer) { 11210 mContext.enforceCallingOrSelfPermission( 11211 android.Manifest.permission.DELETE_CACHE_FILES, null); 11212 // Queue up an async operation since the package deletion may take a little while. 11213 final int userId = UserHandle.getCallingUserId(); 11214 mHandler.post(new Runnable() { 11215 public void run() { 11216 mHandler.removeCallbacks(this); 11217 final boolean succeded; 11218 synchronized (mInstallLock) { 11219 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11220 } 11221 clearExternalStorageDataSync(packageName, userId, false); 11222 if(observer != null) { 11223 try { 11224 observer.onRemoveCompleted(packageName, succeded); 11225 } catch (RemoteException e) { 11226 Log.i(TAG, "Observer no longer exists."); 11227 } 11228 } //end if observer 11229 } //end run 11230 }); 11231 } 11232 11233 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11234 if (packageName == null) { 11235 Slog.w(TAG, "Attempt to delete null packageName."); 11236 return false; 11237 } 11238 PackageParser.Package p; 11239 synchronized (mPackages) { 11240 p = mPackages.get(packageName); 11241 } 11242 if (p == null) { 11243 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11244 return false; 11245 } 11246 final ApplicationInfo applicationInfo = p.applicationInfo; 11247 if (applicationInfo == null) { 11248 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11249 return false; 11250 } 11251 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11252 if (retCode < 0) { 11253 Slog.w(TAG, "Couldn't remove cache files for package: " 11254 + packageName + " u" + userId); 11255 return false; 11256 } 11257 return true; 11258 } 11259 11260 @Override 11261 public void getPackageSizeInfo(final String packageName, int userHandle, 11262 final IPackageStatsObserver observer) { 11263 mContext.enforceCallingOrSelfPermission( 11264 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11265 if (packageName == null) { 11266 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11267 } 11268 11269 PackageStats stats = new PackageStats(packageName, userHandle); 11270 11271 /* 11272 * Queue up an async operation since the package measurement may take a 11273 * little while. 11274 */ 11275 Message msg = mHandler.obtainMessage(INIT_COPY); 11276 msg.obj = new MeasureParams(stats, observer); 11277 mHandler.sendMessage(msg); 11278 } 11279 11280 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11281 PackageStats pStats) { 11282 if (packageName == null) { 11283 Slog.w(TAG, "Attempt to get size of null packageName."); 11284 return false; 11285 } 11286 PackageParser.Package p; 11287 boolean dataOnly = false; 11288 String libDirRoot = null; 11289 String asecPath = null; 11290 PackageSetting ps = null; 11291 synchronized (mPackages) { 11292 p = mPackages.get(packageName); 11293 ps = mSettings.mPackages.get(packageName); 11294 if(p == null) { 11295 dataOnly = true; 11296 if((ps == null) || (ps.pkg == null)) { 11297 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11298 return false; 11299 } 11300 p = ps.pkg; 11301 } 11302 if (ps != null) { 11303 libDirRoot = ps.legacyNativeLibraryPathString; 11304 } 11305 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11306 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11307 if (secureContainerId != null) { 11308 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11309 } 11310 } 11311 } 11312 String publicSrcDir = null; 11313 if(!dataOnly) { 11314 final ApplicationInfo applicationInfo = p.applicationInfo; 11315 if (applicationInfo == null) { 11316 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11317 return false; 11318 } 11319 if (isForwardLocked(p)) { 11320 publicSrcDir = applicationInfo.getBaseResourcePath(); 11321 } 11322 } 11323 // TODO: extend to measure size of split APKs 11324 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11325 // not just the first level. 11326 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11327 // just the primary. 11328 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11329 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11330 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11331 if (res < 0) { 11332 return false; 11333 } 11334 11335 // Fix-up for forward-locked applications in ASEC containers. 11336 if (!isExternal(p)) { 11337 pStats.codeSize += pStats.externalCodeSize; 11338 pStats.externalCodeSize = 0L; 11339 } 11340 11341 return true; 11342 } 11343 11344 11345 @Override 11346 public void addPackageToPreferred(String packageName) { 11347 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11348 } 11349 11350 @Override 11351 public void removePackageFromPreferred(String packageName) { 11352 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11353 } 11354 11355 @Override 11356 public List<PackageInfo> getPreferredPackages(int flags) { 11357 return new ArrayList<PackageInfo>(); 11358 } 11359 11360 private int getUidTargetSdkVersionLockedLPr(int uid) { 11361 Object obj = mSettings.getUserIdLPr(uid); 11362 if (obj instanceof SharedUserSetting) { 11363 final SharedUserSetting sus = (SharedUserSetting) obj; 11364 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11365 final Iterator<PackageSetting> it = sus.packages.iterator(); 11366 while (it.hasNext()) { 11367 final PackageSetting ps = it.next(); 11368 if (ps.pkg != null) { 11369 int v = ps.pkg.applicationInfo.targetSdkVersion; 11370 if (v < vers) vers = v; 11371 } 11372 } 11373 return vers; 11374 } else if (obj instanceof PackageSetting) { 11375 final PackageSetting ps = (PackageSetting) obj; 11376 if (ps.pkg != null) { 11377 return ps.pkg.applicationInfo.targetSdkVersion; 11378 } 11379 } 11380 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11381 } 11382 11383 @Override 11384 public void addPreferredActivity(IntentFilter filter, int match, 11385 ComponentName[] set, ComponentName activity, int userId) { 11386 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11387 "Adding preferred"); 11388 } 11389 11390 private void addPreferredActivityInternal(IntentFilter filter, int match, 11391 ComponentName[] set, ComponentName activity, boolean always, int userId, 11392 String opname) { 11393 // writer 11394 int callingUid = Binder.getCallingUid(); 11395 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 11396 if (filter.countActions() == 0) { 11397 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11398 return; 11399 } 11400 synchronized (mPackages) { 11401 if (mContext.checkCallingOrSelfPermission( 11402 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11403 != PackageManager.PERMISSION_GRANTED) { 11404 if (getUidTargetSdkVersionLockedLPr(callingUid) 11405 < Build.VERSION_CODES.FROYO) { 11406 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11407 + callingUid); 11408 return; 11409 } 11410 mContext.enforceCallingOrSelfPermission( 11411 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11412 } 11413 11414 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11415 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11416 + userId + ":"); 11417 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11418 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11419 mSettings.writePackageRestrictionsLPr(userId); 11420 } 11421 } 11422 11423 @Override 11424 public void replacePreferredActivity(IntentFilter filter, int match, 11425 ComponentName[] set, ComponentName activity, int userId) { 11426 if (filter.countActions() != 1) { 11427 throw new IllegalArgumentException( 11428 "replacePreferredActivity expects filter to have only 1 action."); 11429 } 11430 if (filter.countDataAuthorities() != 0 11431 || filter.countDataPaths() != 0 11432 || filter.countDataSchemes() > 1 11433 || filter.countDataTypes() != 0) { 11434 throw new IllegalArgumentException( 11435 "replacePreferredActivity expects filter to have no data authorities, " + 11436 "paths, or types; and at most one scheme."); 11437 } 11438 11439 final int callingUid = Binder.getCallingUid(); 11440 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 11441 synchronized (mPackages) { 11442 if (mContext.checkCallingOrSelfPermission( 11443 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11444 != PackageManager.PERMISSION_GRANTED) { 11445 if (getUidTargetSdkVersionLockedLPr(callingUid) 11446 < Build.VERSION_CODES.FROYO) { 11447 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11448 + Binder.getCallingUid()); 11449 return; 11450 } 11451 mContext.enforceCallingOrSelfPermission( 11452 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11453 } 11454 11455 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11456 if (pir != null) { 11457 // Get all of the existing entries that exactly match this filter. 11458 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11459 if (existing != null && existing.size() == 1) { 11460 PreferredActivity cur = existing.get(0); 11461 if (DEBUG_PREFERRED) { 11462 Slog.i(TAG, "Checking replace of preferred:"); 11463 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11464 if (!cur.mPref.mAlways) { 11465 Slog.i(TAG, " -- CUR; not mAlways!"); 11466 } else { 11467 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11468 Slog.i(TAG, " -- CUR: mSet=" 11469 + Arrays.toString(cur.mPref.mSetComponents)); 11470 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11471 Slog.i(TAG, " -- NEW: mMatch=" 11472 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11473 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11474 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11475 } 11476 } 11477 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11478 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11479 && cur.mPref.sameSet(set)) { 11480 // Setting the preferred activity to what it happens to be already 11481 if (DEBUG_PREFERRED) { 11482 Slog.i(TAG, "Replacing with same preferred activity " 11483 + cur.mPref.mShortComponent + " for user " 11484 + userId + ":"); 11485 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11486 } 11487 return; 11488 } 11489 } 11490 11491 if (existing != null) { 11492 if (DEBUG_PREFERRED) { 11493 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11494 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11495 } 11496 for (int i = 0; i < existing.size(); i++) { 11497 PreferredActivity pa = existing.get(i); 11498 if (DEBUG_PREFERRED) { 11499 Slog.i(TAG, "Removing existing preferred activity " 11500 + pa.mPref.mComponent + ":"); 11501 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11502 } 11503 pir.removeFilter(pa); 11504 } 11505 } 11506 } 11507 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11508 "Replacing preferred"); 11509 } 11510 } 11511 11512 @Override 11513 public void clearPackagePreferredActivities(String packageName) { 11514 final int uid = Binder.getCallingUid(); 11515 // writer 11516 synchronized (mPackages) { 11517 PackageParser.Package pkg = mPackages.get(packageName); 11518 if (pkg == null || pkg.applicationInfo.uid != uid) { 11519 if (mContext.checkCallingOrSelfPermission( 11520 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11521 != PackageManager.PERMISSION_GRANTED) { 11522 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11523 < Build.VERSION_CODES.FROYO) { 11524 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11525 + Binder.getCallingUid()); 11526 return; 11527 } 11528 mContext.enforceCallingOrSelfPermission( 11529 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11530 } 11531 } 11532 11533 int user = UserHandle.getCallingUserId(); 11534 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11535 mSettings.writePackageRestrictionsLPr(user); 11536 scheduleWriteSettingsLocked(); 11537 } 11538 } 11539 } 11540 11541 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11542 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11543 ArrayList<PreferredActivity> removed = null; 11544 boolean changed = false; 11545 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11546 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11547 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11548 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11549 continue; 11550 } 11551 Iterator<PreferredActivity> it = pir.filterIterator(); 11552 while (it.hasNext()) { 11553 PreferredActivity pa = it.next(); 11554 // Mark entry for removal only if it matches the package name 11555 // and the entry is of type "always". 11556 if (packageName == null || 11557 (pa.mPref.mComponent.getPackageName().equals(packageName) 11558 && pa.mPref.mAlways)) { 11559 if (removed == null) { 11560 removed = new ArrayList<PreferredActivity>(); 11561 } 11562 removed.add(pa); 11563 } 11564 } 11565 if (removed != null) { 11566 for (int j=0; j<removed.size(); j++) { 11567 PreferredActivity pa = removed.get(j); 11568 pir.removeFilter(pa); 11569 } 11570 changed = true; 11571 } 11572 } 11573 return changed; 11574 } 11575 11576 @Override 11577 public void resetPreferredActivities(int userId) { 11578 /* TODO: Actually use userId. Why is it being passed in? */ 11579 mContext.enforceCallingOrSelfPermission( 11580 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11581 // writer 11582 synchronized (mPackages) { 11583 int user = UserHandle.getCallingUserId(); 11584 clearPackagePreferredActivitiesLPw(null, user); 11585 mSettings.readDefaultPreferredAppsLPw(this, user); 11586 mSettings.writePackageRestrictionsLPr(user); 11587 scheduleWriteSettingsLocked(); 11588 } 11589 } 11590 11591 @Override 11592 public int getPreferredActivities(List<IntentFilter> outFilters, 11593 List<ComponentName> outActivities, String packageName) { 11594 11595 int num = 0; 11596 final int userId = UserHandle.getCallingUserId(); 11597 // reader 11598 synchronized (mPackages) { 11599 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11600 if (pir != null) { 11601 final Iterator<PreferredActivity> it = pir.filterIterator(); 11602 while (it.hasNext()) { 11603 final PreferredActivity pa = it.next(); 11604 if (packageName == null 11605 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11606 && pa.mPref.mAlways)) { 11607 if (outFilters != null) { 11608 outFilters.add(new IntentFilter(pa)); 11609 } 11610 if (outActivities != null) { 11611 outActivities.add(pa.mPref.mComponent); 11612 } 11613 } 11614 } 11615 } 11616 } 11617 11618 return num; 11619 } 11620 11621 @Override 11622 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11623 int userId) { 11624 int callingUid = Binder.getCallingUid(); 11625 if (callingUid != Process.SYSTEM_UID) { 11626 throw new SecurityException( 11627 "addPersistentPreferredActivity can only be run by the system"); 11628 } 11629 if (filter.countActions() == 0) { 11630 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11631 return; 11632 } 11633 synchronized (mPackages) { 11634 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11635 " :"); 11636 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11637 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11638 new PersistentPreferredActivity(filter, activity)); 11639 mSettings.writePackageRestrictionsLPr(userId); 11640 } 11641 } 11642 11643 @Override 11644 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11645 int callingUid = Binder.getCallingUid(); 11646 if (callingUid != Process.SYSTEM_UID) { 11647 throw new SecurityException( 11648 "clearPackagePersistentPreferredActivities can only be run by the system"); 11649 } 11650 ArrayList<PersistentPreferredActivity> removed = null; 11651 boolean changed = false; 11652 synchronized (mPackages) { 11653 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11654 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11655 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11656 .valueAt(i); 11657 if (userId != thisUserId) { 11658 continue; 11659 } 11660 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11661 while (it.hasNext()) { 11662 PersistentPreferredActivity ppa = it.next(); 11663 // Mark entry for removal only if it matches the package name. 11664 if (ppa.mComponent.getPackageName().equals(packageName)) { 11665 if (removed == null) { 11666 removed = new ArrayList<PersistentPreferredActivity>(); 11667 } 11668 removed.add(ppa); 11669 } 11670 } 11671 if (removed != null) { 11672 for (int j=0; j<removed.size(); j++) { 11673 PersistentPreferredActivity ppa = removed.get(j); 11674 ppir.removeFilter(ppa); 11675 } 11676 changed = true; 11677 } 11678 } 11679 11680 if (changed) { 11681 mSettings.writePackageRestrictionsLPr(userId); 11682 } 11683 } 11684 } 11685 11686 @Override 11687 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11688 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11689 mContext.enforceCallingOrSelfPermission( 11690 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11691 int callingUid = Binder.getCallingUid(); 11692 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11693 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11694 if (intentFilter.countActions() == 0) { 11695 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11696 return; 11697 } 11698 synchronized (mPackages) { 11699 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11700 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11701 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11702 mSettings.writePackageRestrictionsLPr(sourceUserId); 11703 } 11704 } 11705 11706 @Override 11707 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11708 int ownerUserId) { 11709 mContext.enforceCallingOrSelfPermission( 11710 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11711 int callingUid = Binder.getCallingUid(); 11712 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11713 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11714 int callingUserId = UserHandle.getUserId(callingUid); 11715 synchronized (mPackages) { 11716 CrossProfileIntentResolver resolver = 11717 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11718 HashSet<CrossProfileIntentFilter> set = 11719 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11720 for (CrossProfileIntentFilter filter : set) { 11721 if (filter.getOwnerPackage().equals(ownerPackage) 11722 && filter.getOwnerUserId() == callingUserId) { 11723 resolver.removeFilter(filter); 11724 } 11725 } 11726 mSettings.writePackageRestrictionsLPr(sourceUserId); 11727 } 11728 } 11729 11730 // Enforcing that callingUid is owning pkg on userId 11731 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11732 // The system owns everything. 11733 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11734 return; 11735 } 11736 int callingUserId = UserHandle.getUserId(callingUid); 11737 if (callingUserId != userId) { 11738 throw new SecurityException("calling uid " + callingUid 11739 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11740 + callingUserId); 11741 } 11742 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11743 if (pi == null) { 11744 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11745 + callingUserId); 11746 } 11747 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11748 throw new SecurityException("Calling uid " + callingUid 11749 + " does not own package " + pkg); 11750 } 11751 } 11752 11753 @Override 11754 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11755 Intent intent = new Intent(Intent.ACTION_MAIN); 11756 intent.addCategory(Intent.CATEGORY_HOME); 11757 11758 final int callingUserId = UserHandle.getCallingUserId(); 11759 List<ResolveInfo> list = queryIntentActivities(intent, null, 11760 PackageManager.GET_META_DATA, callingUserId); 11761 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11762 true, false, false, callingUserId); 11763 11764 allHomeCandidates.clear(); 11765 if (list != null) { 11766 for (ResolveInfo ri : list) { 11767 allHomeCandidates.add(ri); 11768 } 11769 } 11770 return (preferred == null || preferred.activityInfo == null) 11771 ? null 11772 : new ComponentName(preferred.activityInfo.packageName, 11773 preferred.activityInfo.name); 11774 } 11775 11776 @Override 11777 public void setApplicationEnabledSetting(String appPackageName, 11778 int newState, int flags, int userId, String callingPackage) { 11779 if (!sUserManager.exists(userId)) return; 11780 if (callingPackage == null) { 11781 callingPackage = Integer.toString(Binder.getCallingUid()); 11782 } 11783 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11784 } 11785 11786 @Override 11787 public void setComponentEnabledSetting(ComponentName componentName, 11788 int newState, int flags, int userId) { 11789 if (!sUserManager.exists(userId)) return; 11790 setEnabledSetting(componentName.getPackageName(), 11791 componentName.getClassName(), newState, flags, userId, null); 11792 } 11793 11794 private void setEnabledSetting(final String packageName, String className, int newState, 11795 final int flags, int userId, String callingPackage) { 11796 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11797 || newState == COMPONENT_ENABLED_STATE_ENABLED 11798 || newState == COMPONENT_ENABLED_STATE_DISABLED 11799 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11800 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11801 throw new IllegalArgumentException("Invalid new component state: " 11802 + newState); 11803 } 11804 PackageSetting pkgSetting; 11805 final int uid = Binder.getCallingUid(); 11806 final int permission = mContext.checkCallingOrSelfPermission( 11807 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11808 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 11809 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11810 boolean sendNow = false; 11811 boolean isApp = (className == null); 11812 String componentName = isApp ? packageName : className; 11813 int packageUid = -1; 11814 ArrayList<String> components; 11815 11816 // writer 11817 synchronized (mPackages) { 11818 pkgSetting = mSettings.mPackages.get(packageName); 11819 if (pkgSetting == null) { 11820 if (className == null) { 11821 throw new IllegalArgumentException( 11822 "Unknown package: " + packageName); 11823 } 11824 throw new IllegalArgumentException( 11825 "Unknown component: " + packageName 11826 + "/" + className); 11827 } 11828 // Allow root and verify that userId is not being specified by a different user 11829 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11830 throw new SecurityException( 11831 "Permission Denial: attempt to change component state from pid=" 11832 + Binder.getCallingPid() 11833 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11834 } 11835 if (className == null) { 11836 // We're dealing with an application/package level state change 11837 if (pkgSetting.getEnabled(userId) == newState) { 11838 // Nothing to do 11839 return; 11840 } 11841 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11842 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11843 // Don't care about who enables an app. 11844 callingPackage = null; 11845 } 11846 pkgSetting.setEnabled(newState, userId, callingPackage); 11847 // pkgSetting.pkg.mSetEnabled = newState; 11848 } else { 11849 // We're dealing with a component level state change 11850 // First, verify that this is a valid class name. 11851 PackageParser.Package pkg = pkgSetting.pkg; 11852 if (pkg == null || !pkg.hasComponentClassName(className)) { 11853 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11854 throw new IllegalArgumentException("Component class " + className 11855 + " does not exist in " + packageName); 11856 } else { 11857 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11858 + className + " does not exist in " + packageName); 11859 } 11860 } 11861 switch (newState) { 11862 case COMPONENT_ENABLED_STATE_ENABLED: 11863 if (!pkgSetting.enableComponentLPw(className, userId)) { 11864 return; 11865 } 11866 break; 11867 case COMPONENT_ENABLED_STATE_DISABLED: 11868 if (!pkgSetting.disableComponentLPw(className, userId)) { 11869 return; 11870 } 11871 break; 11872 case COMPONENT_ENABLED_STATE_DEFAULT: 11873 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11874 return; 11875 } 11876 break; 11877 default: 11878 Slog.e(TAG, "Invalid new component state: " + newState); 11879 return; 11880 } 11881 } 11882 mSettings.writePackageRestrictionsLPr(userId); 11883 components = mPendingBroadcasts.get(userId, packageName); 11884 final boolean newPackage = components == null; 11885 if (newPackage) { 11886 components = new ArrayList<String>(); 11887 } 11888 if (!components.contains(componentName)) { 11889 components.add(componentName); 11890 } 11891 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11892 sendNow = true; 11893 // Purge entry from pending broadcast list if another one exists already 11894 // since we are sending one right away. 11895 mPendingBroadcasts.remove(userId, packageName); 11896 } else { 11897 if (newPackage) { 11898 mPendingBroadcasts.put(userId, packageName, components); 11899 } 11900 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11901 // Schedule a message 11902 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11903 } 11904 } 11905 } 11906 11907 long callingId = Binder.clearCallingIdentity(); 11908 try { 11909 if (sendNow) { 11910 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11911 sendPackageChangedBroadcast(packageName, 11912 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11913 } 11914 } finally { 11915 Binder.restoreCallingIdentity(callingId); 11916 } 11917 } 11918 11919 private void sendPackageChangedBroadcast(String packageName, 11920 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11921 if (DEBUG_INSTALL) 11922 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11923 + componentNames); 11924 Bundle extras = new Bundle(4); 11925 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11926 String nameList[] = new String[componentNames.size()]; 11927 componentNames.toArray(nameList); 11928 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11929 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11930 extras.putInt(Intent.EXTRA_UID, packageUid); 11931 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11932 new int[] {UserHandle.getUserId(packageUid)}); 11933 } 11934 11935 @Override 11936 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11937 if (!sUserManager.exists(userId)) return; 11938 final int uid = Binder.getCallingUid(); 11939 final int permission = mContext.checkCallingOrSelfPermission( 11940 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11941 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11942 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 11943 // writer 11944 synchronized (mPackages) { 11945 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11946 uid, userId)) { 11947 scheduleWritePackageRestrictionsLocked(userId); 11948 } 11949 } 11950 } 11951 11952 @Override 11953 public String getInstallerPackageName(String packageName) { 11954 // reader 11955 synchronized (mPackages) { 11956 return mSettings.getInstallerPackageNameLPr(packageName); 11957 } 11958 } 11959 11960 @Override 11961 public int getApplicationEnabledSetting(String packageName, int userId) { 11962 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11963 int uid = Binder.getCallingUid(); 11964 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 11965 // reader 11966 synchronized (mPackages) { 11967 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11968 } 11969 } 11970 11971 @Override 11972 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11973 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11974 int uid = Binder.getCallingUid(); 11975 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 11976 // reader 11977 synchronized (mPackages) { 11978 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11979 } 11980 } 11981 11982 @Override 11983 public void enterSafeMode() { 11984 enforceSystemOrRoot("Only the system can request entering safe mode"); 11985 11986 if (!mSystemReady) { 11987 mSafeMode = true; 11988 } 11989 } 11990 11991 @Override 11992 public void systemReady() { 11993 mSystemReady = true; 11994 11995 // Read the compatibilty setting when the system is ready. 11996 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11997 mContext.getContentResolver(), 11998 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11999 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12000 if (DEBUG_SETTINGS) { 12001 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12002 } 12003 12004 synchronized (mPackages) { 12005 // Verify that all of the preferred activity components actually 12006 // exist. It is possible for applications to be updated and at 12007 // that point remove a previously declared activity component that 12008 // had been set as a preferred activity. We try to clean this up 12009 // the next time we encounter that preferred activity, but it is 12010 // possible for the user flow to never be able to return to that 12011 // situation so here we do a sanity check to make sure we haven't 12012 // left any junk around. 12013 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12014 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12015 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12016 removed.clear(); 12017 for (PreferredActivity pa : pir.filterSet()) { 12018 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12019 removed.add(pa); 12020 } 12021 } 12022 if (removed.size() > 0) { 12023 for (int r=0; r<removed.size(); r++) { 12024 PreferredActivity pa = removed.get(r); 12025 Slog.w(TAG, "Removing dangling preferred activity: " 12026 + pa.mPref.mComponent); 12027 pir.removeFilter(pa); 12028 } 12029 mSettings.writePackageRestrictionsLPr( 12030 mSettings.mPreferredActivities.keyAt(i)); 12031 } 12032 } 12033 } 12034 sUserManager.systemReady(); 12035 12036 // Kick off any messages waiting for system ready 12037 if (mPostSystemReadyMessages != null) { 12038 for (Message msg : mPostSystemReadyMessages) { 12039 msg.sendToTarget(); 12040 } 12041 mPostSystemReadyMessages = null; 12042 } 12043 } 12044 12045 @Override 12046 public boolean isSafeMode() { 12047 return mSafeMode; 12048 } 12049 12050 @Override 12051 public boolean hasSystemUidErrors() { 12052 return mHasSystemUidErrors; 12053 } 12054 12055 static String arrayToString(int[] array) { 12056 StringBuffer buf = new StringBuffer(128); 12057 buf.append('['); 12058 if (array != null) { 12059 for (int i=0; i<array.length; i++) { 12060 if (i > 0) buf.append(", "); 12061 buf.append(array[i]); 12062 } 12063 } 12064 buf.append(']'); 12065 return buf.toString(); 12066 } 12067 12068 static class DumpState { 12069 public static final int DUMP_LIBS = 1 << 0; 12070 public static final int DUMP_FEATURES = 1 << 1; 12071 public static final int DUMP_RESOLVERS = 1 << 2; 12072 public static final int DUMP_PERMISSIONS = 1 << 3; 12073 public static final int DUMP_PACKAGES = 1 << 4; 12074 public static final int DUMP_SHARED_USERS = 1 << 5; 12075 public static final int DUMP_MESSAGES = 1 << 6; 12076 public static final int DUMP_PROVIDERS = 1 << 7; 12077 public static final int DUMP_VERIFIERS = 1 << 8; 12078 public static final int DUMP_PREFERRED = 1 << 9; 12079 public static final int DUMP_PREFERRED_XML = 1 << 10; 12080 public static final int DUMP_KEYSETS = 1 << 11; 12081 public static final int DUMP_VERSION = 1 << 12; 12082 public static final int DUMP_INSTALLS = 1 << 13; 12083 12084 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12085 12086 private int mTypes; 12087 12088 private int mOptions; 12089 12090 private boolean mTitlePrinted; 12091 12092 private SharedUserSetting mSharedUser; 12093 12094 public boolean isDumping(int type) { 12095 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12096 return true; 12097 } 12098 12099 return (mTypes & type) != 0; 12100 } 12101 12102 public void setDump(int type) { 12103 mTypes |= type; 12104 } 12105 12106 public boolean isOptionEnabled(int option) { 12107 return (mOptions & option) != 0; 12108 } 12109 12110 public void setOptionEnabled(int option) { 12111 mOptions |= option; 12112 } 12113 12114 public boolean onTitlePrinted() { 12115 final boolean printed = mTitlePrinted; 12116 mTitlePrinted = true; 12117 return printed; 12118 } 12119 12120 public boolean getTitlePrinted() { 12121 return mTitlePrinted; 12122 } 12123 12124 public void setTitlePrinted(boolean enabled) { 12125 mTitlePrinted = enabled; 12126 } 12127 12128 public SharedUserSetting getSharedUser() { 12129 return mSharedUser; 12130 } 12131 12132 public void setSharedUser(SharedUserSetting user) { 12133 mSharedUser = user; 12134 } 12135 } 12136 12137 @Override 12138 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12139 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12140 != PackageManager.PERMISSION_GRANTED) { 12141 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12142 + Binder.getCallingPid() 12143 + ", uid=" + Binder.getCallingUid() 12144 + " without permission " 12145 + android.Manifest.permission.DUMP); 12146 return; 12147 } 12148 12149 DumpState dumpState = new DumpState(); 12150 boolean fullPreferred = false; 12151 boolean checkin = false; 12152 12153 String packageName = null; 12154 12155 int opti = 0; 12156 while (opti < args.length) { 12157 String opt = args[opti]; 12158 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12159 break; 12160 } 12161 opti++; 12162 if ("-a".equals(opt)) { 12163 // Right now we only know how to print all. 12164 } else if ("-h".equals(opt)) { 12165 pw.println("Package manager dump options:"); 12166 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12167 pw.println(" --checkin: dump for a checkin"); 12168 pw.println(" -f: print details of intent filters"); 12169 pw.println(" -h: print this help"); 12170 pw.println(" cmd may be one of:"); 12171 pw.println(" l[ibraries]: list known shared libraries"); 12172 pw.println(" f[ibraries]: list device features"); 12173 pw.println(" k[eysets]: print known keysets"); 12174 pw.println(" r[esolvers]: dump intent resolvers"); 12175 pw.println(" perm[issions]: dump permissions"); 12176 pw.println(" pref[erred]: print preferred package settings"); 12177 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12178 pw.println(" prov[iders]: dump content providers"); 12179 pw.println(" p[ackages]: dump installed packages"); 12180 pw.println(" s[hared-users]: dump shared user IDs"); 12181 pw.println(" m[essages]: print collected runtime messages"); 12182 pw.println(" v[erifiers]: print package verifier info"); 12183 pw.println(" version: print database version info"); 12184 pw.println(" write: write current settings now"); 12185 pw.println(" <package.name>: info about given package"); 12186 pw.println(" installs: details about install sessions"); 12187 return; 12188 } else if ("--checkin".equals(opt)) { 12189 checkin = true; 12190 } else if ("-f".equals(opt)) { 12191 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12192 } else { 12193 pw.println("Unknown argument: " + opt + "; use -h for help"); 12194 } 12195 } 12196 12197 // Is the caller requesting to dump a particular piece of data? 12198 if (opti < args.length) { 12199 String cmd = args[opti]; 12200 opti++; 12201 // Is this a package name? 12202 if ("android".equals(cmd) || cmd.contains(".")) { 12203 packageName = cmd; 12204 // When dumping a single package, we always dump all of its 12205 // filter information since the amount of data will be reasonable. 12206 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12207 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12208 dumpState.setDump(DumpState.DUMP_LIBS); 12209 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12210 dumpState.setDump(DumpState.DUMP_FEATURES); 12211 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12212 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12213 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12214 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12215 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12216 dumpState.setDump(DumpState.DUMP_PREFERRED); 12217 } else if ("preferred-xml".equals(cmd)) { 12218 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12219 if (opti < args.length && "--full".equals(args[opti])) { 12220 fullPreferred = true; 12221 opti++; 12222 } 12223 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12224 dumpState.setDump(DumpState.DUMP_PACKAGES); 12225 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12226 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12227 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12228 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12229 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12230 dumpState.setDump(DumpState.DUMP_MESSAGES); 12231 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12232 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12233 } else if ("version".equals(cmd)) { 12234 dumpState.setDump(DumpState.DUMP_VERSION); 12235 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12236 dumpState.setDump(DumpState.DUMP_KEYSETS); 12237 } else if ("installs".equals(cmd)) { 12238 dumpState.setDump(DumpState.DUMP_INSTALLS); 12239 } else if ("write".equals(cmd)) { 12240 synchronized (mPackages) { 12241 mSettings.writeLPr(); 12242 pw.println("Settings written."); 12243 return; 12244 } 12245 } 12246 } 12247 12248 if (checkin) { 12249 pw.println("vers,1"); 12250 } 12251 12252 // reader 12253 synchronized (mPackages) { 12254 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12255 if (!checkin) { 12256 if (dumpState.onTitlePrinted()) 12257 pw.println(); 12258 pw.println("Database versions:"); 12259 pw.print(" SDK Version:"); 12260 pw.print(" internal="); 12261 pw.print(mSettings.mInternalSdkPlatform); 12262 pw.print(" external="); 12263 pw.println(mSettings.mExternalSdkPlatform); 12264 pw.print(" DB Version:"); 12265 pw.print(" internal="); 12266 pw.print(mSettings.mInternalDatabaseVersion); 12267 pw.print(" external="); 12268 pw.println(mSettings.mExternalDatabaseVersion); 12269 } 12270 } 12271 12272 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12273 if (!checkin) { 12274 if (dumpState.onTitlePrinted()) 12275 pw.println(); 12276 pw.println("Verifiers:"); 12277 pw.print(" Required: "); 12278 pw.print(mRequiredVerifierPackage); 12279 pw.print(" (uid="); 12280 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12281 pw.println(")"); 12282 } else if (mRequiredVerifierPackage != null) { 12283 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12284 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12285 } 12286 } 12287 12288 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12289 boolean printedHeader = false; 12290 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12291 while (it.hasNext()) { 12292 String name = it.next(); 12293 SharedLibraryEntry ent = mSharedLibraries.get(name); 12294 if (!checkin) { 12295 if (!printedHeader) { 12296 if (dumpState.onTitlePrinted()) 12297 pw.println(); 12298 pw.println("Libraries:"); 12299 printedHeader = true; 12300 } 12301 pw.print(" "); 12302 } else { 12303 pw.print("lib,"); 12304 } 12305 pw.print(name); 12306 if (!checkin) { 12307 pw.print(" -> "); 12308 } 12309 if (ent.path != null) { 12310 if (!checkin) { 12311 pw.print("(jar) "); 12312 pw.print(ent.path); 12313 } else { 12314 pw.print(",jar,"); 12315 pw.print(ent.path); 12316 } 12317 } else { 12318 if (!checkin) { 12319 pw.print("(apk) "); 12320 pw.print(ent.apk); 12321 } else { 12322 pw.print(",apk,"); 12323 pw.print(ent.apk); 12324 } 12325 } 12326 pw.println(); 12327 } 12328 } 12329 12330 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12331 if (dumpState.onTitlePrinted()) 12332 pw.println(); 12333 if (!checkin) { 12334 pw.println("Features:"); 12335 } 12336 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12337 while (it.hasNext()) { 12338 String name = it.next(); 12339 if (!checkin) { 12340 pw.print(" "); 12341 } else { 12342 pw.print("feat,"); 12343 } 12344 pw.println(name); 12345 } 12346 } 12347 12348 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12349 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12350 : "Activity Resolver Table:", " ", packageName, 12351 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12352 dumpState.setTitlePrinted(true); 12353 } 12354 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12355 : "Receiver Resolver Table:", " ", packageName, 12356 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12357 dumpState.setTitlePrinted(true); 12358 } 12359 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12360 : "Service Resolver Table:", " ", packageName, 12361 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12362 dumpState.setTitlePrinted(true); 12363 } 12364 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12365 : "Provider Resolver Table:", " ", packageName, 12366 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12367 dumpState.setTitlePrinted(true); 12368 } 12369 } 12370 12371 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12372 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12373 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12374 int user = mSettings.mPreferredActivities.keyAt(i); 12375 if (pir.dump(pw, 12376 dumpState.getTitlePrinted() 12377 ? "\nPreferred Activities User " + user + ":" 12378 : "Preferred Activities User " + user + ":", " ", 12379 packageName, true)) { 12380 dumpState.setTitlePrinted(true); 12381 } 12382 } 12383 } 12384 12385 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12386 pw.flush(); 12387 FileOutputStream fout = new FileOutputStream(fd); 12388 BufferedOutputStream str = new BufferedOutputStream(fout); 12389 XmlSerializer serializer = new FastXmlSerializer(); 12390 try { 12391 serializer.setOutput(str, "utf-8"); 12392 serializer.startDocument(null, true); 12393 serializer.setFeature( 12394 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12395 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12396 serializer.endDocument(); 12397 serializer.flush(); 12398 } catch (IllegalArgumentException e) { 12399 pw.println("Failed writing: " + e); 12400 } catch (IllegalStateException e) { 12401 pw.println("Failed writing: " + e); 12402 } catch (IOException e) { 12403 pw.println("Failed writing: " + e); 12404 } 12405 } 12406 12407 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12408 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12409 if (packageName == null) { 12410 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12411 if (iperm == 0) { 12412 if (dumpState.onTitlePrinted()) 12413 pw.println(); 12414 pw.println("AppOp Permissions:"); 12415 } 12416 pw.print(" AppOp Permission "); 12417 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12418 pw.println(":"); 12419 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12420 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12421 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12422 } 12423 } 12424 } 12425 } 12426 12427 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12428 boolean printedSomething = false; 12429 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12430 if (packageName != null && !packageName.equals(p.info.packageName)) { 12431 continue; 12432 } 12433 if (!printedSomething) { 12434 if (dumpState.onTitlePrinted()) 12435 pw.println(); 12436 pw.println("Registered ContentProviders:"); 12437 printedSomething = true; 12438 } 12439 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12440 pw.print(" "); pw.println(p.toString()); 12441 } 12442 printedSomething = false; 12443 for (Map.Entry<String, PackageParser.Provider> entry : 12444 mProvidersByAuthority.entrySet()) { 12445 PackageParser.Provider p = entry.getValue(); 12446 if (packageName != null && !packageName.equals(p.info.packageName)) { 12447 continue; 12448 } 12449 if (!printedSomething) { 12450 if (dumpState.onTitlePrinted()) 12451 pw.println(); 12452 pw.println("ContentProvider Authorities:"); 12453 printedSomething = true; 12454 } 12455 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12456 pw.print(" "); pw.println(p.toString()); 12457 if (p.info != null && p.info.applicationInfo != null) { 12458 final String appInfo = p.info.applicationInfo.toString(); 12459 pw.print(" applicationInfo="); pw.println(appInfo); 12460 } 12461 } 12462 } 12463 12464 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12465 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12466 } 12467 12468 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12469 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12470 } 12471 12472 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12473 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12474 } 12475 12476 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 12477 // XXX should handle packageName != null by dumping only install data that 12478 // the given package is involved with. 12479 if (dumpState.onTitlePrinted()) pw.println(); 12480 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12481 } 12482 12483 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12484 if (dumpState.onTitlePrinted()) pw.println(); 12485 mSettings.dumpReadMessagesLPr(pw, dumpState); 12486 12487 pw.println(); 12488 pw.println("Package warning messages:"); 12489 final File fname = getSettingsProblemFile(); 12490 FileInputStream in = null; 12491 try { 12492 in = new FileInputStream(fname); 12493 final int avail = in.available(); 12494 final byte[] data = new byte[avail]; 12495 in.read(data); 12496 pw.print(new String(data)); 12497 } catch (FileNotFoundException e) { 12498 } catch (IOException e) { 12499 } finally { 12500 if (in != null) { 12501 try { 12502 in.close(); 12503 } catch (IOException e) { 12504 } 12505 } 12506 } 12507 } 12508 } 12509 } 12510 12511 // ------- apps on sdcard specific code ------- 12512 static final boolean DEBUG_SD_INSTALL = false; 12513 12514 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12515 12516 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12517 12518 private boolean mMediaMounted = false; 12519 12520 static String getEncryptKey() { 12521 try { 12522 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12523 SD_ENCRYPTION_KEYSTORE_NAME); 12524 if (sdEncKey == null) { 12525 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12526 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12527 if (sdEncKey == null) { 12528 Slog.e(TAG, "Failed to create encryption keys"); 12529 return null; 12530 } 12531 } 12532 return sdEncKey; 12533 } catch (NoSuchAlgorithmException nsae) { 12534 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12535 return null; 12536 } catch (IOException ioe) { 12537 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12538 return null; 12539 } 12540 } 12541 12542 /* 12543 * Update media status on PackageManager. 12544 */ 12545 @Override 12546 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12547 int callingUid = Binder.getCallingUid(); 12548 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12549 throw new SecurityException("Media status can only be updated by the system"); 12550 } 12551 // reader; this apparently protects mMediaMounted, but should probably 12552 // be a different lock in that case. 12553 synchronized (mPackages) { 12554 Log.i(TAG, "Updating external media status from " 12555 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12556 + (mediaStatus ? "mounted" : "unmounted")); 12557 if (DEBUG_SD_INSTALL) 12558 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12559 + ", mMediaMounted=" + mMediaMounted); 12560 if (mediaStatus == mMediaMounted) { 12561 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12562 : 0, -1); 12563 mHandler.sendMessage(msg); 12564 return; 12565 } 12566 mMediaMounted = mediaStatus; 12567 } 12568 // Queue up an async operation since the package installation may take a 12569 // little while. 12570 mHandler.post(new Runnable() { 12571 public void run() { 12572 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12573 } 12574 }); 12575 } 12576 12577 /** 12578 * Called by MountService when the initial ASECs to scan are available. 12579 * Should block until all the ASEC containers are finished being scanned. 12580 */ 12581 public void scanAvailableAsecs() { 12582 updateExternalMediaStatusInner(true, false, false); 12583 if (mShouldRestoreconData) { 12584 SELinuxMMAC.setRestoreconDone(); 12585 mShouldRestoreconData = false; 12586 } 12587 } 12588 12589 /* 12590 * Collect information of applications on external media, map them against 12591 * existing containers and update information based on current mount status. 12592 * Please note that we always have to report status if reportStatus has been 12593 * set to true especially when unloading packages. 12594 */ 12595 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12596 boolean externalStorage) { 12597 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12598 int[] uidArr = EmptyArray.INT; 12599 12600 final String[] list = PackageHelper.getSecureContainerList(); 12601 if (ArrayUtils.isEmpty(list)) { 12602 Log.i(TAG, "No secure containers found"); 12603 } else { 12604 // Process list of secure containers and categorize them 12605 // as active or stale based on their package internal state. 12606 12607 // reader 12608 synchronized (mPackages) { 12609 for (String cid : list) { 12610 // Leave stages untouched for now; installer service owns them 12611 if (PackageInstallerService.isStageName(cid)) continue; 12612 12613 if (DEBUG_SD_INSTALL) 12614 Log.i(TAG, "Processing container " + cid); 12615 String pkgName = getAsecPackageName(cid); 12616 if (pkgName == null) { 12617 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12618 continue; 12619 } 12620 if (DEBUG_SD_INSTALL) 12621 Log.i(TAG, "Looking for pkg : " + pkgName); 12622 12623 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12624 if (ps == null) { 12625 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12626 continue; 12627 } 12628 12629 /* 12630 * Skip packages that are not external if we're unmounting 12631 * external storage. 12632 */ 12633 if (externalStorage && !isMounted && !isExternal(ps)) { 12634 continue; 12635 } 12636 12637 final AsecInstallArgs args = new AsecInstallArgs(cid, 12638 getAppDexInstructionSets(ps), isForwardLocked(ps)); 12639 // The package status is changed only if the code path 12640 // matches between settings and the container id. 12641 if (ps.codePathString != null 12642 && ps.codePathString.startsWith(args.getCodePath())) { 12643 if (DEBUG_SD_INSTALL) { 12644 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12645 + " at code path: " + ps.codePathString); 12646 } 12647 12648 // We do have a valid package installed on sdcard 12649 processCids.put(args, ps.codePathString); 12650 final int uid = ps.appId; 12651 if (uid != -1) { 12652 uidArr = ArrayUtils.appendInt(uidArr, uid); 12653 } 12654 } else { 12655 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12656 + ps.codePathString); 12657 } 12658 } 12659 } 12660 12661 Arrays.sort(uidArr); 12662 } 12663 12664 // Process packages with valid entries. 12665 if (isMounted) { 12666 if (DEBUG_SD_INSTALL) 12667 Log.i(TAG, "Loading packages"); 12668 loadMediaPackages(processCids, uidArr); 12669 startCleaningPackages(); 12670 mInstallerService.onSecureContainersAvailable(); 12671 } else { 12672 if (DEBUG_SD_INSTALL) 12673 Log.i(TAG, "Unloading packages"); 12674 unloadMediaPackages(processCids, uidArr, reportStatus); 12675 } 12676 } 12677 12678 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12679 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12680 int size = pkgList.size(); 12681 if (size > 0) { 12682 // Send broadcasts here 12683 Bundle extras = new Bundle(); 12684 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12685 .toArray(new String[size])); 12686 if (uidArr != null) { 12687 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12688 } 12689 if (replacing) { 12690 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12691 } 12692 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12693 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12694 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12695 } 12696 } 12697 12698 /* 12699 * Look at potentially valid container ids from processCids If package 12700 * information doesn't match the one on record or package scanning fails, 12701 * the cid is added to list of removeCids. We currently don't delete stale 12702 * containers. 12703 */ 12704 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12705 ArrayList<String> pkgList = new ArrayList<String>(); 12706 Set<AsecInstallArgs> keys = processCids.keySet(); 12707 12708 for (AsecInstallArgs args : keys) { 12709 String codePath = processCids.get(args); 12710 if (DEBUG_SD_INSTALL) 12711 Log.i(TAG, "Loading container : " + args.cid); 12712 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12713 try { 12714 // Make sure there are no container errors first. 12715 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12716 Slog.e(TAG, "Failed to mount cid : " + args.cid 12717 + " when installing from sdcard"); 12718 continue; 12719 } 12720 // Check code path here. 12721 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12722 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12723 + " does not match one in settings " + codePath); 12724 continue; 12725 } 12726 // Parse package 12727 int parseFlags = mDefParseFlags; 12728 if (args.isExternal()) { 12729 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12730 } 12731 if (args.isFwdLocked()) { 12732 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12733 } 12734 12735 synchronized (mInstallLock) { 12736 PackageParser.Package pkg = null; 12737 try { 12738 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12739 } catch (PackageManagerException e) { 12740 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12741 } 12742 // Scan the package 12743 if (pkg != null) { 12744 /* 12745 * TODO why is the lock being held? doPostInstall is 12746 * called in other places without the lock. This needs 12747 * to be straightened out. 12748 */ 12749 // writer 12750 synchronized (mPackages) { 12751 retCode = PackageManager.INSTALL_SUCCEEDED; 12752 pkgList.add(pkg.packageName); 12753 // Post process args 12754 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12755 pkg.applicationInfo.uid); 12756 } 12757 } else { 12758 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12759 } 12760 } 12761 12762 } finally { 12763 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12764 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12765 } 12766 } 12767 } 12768 // writer 12769 synchronized (mPackages) { 12770 // If the platform SDK has changed since the last time we booted, 12771 // we need to re-grant app permission to catch any new ones that 12772 // appear. This is really a hack, and means that apps can in some 12773 // cases get permissions that the user didn't initially explicitly 12774 // allow... it would be nice to have some better way to handle 12775 // this situation. 12776 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12777 if (regrantPermissions) 12778 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12779 + mSdkVersion + "; regranting permissions for external storage"); 12780 mSettings.mExternalSdkPlatform = mSdkVersion; 12781 12782 // Make sure group IDs have been assigned, and any permission 12783 // changes in other apps are accounted for 12784 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12785 | (regrantPermissions 12786 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12787 : 0)); 12788 12789 mSettings.updateExternalDatabaseVersion(); 12790 12791 // can downgrade to reader 12792 // Persist settings 12793 mSettings.writeLPr(); 12794 } 12795 // Send a broadcast to let everyone know we are done processing 12796 if (pkgList.size() > 0) { 12797 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12798 } 12799 } 12800 12801 /* 12802 * Utility method to unload a list of specified containers 12803 */ 12804 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12805 // Just unmount all valid containers. 12806 for (AsecInstallArgs arg : cidArgs) { 12807 synchronized (mInstallLock) { 12808 arg.doPostDeleteLI(false); 12809 } 12810 } 12811 } 12812 12813 /* 12814 * Unload packages mounted on external media. This involves deleting package 12815 * data from internal structures, sending broadcasts about diabled packages, 12816 * gc'ing to free up references, unmounting all secure containers 12817 * corresponding to packages on external media, and posting a 12818 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12819 * that we always have to post this message if status has been requested no 12820 * matter what. 12821 */ 12822 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 12823 final boolean reportStatus) { 12824 if (DEBUG_SD_INSTALL) 12825 Log.i(TAG, "unloading media packages"); 12826 ArrayList<String> pkgList = new ArrayList<String>(); 12827 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12828 final Set<AsecInstallArgs> keys = processCids.keySet(); 12829 for (AsecInstallArgs args : keys) { 12830 String pkgName = args.getPackageName(); 12831 if (DEBUG_SD_INSTALL) 12832 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12833 // Delete package internally 12834 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12835 synchronized (mInstallLock) { 12836 boolean res = deletePackageLI(pkgName, null, false, null, null, 12837 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12838 if (res) { 12839 pkgList.add(pkgName); 12840 } else { 12841 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12842 failedList.add(args); 12843 } 12844 } 12845 } 12846 12847 // reader 12848 synchronized (mPackages) { 12849 // We didn't update the settings after removing each package; 12850 // write them now for all packages. 12851 mSettings.writeLPr(); 12852 } 12853 12854 // We have to absolutely send UPDATED_MEDIA_STATUS only 12855 // after confirming that all the receivers processed the ordered 12856 // broadcast when packages get disabled, force a gc to clean things up. 12857 // and unload all the containers. 12858 if (pkgList.size() > 0) { 12859 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12860 new IIntentReceiver.Stub() { 12861 public void performReceive(Intent intent, int resultCode, String data, 12862 Bundle extras, boolean ordered, boolean sticky, 12863 int sendingUser) throws RemoteException { 12864 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12865 reportStatus ? 1 : 0, 1, keys); 12866 mHandler.sendMessage(msg); 12867 } 12868 }); 12869 } else { 12870 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12871 keys); 12872 mHandler.sendMessage(msg); 12873 } 12874 } 12875 12876 /** Binder call */ 12877 @Override 12878 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12879 final int flags) { 12880 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12881 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12882 int returnCode = PackageManager.MOVE_SUCCEEDED; 12883 int currInstallFlags = 0; 12884 int newInstallFlags = 0; 12885 12886 File codeFile = null; 12887 String installerPackageName = null; 12888 String packageAbiOverride = null; 12889 12890 // reader 12891 synchronized (mPackages) { 12892 final PackageParser.Package pkg = mPackages.get(packageName); 12893 final PackageSetting ps = mSettings.mPackages.get(packageName); 12894 if (pkg == null || ps == null) { 12895 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12896 } else { 12897 // Disable moving fwd locked apps and system packages 12898 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12899 Slog.w(TAG, "Cannot move system application"); 12900 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12901 } else if (pkg.mOperationPending) { 12902 Slog.w(TAG, "Attempt to move package which has pending operations"); 12903 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12904 } else { 12905 // Find install location first 12906 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12907 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12908 Slog.w(TAG, "Ambigous flags specified for move location."); 12909 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12910 } else { 12911 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12912 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12913 currInstallFlags = isExternal(pkg) 12914 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12915 12916 if (newInstallFlags == currInstallFlags) { 12917 Slog.w(TAG, "No move required. Trying to move to same location"); 12918 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12919 } else { 12920 if (isForwardLocked(pkg)) { 12921 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12922 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12923 } 12924 } 12925 } 12926 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12927 pkg.mOperationPending = true; 12928 } 12929 } 12930 12931 codeFile = new File(pkg.codePath); 12932 installerPackageName = ps.installerPackageName; 12933 packageAbiOverride = ps.cpuAbiOverrideString; 12934 } 12935 } 12936 12937 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12938 try { 12939 observer.packageMoved(packageName, returnCode); 12940 } catch (RemoteException ignored) { 12941 } 12942 return; 12943 } 12944 12945 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 12946 @Override 12947 public void onUserActionRequired(Intent intent) throws RemoteException { 12948 throw new IllegalStateException(); 12949 } 12950 12951 @Override 12952 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 12953 Bundle extras) throws RemoteException { 12954 Slog.d(TAG, "Install result for move: " 12955 + PackageManager.installStatusToString(returnCode, msg)); 12956 12957 // We usually have a new package now after the install, but if 12958 // we failed we need to clear the pending flag on the original 12959 // package object. 12960 synchronized (mPackages) { 12961 final PackageParser.Package pkg = mPackages.get(packageName); 12962 if (pkg != null) { 12963 pkg.mOperationPending = false; 12964 } 12965 } 12966 12967 final int status = PackageManager.installStatusToPublicStatus(returnCode); 12968 switch (status) { 12969 case PackageInstaller.STATUS_SUCCESS: 12970 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 12971 break; 12972 case PackageInstaller.STATUS_FAILURE_STORAGE: 12973 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 12974 break; 12975 default: 12976 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 12977 break; 12978 } 12979 } 12980 }; 12981 12982 // Treat a move like reinstalling an existing app, which ensures that we 12983 // process everythign uniformly, like unpacking native libraries. 12984 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 12985 12986 final Message msg = mHandler.obtainMessage(INIT_COPY); 12987 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 12988 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 12989 installerPackageName, null, user, packageAbiOverride); 12990 mHandler.sendMessage(msg); 12991 } 12992 12993 @Override 12994 public boolean setInstallLocation(int loc) { 12995 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 12996 null); 12997 if (getInstallLocation() == loc) { 12998 return true; 12999 } 13000 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13001 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13002 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13003 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13004 return true; 13005 } 13006 return false; 13007 } 13008 13009 @Override 13010 public int getInstallLocation() { 13011 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13012 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13013 PackageHelper.APP_INSTALL_AUTO); 13014 } 13015 13016 /** Called by UserManagerService */ 13017 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 13018 mDirtyUsers.remove(userHandle); 13019 mSettings.removeUserLPw(userHandle); 13020 mPendingBroadcasts.remove(userHandle); 13021 if (mInstaller != null) { 13022 // Technically, we shouldn't be doing this with the package lock 13023 // held. However, this is very rare, and there is already so much 13024 // other disk I/O going on, that we'll let it slide for now. 13025 mInstaller.removeUserDataDirs(userHandle); 13026 } 13027 mUserNeedsBadging.delete(userHandle); 13028 removeUnusedPackagesLILPw(userManager, userHandle); 13029 } 13030 13031 /** 13032 * We're removing userHandle and would like to remove any downloaded packages 13033 * that are no longer in use by any other user. 13034 * @param userHandle the user being removed 13035 */ 13036 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 13037 final boolean DEBUG_CLEAN_APKS = false; 13038 int [] users = userManager.getUserIdsLPr(); 13039 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 13040 while (psit.hasNext()) { 13041 PackageSetting ps = psit.next(); 13042 if (ps.pkg == null) { 13043 continue; 13044 } 13045 final String packageName = ps.pkg.packageName; 13046 // Skip over if system app 13047 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13048 continue; 13049 } 13050 if (DEBUG_CLEAN_APKS) { 13051 Slog.i(TAG, "Checking package " + packageName); 13052 } 13053 boolean keep = false; 13054 for (int i = 0; i < users.length; i++) { 13055 if (users[i] != userHandle && ps.getInstalled(users[i])) { 13056 keep = true; 13057 if (DEBUG_CLEAN_APKS) { 13058 Slog.i(TAG, " Keeping package " + packageName + " for user " 13059 + users[i]); 13060 } 13061 break; 13062 } 13063 } 13064 if (!keep) { 13065 if (DEBUG_CLEAN_APKS) { 13066 Slog.i(TAG, " Removing package " + packageName); 13067 } 13068 mHandler.post(new Runnable() { 13069 public void run() { 13070 deletePackageX(packageName, userHandle, 0); 13071 } //end run 13072 }); 13073 } 13074 } 13075 } 13076 13077 /** Called by UserManagerService */ 13078 void createNewUserLILPw(int userHandle, File path) { 13079 if (mInstaller != null) { 13080 mInstaller.createUserConfig(userHandle); 13081 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13082 } 13083 } 13084 13085 @Override 13086 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13087 mContext.enforceCallingOrSelfPermission( 13088 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13089 "Only package verification agents can read the verifier device identity"); 13090 13091 synchronized (mPackages) { 13092 return mSettings.getVerifierDeviceIdentityLPw(); 13093 } 13094 } 13095 13096 @Override 13097 public void setPermissionEnforced(String permission, boolean enforced) { 13098 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13099 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13100 synchronized (mPackages) { 13101 if (mSettings.mReadExternalStorageEnforced == null 13102 || mSettings.mReadExternalStorageEnforced != enforced) { 13103 mSettings.mReadExternalStorageEnforced = enforced; 13104 mSettings.writeLPr(); 13105 } 13106 } 13107 // kill any non-foreground processes so we restart them and 13108 // grant/revoke the GID. 13109 final IActivityManager am = ActivityManagerNative.getDefault(); 13110 if (am != null) { 13111 final long token = Binder.clearCallingIdentity(); 13112 try { 13113 am.killProcessesBelowForeground("setPermissionEnforcement"); 13114 } catch (RemoteException e) { 13115 } finally { 13116 Binder.restoreCallingIdentity(token); 13117 } 13118 } 13119 } else { 13120 throw new IllegalArgumentException("No selective enforcement for " + permission); 13121 } 13122 } 13123 13124 @Override 13125 @Deprecated 13126 public boolean isPermissionEnforced(String permission) { 13127 return true; 13128 } 13129 13130 @Override 13131 public boolean isStorageLow() { 13132 final long token = Binder.clearCallingIdentity(); 13133 try { 13134 final DeviceStorageMonitorInternal 13135 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13136 if (dsm != null) { 13137 return dsm.isMemoryLow(); 13138 } else { 13139 return false; 13140 } 13141 } finally { 13142 Binder.restoreCallingIdentity(token); 13143 } 13144 } 13145 13146 @Override 13147 public IPackageInstaller getPackageInstaller() { 13148 return mInstallerService; 13149 } 13150 13151 private boolean userNeedsBadging(int userId) { 13152 int index = mUserNeedsBadging.indexOfKey(userId); 13153 if (index < 0) { 13154 final UserInfo userInfo; 13155 final long token = Binder.clearCallingIdentity(); 13156 try { 13157 userInfo = sUserManager.getUserInfo(userId); 13158 } finally { 13159 Binder.restoreCallingIdentity(token); 13160 } 13161 final boolean b; 13162 if (userInfo != null && userInfo.isManagedProfile()) { 13163 b = true; 13164 } else { 13165 b = false; 13166 } 13167 mUserNeedsBadging.put(userId, b); 13168 return b; 13169 } 13170 return mUserNeedsBadging.valueAt(index); 13171 } 13172 13173 @Override 13174 public KeySet getKeySetByAlias(String packageName, String alias) { 13175 if (packageName == null || alias == null) { 13176 return null; 13177 } 13178 synchronized(mPackages) { 13179 final PackageParser.Package pkg = mPackages.get(packageName); 13180 if (pkg == null) { 13181 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13182 throw new IllegalArgumentException("Unknown package: " + packageName); 13183 } 13184 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13185 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13186 } 13187 } 13188 13189 @Override 13190 public KeySet getSigningKeySet(String packageName) { 13191 if (packageName == null) { 13192 return null; 13193 } 13194 synchronized(mPackages) { 13195 final PackageParser.Package pkg = mPackages.get(packageName); 13196 if (pkg == null) { 13197 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13198 throw new IllegalArgumentException("Unknown package: " + packageName); 13199 } 13200 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13201 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13202 throw new SecurityException("May not access signing KeySet of other apps."); 13203 } 13204 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13205 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13206 } 13207 } 13208 13209 @Override 13210 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13211 if (packageName == null || ks == null) { 13212 return false; 13213 } 13214 synchronized(mPackages) { 13215 final PackageParser.Package pkg = mPackages.get(packageName); 13216 if (pkg == null) { 13217 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13218 throw new IllegalArgumentException("Unknown package: " + packageName); 13219 } 13220 IBinder ksh = ks.getToken(); 13221 if (ksh instanceof KeySetHandle) { 13222 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13223 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13224 } 13225 return false; 13226 } 13227 } 13228 13229 @Override 13230 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13231 if (packageName == null || ks == null) { 13232 return false; 13233 } 13234 synchronized(mPackages) { 13235 final PackageParser.Package pkg = mPackages.get(packageName); 13236 if (pkg == null) { 13237 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13238 throw new IllegalArgumentException("Unknown package: " + packageName); 13239 } 13240 IBinder ksh = ks.getToken(); 13241 if (ksh instanceof KeySetHandle) { 13242 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13243 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13244 } 13245 return false; 13246 } 13247 } 13248} 13249