PackageManagerService.java revision b9f8a5204a1b0b3919fa921e858d04124c582828
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.BufferedReader; 180import java.io.File; 181import java.io.FileDescriptor; 182import java.io.FileInputStream; 183import java.io.FileNotFoundException; 184import java.io.FileOutputStream; 185import java.io.FileReader; 186import java.io.FilenameFilter; 187import java.io.IOException; 188import java.io.InputStream; 189import java.io.PrintWriter; 190import java.nio.charset.StandardCharsets; 191import java.security.NoSuchAlgorithmException; 192import java.security.PublicKey; 193import java.security.cert.CertificateEncodingException; 194import java.security.cert.CertificateException; 195import java.text.SimpleDateFormat; 196import java.util.ArrayList; 197import java.util.Arrays; 198import java.util.Collection; 199import java.util.Collections; 200import java.util.Comparator; 201import java.util.Date; 202import java.util.HashMap; 203import java.util.HashSet; 204import java.util.Iterator; 205import java.util.List; 206import java.util.Map; 207import java.util.Objects; 208import java.util.Set; 209import java.util.concurrent.atomic.AtomicBoolean; 210import java.util.concurrent.atomic.AtomicLong; 211 212import dalvik.system.DexFile; 213import dalvik.system.StaleDexCacheError; 214import dalvik.system.VMRuntime; 215 216import libcore.io.IoUtils; 217import libcore.util.EmptyArray; 218 219/** 220 * Keep track of all those .apks everywhere. 221 * 222 * This is very central to the platform's security; please run the unit 223 * tests whenever making modifications here: 224 * 225mmm frameworks/base/tests/AndroidTests 226adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 227adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 228 * 229 * {@hide} 230 */ 231public class PackageManagerService extends IPackageManager.Stub { 232 static final String TAG = "PackageManager"; 233 static final boolean DEBUG_SETTINGS = false; 234 static final boolean DEBUG_PREFERRED = false; 235 static final boolean DEBUG_UPGRADE = false; 236 private static final boolean DEBUG_INSTALL = false; 237 private static final boolean DEBUG_REMOVE = false; 238 private static final boolean DEBUG_BROADCASTS = false; 239 private static final boolean DEBUG_SHOW_INFO = false; 240 private static final boolean DEBUG_PACKAGE_INFO = false; 241 private static final boolean DEBUG_INTENT_MATCHING = false; 242 private static final boolean DEBUG_PACKAGE_SCANNING = false; 243 private static final boolean DEBUG_VERIFY = false; 244 private static final boolean DEBUG_DEXOPT = false; 245 private static final boolean DEBUG_ABI_SELECTION = false; 246 247 private static final int RADIO_UID = Process.PHONE_UID; 248 private static final int LOG_UID = Process.LOG_UID; 249 private static final int NFC_UID = Process.NFC_UID; 250 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 251 private static final int SHELL_UID = Process.SHELL_UID; 252 253 // Cap the size of permission trees that 3rd party apps can define 254 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 255 256 // Suffix used during package installation when copying/moving 257 // package apks to install directory. 258 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 259 260 static final int SCAN_NO_DEX = 1<<1; 261 static final int SCAN_FORCE_DEX = 1<<2; 262 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 263 static final int SCAN_NEW_INSTALL = 1<<4; 264 static final int SCAN_NO_PATHS = 1<<5; 265 static final int SCAN_UPDATE_TIME = 1<<6; 266 static final int SCAN_DEFER_DEX = 1<<7; 267 static final int SCAN_BOOTING = 1<<8; 268 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 269 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 270 static final int SCAN_REPLACING = 1<<11; 271 272 static final int REMOVE_CHATTY = 1<<16; 273 274 /** 275 * Timeout (in milliseconds) after which the watchdog should declare that 276 * our handler thread is wedged. The usual default for such things is one 277 * minute but we sometimes do very lengthy I/O operations on this thread, 278 * such as installing multi-gigabyte applications, so ours needs to be longer. 279 */ 280 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 281 282 /** 283 * Whether verification is enabled by default. 284 */ 285 private static final boolean DEFAULT_VERIFY_ENABLE = true; 286 287 /** 288 * The default maximum time to wait for the verification agent to return in 289 * milliseconds. 290 */ 291 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 292 293 /** 294 * The default response for package verification timeout. 295 * 296 * This can be either PackageManager.VERIFICATION_ALLOW or 297 * PackageManager.VERIFICATION_REJECT. 298 */ 299 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 300 301 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 302 303 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 304 DEFAULT_CONTAINER_PACKAGE, 305 "com.android.defcontainer.DefaultContainerService"); 306 307 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 308 309 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 310 311 private static String sPreferredInstructionSet; 312 313 final ServiceThread mHandlerThread; 314 315 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 316 private static final String IDMAP_SUFFIX = "@idmap"; 317 318 final PackageHandler mHandler; 319 320 /** 321 * Messages for {@link #mHandler} that need to wait for system ready before 322 * being dispatched. 323 */ 324 private ArrayList<Message> mPostSystemReadyMessages; 325 326 final int mSdkVersion = Build.VERSION.SDK_INT; 327 328 final Context mContext; 329 final boolean mFactoryTest; 330 final boolean mOnlyCore; 331 final boolean mLazyDexOpt; 332 final DisplayMetrics mMetrics; 333 final int mDefParseFlags; 334 final String[] mSeparateProcesses; 335 336 // This is where all application persistent data goes. 337 final File mAppDataDir; 338 339 // This is where all application persistent data goes for secondary users. 340 final File mUserAppDataDir; 341 342 /** The location for ASEC container files on internal storage. */ 343 final String mAsecInternalPath; 344 345 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 346 // LOCK HELD. Can be called with mInstallLock held. 347 final Installer mInstaller; 348 349 /** Directory where installed third-party apps stored */ 350 final File mAppInstallDir; 351 352 /** 353 * Directory to which applications installed internally have their 354 * 32 bit native libraries copied. 355 */ 356 private File mAppLib32InstallDir; 357 358 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 359 // apps. 360 final File mDrmAppPrivateInstallDir; 361 362 // ---------------------------------------------------------------- 363 364 // Lock for state used when installing and doing other long running 365 // operations. Methods that must be called with this lock held have 366 // the suffix "LI". 367 final Object mInstallLock = new Object(); 368 369 // ---------------------------------------------------------------- 370 371 // Keys are String (package name), values are Package. This also serves 372 // as the lock for the global state. Methods that must be called with 373 // this lock held have the prefix "LP". 374 final HashMap<String, PackageParser.Package> mPackages = 375 new HashMap<String, PackageParser.Package>(); 376 377 // Tracks available target package names -> overlay package paths. 378 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 379 new HashMap<String, HashMap<String, PackageParser.Package>>(); 380 381 final Settings mSettings; 382 boolean mRestoredSettings; 383 384 // System configuration read by SystemConfig. 385 final int[] mGlobalGids; 386 final SparseArray<HashSet<String>> mSystemPermissions; 387 final HashMap<String, FeatureInfo> mAvailableFeatures; 388 389 // If mac_permissions.xml was found for seinfo labeling. 390 boolean mFoundPolicyFile; 391 392 // If a recursive restorecon of /data/data/<pkg> is needed. 393 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 394 395 public static final class SharedLibraryEntry { 396 public final String path; 397 public final String apk; 398 399 SharedLibraryEntry(String _path, String _apk) { 400 path = _path; 401 apk = _apk; 402 } 403 } 404 405 // Currently known shared libraries. 406 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 407 new HashMap<String, SharedLibraryEntry>(); 408 409 // All available activities, for your resolving pleasure. 410 final ActivityIntentResolver mActivities = 411 new ActivityIntentResolver(); 412 413 // All available receivers, for your resolving pleasure. 414 final ActivityIntentResolver mReceivers = 415 new ActivityIntentResolver(); 416 417 // All available services, for your resolving pleasure. 418 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 419 420 // All available providers, for your resolving pleasure. 421 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 422 423 // Mapping from provider base names (first directory in content URI codePath) 424 // to the provider information. 425 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 426 new HashMap<String, PackageParser.Provider>(); 427 428 // Mapping from instrumentation class names to info about them. 429 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 430 new HashMap<ComponentName, PackageParser.Instrumentation>(); 431 432 // Mapping from permission names to info about them. 433 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 434 new HashMap<String, PackageParser.PermissionGroup>(); 435 436 // Packages whose data we have transfered into another package, thus 437 // should no longer exist. 438 final HashSet<String> mTransferedPackages = new HashSet<String>(); 439 440 // Broadcast actions that are only available to the system. 441 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 442 443 /** List of packages waiting for verification. */ 444 final SparseArray<PackageVerificationState> mPendingVerification 445 = new SparseArray<PackageVerificationState>(); 446 447 /** Set of packages associated with each app op permission. */ 448 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 449 450 final PackageInstallerService mInstallerService; 451 452 HashSet<PackageParser.Package> mDeferredDexOpt = null; 453 454 // Cache of users who need badging. 455 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 456 457 /** Token for keys in mPendingVerification. */ 458 private int mPendingVerificationToken = 0; 459 460 volatile boolean mSystemReady; 461 volatile boolean mSafeMode; 462 volatile boolean mHasSystemUidErrors; 463 464 ApplicationInfo mAndroidApplication; 465 final ActivityInfo mResolveActivity = new ActivityInfo(); 466 final ResolveInfo mResolveInfo = new ResolveInfo(); 467 ComponentName mResolveComponentName; 468 PackageParser.Package mPlatformPackage; 469 ComponentName mCustomResolverComponentName; 470 471 boolean mResolverReplaced = false; 472 473 // Set of pending broadcasts for aggregating enable/disable of components. 474 static class PendingPackageBroadcasts { 475 // for each user id, a map of <package name -> components within that package> 476 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 477 478 public PendingPackageBroadcasts() { 479 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 480 } 481 482 public ArrayList<String> get(int userId, String packageName) { 483 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 484 return packages.get(packageName); 485 } 486 487 public void put(int userId, String packageName, ArrayList<String> components) { 488 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 489 packages.put(packageName, components); 490 } 491 492 public void remove(int userId, String packageName) { 493 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 494 if (packages != null) { 495 packages.remove(packageName); 496 } 497 } 498 499 public void remove(int userId) { 500 mUidMap.remove(userId); 501 } 502 503 public int userIdCount() { 504 return mUidMap.size(); 505 } 506 507 public int userIdAt(int n) { 508 return mUidMap.keyAt(n); 509 } 510 511 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 512 return mUidMap.get(userId); 513 } 514 515 public int size() { 516 // total number of pending broadcast entries across all userIds 517 int num = 0; 518 for (int i = 0; i< mUidMap.size(); i++) { 519 num += mUidMap.valueAt(i).size(); 520 } 521 return num; 522 } 523 524 public void clear() { 525 mUidMap.clear(); 526 } 527 528 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 529 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 530 if (map == null) { 531 map = new HashMap<String, ArrayList<String>>(); 532 mUidMap.put(userId, map); 533 } 534 return map; 535 } 536 } 537 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 538 539 // Service Connection to remote media container service to copy 540 // package uri's from external media onto secure containers 541 // or internal storage. 542 private IMediaContainerService mContainerService = null; 543 544 static final int SEND_PENDING_BROADCAST = 1; 545 static final int MCS_BOUND = 3; 546 static final int END_COPY = 4; 547 static final int INIT_COPY = 5; 548 static final int MCS_UNBIND = 6; 549 static final int START_CLEANING_PACKAGE = 7; 550 static final int FIND_INSTALL_LOC = 8; 551 static final int POST_INSTALL = 9; 552 static final int MCS_RECONNECT = 10; 553 static final int MCS_GIVE_UP = 11; 554 static final int UPDATED_MEDIA_STATUS = 12; 555 static final int WRITE_SETTINGS = 13; 556 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 557 static final int PACKAGE_VERIFIED = 15; 558 static final int CHECK_PENDING_VERIFICATION = 16; 559 560 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 561 562 // Delay time in millisecs 563 static final int BROADCAST_DELAY = 10 * 1000; 564 565 static UserManagerService sUserManager; 566 567 // Stores a list of users whose package restrictions file needs to be updated 568 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 569 570 final private DefaultContainerConnection mDefContainerConn = 571 new DefaultContainerConnection(); 572 class DefaultContainerConnection implements ServiceConnection { 573 public void onServiceConnected(ComponentName name, IBinder service) { 574 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 575 IMediaContainerService imcs = 576 IMediaContainerService.Stub.asInterface(service); 577 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 578 } 579 580 public void onServiceDisconnected(ComponentName name) { 581 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 582 } 583 }; 584 585 // Recordkeeping of restore-after-install operations that are currently in flight 586 // between the Package Manager and the Backup Manager 587 class PostInstallData { 588 public InstallArgs args; 589 public PackageInstalledInfo res; 590 591 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 592 args = _a; 593 res = _r; 594 } 595 }; 596 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 597 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 598 599 private final String mRequiredVerifierPackage; 600 601 private final PackageUsage mPackageUsage = new PackageUsage(); 602 603 private class PackageUsage { 604 private static final int WRITE_INTERVAL 605 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 606 607 private final Object mFileLock = new Object(); 608 private final AtomicLong mLastWritten = new AtomicLong(0); 609 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 610 611 private boolean mIsHistoricalPackageUsageAvailable = true; 612 613 boolean isHistoricalPackageUsageAvailable() { 614 return mIsHistoricalPackageUsageAvailable; 615 } 616 617 void write(boolean force) { 618 if (force) { 619 writeInternal(); 620 return; 621 } 622 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 623 && !DEBUG_DEXOPT) { 624 return; 625 } 626 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 627 new Thread("PackageUsage_DiskWriter") { 628 @Override 629 public void run() { 630 try { 631 writeInternal(); 632 } finally { 633 mBackgroundWriteRunning.set(false); 634 } 635 } 636 }.start(); 637 } 638 } 639 640 private void writeInternal() { 641 synchronized (mPackages) { 642 synchronized (mFileLock) { 643 AtomicFile file = getFile(); 644 FileOutputStream f = null; 645 try { 646 f = file.startWrite(); 647 BufferedOutputStream out = new BufferedOutputStream(f); 648 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 649 StringBuilder sb = new StringBuilder(); 650 for (PackageParser.Package pkg : mPackages.values()) { 651 if (pkg.mLastPackageUsageTimeInMills == 0) { 652 continue; 653 } 654 sb.setLength(0); 655 sb.append(pkg.packageName); 656 sb.append(' '); 657 sb.append((long)pkg.mLastPackageUsageTimeInMills); 658 sb.append('\n'); 659 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 660 } 661 out.flush(); 662 file.finishWrite(f); 663 } catch (IOException e) { 664 if (f != null) { 665 file.failWrite(f); 666 } 667 Log.e(TAG, "Failed to write package usage times", e); 668 } 669 } 670 } 671 mLastWritten.set(SystemClock.elapsedRealtime()); 672 } 673 674 void readLP() { 675 synchronized (mFileLock) { 676 AtomicFile file = getFile(); 677 BufferedInputStream in = null; 678 try { 679 in = new BufferedInputStream(file.openRead()); 680 StringBuffer sb = new StringBuffer(); 681 while (true) { 682 String packageName = readToken(in, sb, ' '); 683 if (packageName == null) { 684 break; 685 } 686 String timeInMillisString = readToken(in, sb, '\n'); 687 if (timeInMillisString == null) { 688 throw new IOException("Failed to find last usage time for package " 689 + packageName); 690 } 691 PackageParser.Package pkg = mPackages.get(packageName); 692 if (pkg == null) { 693 continue; 694 } 695 long timeInMillis; 696 try { 697 timeInMillis = Long.parseLong(timeInMillisString.toString()); 698 } catch (NumberFormatException e) { 699 throw new IOException("Failed to parse " + timeInMillisString 700 + " as a long.", e); 701 } 702 pkg.mLastPackageUsageTimeInMills = timeInMillis; 703 } 704 } catch (FileNotFoundException expected) { 705 mIsHistoricalPackageUsageAvailable = false; 706 } catch (IOException e) { 707 Log.w(TAG, "Failed to read package usage times", e); 708 } finally { 709 IoUtils.closeQuietly(in); 710 } 711 } 712 mLastWritten.set(SystemClock.elapsedRealtime()); 713 } 714 715 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 716 throws IOException { 717 sb.setLength(0); 718 while (true) { 719 int ch = in.read(); 720 if (ch == -1) { 721 if (sb.length() == 0) { 722 return null; 723 } 724 throw new IOException("Unexpected EOF"); 725 } 726 if (ch == endOfToken) { 727 return sb.toString(); 728 } 729 sb.append((char)ch); 730 } 731 } 732 733 private AtomicFile getFile() { 734 File dataDir = Environment.getDataDirectory(); 735 File systemDir = new File(dataDir, "system"); 736 File fname = new File(systemDir, "package-usage.list"); 737 return new AtomicFile(fname); 738 } 739 } 740 741 class PackageHandler extends Handler { 742 private boolean mBound = false; 743 final ArrayList<HandlerParams> mPendingInstalls = 744 new ArrayList<HandlerParams>(); 745 746 private boolean connectToService() { 747 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 748 " DefaultContainerService"); 749 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 750 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 751 if (mContext.bindServiceAsUser(service, mDefContainerConn, 752 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 753 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 754 mBound = true; 755 return true; 756 } 757 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 758 return false; 759 } 760 761 private void disconnectService() { 762 mContainerService = null; 763 mBound = false; 764 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 765 mContext.unbindService(mDefContainerConn); 766 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 767 } 768 769 PackageHandler(Looper looper) { 770 super(looper); 771 } 772 773 public void handleMessage(Message msg) { 774 try { 775 doHandleMessage(msg); 776 } finally { 777 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 778 } 779 } 780 781 void doHandleMessage(Message msg) { 782 switch (msg.what) { 783 case INIT_COPY: { 784 HandlerParams params = (HandlerParams) msg.obj; 785 int idx = mPendingInstalls.size(); 786 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 787 // If a bind was already initiated we dont really 788 // need to do anything. The pending install 789 // will be processed later on. 790 if (!mBound) { 791 // If this is the only one pending we might 792 // have to bind to the service again. 793 if (!connectToService()) { 794 Slog.e(TAG, "Failed to bind to media container service"); 795 params.serviceError(); 796 return; 797 } else { 798 // Once we bind to the service, the first 799 // pending request will be processed. 800 mPendingInstalls.add(idx, params); 801 } 802 } else { 803 mPendingInstalls.add(idx, params); 804 // Already bound to the service. Just make 805 // sure we trigger off processing the first request. 806 if (idx == 0) { 807 mHandler.sendEmptyMessage(MCS_BOUND); 808 } 809 } 810 break; 811 } 812 case MCS_BOUND: { 813 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 814 if (msg.obj != null) { 815 mContainerService = (IMediaContainerService) msg.obj; 816 } 817 if (mContainerService == null) { 818 // Something seriously wrong. Bail out 819 Slog.e(TAG, "Cannot bind to media container service"); 820 for (HandlerParams params : mPendingInstalls) { 821 // Indicate service bind error 822 params.serviceError(); 823 } 824 mPendingInstalls.clear(); 825 } else if (mPendingInstalls.size() > 0) { 826 HandlerParams params = mPendingInstalls.get(0); 827 if (params != null) { 828 if (params.startCopy()) { 829 // We are done... look for more work or to 830 // go idle. 831 if (DEBUG_SD_INSTALL) Log.i(TAG, 832 "Checking for more work or unbind..."); 833 // Delete pending install 834 if (mPendingInstalls.size() > 0) { 835 mPendingInstalls.remove(0); 836 } 837 if (mPendingInstalls.size() == 0) { 838 if (mBound) { 839 if (DEBUG_SD_INSTALL) Log.i(TAG, 840 "Posting delayed MCS_UNBIND"); 841 removeMessages(MCS_UNBIND); 842 Message ubmsg = obtainMessage(MCS_UNBIND); 843 // Unbind after a little delay, to avoid 844 // continual thrashing. 845 sendMessageDelayed(ubmsg, 10000); 846 } 847 } else { 848 // There are more pending requests in queue. 849 // Just post MCS_BOUND message to trigger processing 850 // of next pending install. 851 if (DEBUG_SD_INSTALL) Log.i(TAG, 852 "Posting MCS_BOUND for next work"); 853 mHandler.sendEmptyMessage(MCS_BOUND); 854 } 855 } 856 } 857 } else { 858 // Should never happen ideally. 859 Slog.w(TAG, "Empty queue"); 860 } 861 break; 862 } 863 case MCS_RECONNECT: { 864 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 865 if (mPendingInstalls.size() > 0) { 866 if (mBound) { 867 disconnectService(); 868 } 869 if (!connectToService()) { 870 Slog.e(TAG, "Failed to bind to media container service"); 871 for (HandlerParams params : mPendingInstalls) { 872 // Indicate service bind error 873 params.serviceError(); 874 } 875 mPendingInstalls.clear(); 876 } 877 } 878 break; 879 } 880 case MCS_UNBIND: { 881 // If there is no actual work left, then time to unbind. 882 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 883 884 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 885 if (mBound) { 886 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 887 888 disconnectService(); 889 } 890 } else if (mPendingInstalls.size() > 0) { 891 // There are more pending requests in queue. 892 // Just post MCS_BOUND message to trigger processing 893 // of next pending install. 894 mHandler.sendEmptyMessage(MCS_BOUND); 895 } 896 897 break; 898 } 899 case MCS_GIVE_UP: { 900 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 901 mPendingInstalls.remove(0); 902 break; 903 } 904 case SEND_PENDING_BROADCAST: { 905 String packages[]; 906 ArrayList<String> components[]; 907 int size = 0; 908 int uids[]; 909 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 910 synchronized (mPackages) { 911 if (mPendingBroadcasts == null) { 912 return; 913 } 914 size = mPendingBroadcasts.size(); 915 if (size <= 0) { 916 // Nothing to be done. Just return 917 return; 918 } 919 packages = new String[size]; 920 components = new ArrayList[size]; 921 uids = new int[size]; 922 int i = 0; // filling out the above arrays 923 924 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 925 int packageUserId = mPendingBroadcasts.userIdAt(n); 926 Iterator<Map.Entry<String, ArrayList<String>>> it 927 = mPendingBroadcasts.packagesForUserId(packageUserId) 928 .entrySet().iterator(); 929 while (it.hasNext() && i < size) { 930 Map.Entry<String, ArrayList<String>> ent = it.next(); 931 packages[i] = ent.getKey(); 932 components[i] = ent.getValue(); 933 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 934 uids[i] = (ps != null) 935 ? UserHandle.getUid(packageUserId, ps.appId) 936 : -1; 937 i++; 938 } 939 } 940 size = i; 941 mPendingBroadcasts.clear(); 942 } 943 // Send broadcasts 944 for (int i = 0; i < size; i++) { 945 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 946 } 947 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 948 break; 949 } 950 case START_CLEANING_PACKAGE: { 951 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 952 final String packageName = (String)msg.obj; 953 final int userId = msg.arg1; 954 final boolean andCode = msg.arg2 != 0; 955 synchronized (mPackages) { 956 if (userId == UserHandle.USER_ALL) { 957 int[] users = sUserManager.getUserIds(); 958 for (int user : users) { 959 mSettings.addPackageToCleanLPw( 960 new PackageCleanItem(user, packageName, andCode)); 961 } 962 } else { 963 mSettings.addPackageToCleanLPw( 964 new PackageCleanItem(userId, packageName, andCode)); 965 } 966 } 967 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 968 startCleaningPackages(); 969 } break; 970 case POST_INSTALL: { 971 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 972 PostInstallData data = mRunningInstalls.get(msg.arg1); 973 mRunningInstalls.delete(msg.arg1); 974 boolean deleteOld = false; 975 976 if (data != null) { 977 InstallArgs args = data.args; 978 PackageInstalledInfo res = data.res; 979 980 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 981 res.removedInfo.sendBroadcast(false, true, false); 982 Bundle extras = new Bundle(1); 983 extras.putInt(Intent.EXTRA_UID, res.uid); 984 // Determine the set of users who are adding this 985 // package for the first time vs. those who are seeing 986 // an update. 987 int[] firstUsers; 988 int[] updateUsers = new int[0]; 989 if (res.origUsers == null || res.origUsers.length == 0) { 990 firstUsers = res.newUsers; 991 } else { 992 firstUsers = new int[0]; 993 for (int i=0; i<res.newUsers.length; i++) { 994 int user = res.newUsers[i]; 995 boolean isNew = true; 996 for (int j=0; j<res.origUsers.length; j++) { 997 if (res.origUsers[j] == user) { 998 isNew = false; 999 break; 1000 } 1001 } 1002 if (isNew) { 1003 int[] newFirst = new int[firstUsers.length+1]; 1004 System.arraycopy(firstUsers, 0, newFirst, 0, 1005 firstUsers.length); 1006 newFirst[firstUsers.length] = user; 1007 firstUsers = newFirst; 1008 } else { 1009 int[] newUpdate = new int[updateUsers.length+1]; 1010 System.arraycopy(updateUsers, 0, newUpdate, 0, 1011 updateUsers.length); 1012 newUpdate[updateUsers.length] = user; 1013 updateUsers = newUpdate; 1014 } 1015 } 1016 } 1017 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1018 res.pkg.applicationInfo.packageName, 1019 extras, null, null, firstUsers); 1020 final boolean update = res.removedInfo.removedPackage != null; 1021 if (update) { 1022 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1023 } 1024 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1025 res.pkg.applicationInfo.packageName, 1026 extras, null, null, updateUsers); 1027 if (update) { 1028 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1029 res.pkg.applicationInfo.packageName, 1030 extras, null, null, updateUsers); 1031 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1032 null, null, 1033 res.pkg.applicationInfo.packageName, null, updateUsers); 1034 1035 // treat asec-hosted packages like removable media on upgrade 1036 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1037 if (DEBUG_INSTALL) { 1038 Slog.i(TAG, "upgrading pkg " + res.pkg 1039 + " is ASEC-hosted -> AVAILABLE"); 1040 } 1041 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1042 ArrayList<String> pkgList = new ArrayList<String>(1); 1043 pkgList.add(res.pkg.applicationInfo.packageName); 1044 sendResourcesChangedBroadcast(true, true, 1045 pkgList,uidArray, null); 1046 } 1047 } 1048 if (res.removedInfo.args != null) { 1049 // Remove the replaced package's older resources safely now 1050 deleteOld = true; 1051 } 1052 1053 // Log current value of "unknown sources" setting 1054 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1055 getUnknownSourcesSettings()); 1056 } 1057 // Force a gc to clear up things 1058 Runtime.getRuntime().gc(); 1059 // We delete after a gc for applications on sdcard. 1060 if (deleteOld) { 1061 synchronized (mInstallLock) { 1062 res.removedInfo.args.doPostDeleteLI(true); 1063 } 1064 } 1065 if (args.observer != null) { 1066 try { 1067 Bundle extras = extrasForInstallResult(res); 1068 args.observer.onPackageInstalled(res.name, res.returnCode, 1069 res.returnMsg, extras); 1070 } catch (RemoteException e) { 1071 Slog.i(TAG, "Observer no longer exists."); 1072 } 1073 } 1074 } else { 1075 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1076 } 1077 } break; 1078 case UPDATED_MEDIA_STATUS: { 1079 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1080 boolean reportStatus = msg.arg1 == 1; 1081 boolean doGc = msg.arg2 == 1; 1082 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1083 if (doGc) { 1084 // Force a gc to clear up stale containers. 1085 Runtime.getRuntime().gc(); 1086 } 1087 if (msg.obj != null) { 1088 @SuppressWarnings("unchecked") 1089 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1090 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1091 // Unload containers 1092 unloadAllContainers(args); 1093 } 1094 if (reportStatus) { 1095 try { 1096 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1097 PackageHelper.getMountService().finishMediaUpdate(); 1098 } catch (RemoteException e) { 1099 Log.e(TAG, "MountService not running?"); 1100 } 1101 } 1102 } break; 1103 case WRITE_SETTINGS: { 1104 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1105 synchronized (mPackages) { 1106 removeMessages(WRITE_SETTINGS); 1107 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1108 mSettings.writeLPr(); 1109 mDirtyUsers.clear(); 1110 } 1111 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1112 } break; 1113 case WRITE_PACKAGE_RESTRICTIONS: { 1114 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1115 synchronized (mPackages) { 1116 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1117 for (int userId : mDirtyUsers) { 1118 mSettings.writePackageRestrictionsLPr(userId); 1119 } 1120 mDirtyUsers.clear(); 1121 } 1122 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1123 } break; 1124 case CHECK_PENDING_VERIFICATION: { 1125 final int verificationId = msg.arg1; 1126 final PackageVerificationState state = mPendingVerification.get(verificationId); 1127 1128 if ((state != null) && !state.timeoutExtended()) { 1129 final InstallArgs args = state.getInstallArgs(); 1130 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1131 1132 Slog.i(TAG, "Verification timed out for " + originUri); 1133 mPendingVerification.remove(verificationId); 1134 1135 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1136 1137 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1138 Slog.i(TAG, "Continuing with installation of " + originUri); 1139 state.setVerifierResponse(Binder.getCallingUid(), 1140 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1141 broadcastPackageVerified(verificationId, originUri, 1142 PackageManager.VERIFICATION_ALLOW, 1143 state.getInstallArgs().getUser()); 1144 try { 1145 ret = args.copyApk(mContainerService, true); 1146 } catch (RemoteException e) { 1147 Slog.e(TAG, "Could not contact the ContainerService"); 1148 } 1149 } else { 1150 broadcastPackageVerified(verificationId, originUri, 1151 PackageManager.VERIFICATION_REJECT, 1152 state.getInstallArgs().getUser()); 1153 } 1154 1155 processPendingInstall(args, ret); 1156 mHandler.sendEmptyMessage(MCS_UNBIND); 1157 } 1158 break; 1159 } 1160 case PACKAGE_VERIFIED: { 1161 final int verificationId = msg.arg1; 1162 1163 final PackageVerificationState state = mPendingVerification.get(verificationId); 1164 if (state == null) { 1165 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1166 break; 1167 } 1168 1169 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1170 1171 state.setVerifierResponse(response.callerUid, response.code); 1172 1173 if (state.isVerificationComplete()) { 1174 mPendingVerification.remove(verificationId); 1175 1176 final InstallArgs args = state.getInstallArgs(); 1177 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1178 1179 int ret; 1180 if (state.isInstallAllowed()) { 1181 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1182 broadcastPackageVerified(verificationId, originUri, 1183 response.code, state.getInstallArgs().getUser()); 1184 try { 1185 ret = args.copyApk(mContainerService, true); 1186 } catch (RemoteException e) { 1187 Slog.e(TAG, "Could not contact the ContainerService"); 1188 } 1189 } else { 1190 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1191 } 1192 1193 processPendingInstall(args, ret); 1194 1195 mHandler.sendEmptyMessage(MCS_UNBIND); 1196 } 1197 1198 break; 1199 } 1200 } 1201 } 1202 } 1203 1204 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1205 Bundle extras = null; 1206 switch (res.returnCode) { 1207 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1208 extras = new Bundle(); 1209 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1210 res.origPermission); 1211 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1212 res.origPackage); 1213 break; 1214 } 1215 } 1216 return extras; 1217 } 1218 1219 void scheduleWriteSettingsLocked() { 1220 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1221 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1222 } 1223 } 1224 1225 void scheduleWritePackageRestrictionsLocked(int userId) { 1226 if (!sUserManager.exists(userId)) return; 1227 mDirtyUsers.add(userId); 1228 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1229 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1230 } 1231 } 1232 1233 public static final PackageManagerService main(Context context, Installer installer, 1234 boolean factoryTest, boolean onlyCore) { 1235 PackageManagerService m = new PackageManagerService(context, installer, 1236 factoryTest, onlyCore); 1237 ServiceManager.addService("package", m); 1238 return m; 1239 } 1240 1241 static String[] splitString(String str, char sep) { 1242 int count = 1; 1243 int i = 0; 1244 while ((i=str.indexOf(sep, i)) >= 0) { 1245 count++; 1246 i++; 1247 } 1248 1249 String[] res = new String[count]; 1250 i=0; 1251 count = 0; 1252 int lastI=0; 1253 while ((i=str.indexOf(sep, i)) >= 0) { 1254 res[count] = str.substring(lastI, i); 1255 count++; 1256 i++; 1257 lastI = i; 1258 } 1259 res[count] = str.substring(lastI, str.length()); 1260 return res; 1261 } 1262 1263 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1264 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1265 Context.DISPLAY_SERVICE); 1266 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1267 } 1268 1269 public PackageManagerService(Context context, Installer installer, 1270 boolean factoryTest, boolean onlyCore) { 1271 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1272 SystemClock.uptimeMillis()); 1273 1274 if (mSdkVersion <= 0) { 1275 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1276 } 1277 1278 mContext = context; 1279 mFactoryTest = factoryTest; 1280 mOnlyCore = onlyCore; 1281 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1282 mMetrics = new DisplayMetrics(); 1283 mSettings = new Settings(context); 1284 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1285 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1286 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1287 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1288 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1289 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1290 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1291 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1292 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1293 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1294 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1295 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1296 1297 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1298 if (separateProcesses != null && separateProcesses.length() > 0) { 1299 if ("*".equals(separateProcesses)) { 1300 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1301 mSeparateProcesses = null; 1302 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1303 } else { 1304 mDefParseFlags = 0; 1305 mSeparateProcesses = separateProcesses.split(","); 1306 Slog.w(TAG, "Running with debug.separate_processes: " 1307 + separateProcesses); 1308 } 1309 } else { 1310 mDefParseFlags = 0; 1311 mSeparateProcesses = null; 1312 } 1313 1314 mInstaller = installer; 1315 1316 getDefaultDisplayMetrics(context, mMetrics); 1317 1318 SystemConfig systemConfig = SystemConfig.getInstance(); 1319 mGlobalGids = systemConfig.getGlobalGids(); 1320 mSystemPermissions = systemConfig.getSystemPermissions(); 1321 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1322 1323 synchronized (mInstallLock) { 1324 // writer 1325 synchronized (mPackages) { 1326 mHandlerThread = new ServiceThread(TAG, 1327 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1328 mHandlerThread.start(); 1329 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1330 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1331 1332 File dataDir = Environment.getDataDirectory(); 1333 mAppDataDir = new File(dataDir, "data"); 1334 mAppInstallDir = new File(dataDir, "app"); 1335 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1336 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1337 mUserAppDataDir = new File(dataDir, "user"); 1338 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1339 1340 sUserManager = new UserManagerService(context, this, 1341 mInstallLock, mPackages); 1342 1343 // Propagate permission configuration in to package manager. 1344 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1345 = systemConfig.getPermissions(); 1346 for (int i=0; i<permConfig.size(); i++) { 1347 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1348 BasePermission bp = mSettings.mPermissions.get(perm.name); 1349 if (bp == null) { 1350 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1351 mSettings.mPermissions.put(perm.name, bp); 1352 } 1353 if (perm.gids != null) { 1354 bp.gids = appendInts(bp.gids, perm.gids); 1355 } 1356 } 1357 1358 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1359 for (int i=0; i<libConfig.size(); i++) { 1360 mSharedLibraries.put(libConfig.keyAt(i), 1361 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1362 } 1363 1364 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1365 1366 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1367 mSdkVersion, mOnlyCore); 1368 1369 String customResolverActivity = Resources.getSystem().getString( 1370 R.string.config_customResolverActivity); 1371 if (TextUtils.isEmpty(customResolverActivity)) { 1372 customResolverActivity = null; 1373 } else { 1374 mCustomResolverComponentName = ComponentName.unflattenFromString( 1375 customResolverActivity); 1376 } 1377 1378 long startTime = SystemClock.uptimeMillis(); 1379 1380 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1381 startTime); 1382 1383 // Set flag to monitor and not change apk file paths when 1384 // scanning install directories. 1385 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1386 1387 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1388 1389 /** 1390 * Add everything in the in the boot class path to the 1391 * list of process files because dexopt will have been run 1392 * if necessary during zygote startup. 1393 */ 1394 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1395 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1396 1397 if (bootClassPath != null) { 1398 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1399 for (String element : bootClassPathElements) { 1400 alreadyDexOpted.add(element); 1401 } 1402 } else { 1403 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1404 } 1405 1406 if (systemServerClassPath != null) { 1407 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1408 for (String element : systemServerClassPathElements) { 1409 alreadyDexOpted.add(element); 1410 } 1411 } else { 1412 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1413 } 1414 1415 boolean didDexOptLibraryOrTool = false; 1416 1417 final List<String> allInstructionSets = getAllInstructionSets(); 1418 final String[] dexCodeInstructionSets = 1419 getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()])); 1420 1421 /** 1422 * Ensure all external libraries have had dexopt run on them. 1423 */ 1424 if (mSharedLibraries.size() > 0) { 1425 // NOTE: For now, we're compiling these system "shared libraries" 1426 // (and framework jars) into all available architectures. It's possible 1427 // to compile them only when we come across an app that uses them (there's 1428 // already logic for that in scanPackageLI) but that adds some complexity. 1429 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1430 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1431 final String lib = libEntry.path; 1432 if (lib == null) { 1433 continue; 1434 } 1435 1436 try { 1437 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1438 dexCodeInstructionSet, 1439 false); 1440 if (dexoptRequired != DexFile.UP_TO_DATE) { 1441 alreadyDexOpted.add(lib); 1442 1443 // The list of "shared libraries" we have at this point is 1444 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1445 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1446 } else { 1447 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1448 } 1449 didDexOptLibraryOrTool = true; 1450 } 1451 } catch (FileNotFoundException e) { 1452 Slog.w(TAG, "Library not found: " + lib); 1453 } catch (IOException e) { 1454 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1455 + e.getMessage()); 1456 } 1457 } 1458 } 1459 } 1460 1461 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1462 1463 // Gross hack for now: we know this file doesn't contain any 1464 // code, so don't dexopt it to avoid the resulting log spew. 1465 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1466 1467 // Gross hack for now: we know this file is only part of 1468 // the boot class path for art, so don't dexopt it to 1469 // avoid the resulting log spew. 1470 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1471 1472 /** 1473 * And there are a number of commands implemented in Java, which 1474 * we currently need to do the dexopt on so that they can be 1475 * run from a non-root shell. 1476 */ 1477 String[] frameworkFiles = frameworkDir.list(); 1478 if (frameworkFiles != null) { 1479 // TODO: We could compile these only for the most preferred ABI. We should 1480 // first double check that the dex files for these commands are not referenced 1481 // by other system apps. 1482 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1483 for (int i=0; i<frameworkFiles.length; i++) { 1484 File libPath = new File(frameworkDir, frameworkFiles[i]); 1485 String path = libPath.getPath(); 1486 // Skip the file if we already did it. 1487 if (alreadyDexOpted.contains(path)) { 1488 continue; 1489 } 1490 // Skip the file if it is not a type we want to dexopt. 1491 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1492 continue; 1493 } 1494 try { 1495 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1496 dexCodeInstructionSet, 1497 false); 1498 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1499 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1500 didDexOptLibraryOrTool = true; 1501 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1502 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1503 didDexOptLibraryOrTool = true; 1504 } 1505 } catch (FileNotFoundException e) { 1506 Slog.w(TAG, "Jar not found: " + path); 1507 } catch (IOException e) { 1508 Slog.w(TAG, "Exception reading jar: " + path, e); 1509 } 1510 } 1511 } 1512 } 1513 1514 // Collect vendor overlay packages. 1515 // (Do this before scanning any apps.) 1516 // For security and version matching reason, only consider 1517 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1518 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1519 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1520 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1521 1522 // Find base frameworks (resource packages without code). 1523 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1524 | PackageParser.PARSE_IS_SYSTEM_DIR 1525 | PackageParser.PARSE_IS_PRIVILEGED, 1526 scanFlags | SCAN_NO_DEX, 0); 1527 1528 // Collected privileged system packages. 1529 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1530 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1531 | PackageParser.PARSE_IS_SYSTEM_DIR 1532 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1533 1534 // Collect ordinary system packages. 1535 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1536 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1537 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1538 1539 // Collect all vendor packages. 1540 File vendorAppDir = new File("/vendor/app"); 1541 try { 1542 vendorAppDir = vendorAppDir.getCanonicalFile(); 1543 } catch (IOException e) { 1544 // failed to look up canonical path, continue with original one 1545 } 1546 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1547 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1548 1549 // Collect all OEM packages. 1550 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1551 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1552 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1553 1554 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1555 mInstaller.moveFiles(); 1556 1557 // Prune any system packages that no longer exist. 1558 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1559 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1560 if (!mOnlyCore) { 1561 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1562 while (psit.hasNext()) { 1563 PackageSetting ps = psit.next(); 1564 1565 /* 1566 * If this is not a system app, it can't be a 1567 * disable system app. 1568 */ 1569 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1570 continue; 1571 } 1572 1573 /* 1574 * If the package is scanned, it's not erased. 1575 */ 1576 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1577 if (scannedPkg != null) { 1578 /* 1579 * If the system app is both scanned and in the 1580 * disabled packages list, then it must have been 1581 * added via OTA. Remove it from the currently 1582 * scanned package so the previously user-installed 1583 * application can be scanned. 1584 */ 1585 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1586 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1587 + ps.name + "; removing system app. Last known codePath=" 1588 + ps.codePathString + ", installStatus=" + ps.installStatus 1589 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1590 + scannedPkg.mVersionCode); 1591 removePackageLI(ps, true); 1592 expectingBetter.put(ps.name, ps.codePath); 1593 } 1594 1595 continue; 1596 } 1597 1598 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1599 psit.remove(); 1600 logCriticalInfo(Log.WARN, "System package " + ps.name 1601 + " no longer exists; wiping its data"); 1602 removeDataDirsLI(ps.name); 1603 } else { 1604 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1605 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1606 possiblyDeletedUpdatedSystemApps.add(ps.name); 1607 } 1608 } 1609 } 1610 } 1611 1612 //look for any incomplete package installations 1613 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1614 //clean up list 1615 for(int i = 0; i < deletePkgsList.size(); i++) { 1616 //clean up here 1617 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1618 } 1619 //delete tmp files 1620 deleteTempPackageFiles(); 1621 1622 // Remove any shared userIDs that have no associated packages 1623 mSettings.pruneSharedUsersLPw(); 1624 1625 if (!mOnlyCore) { 1626 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1627 SystemClock.uptimeMillis()); 1628 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1629 1630 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1631 scanFlags, 0); 1632 1633 /** 1634 * Remove disable package settings for any updated system 1635 * apps that were removed via an OTA. If they're not a 1636 * previously-updated app, remove them completely. 1637 * Otherwise, just revoke their system-level permissions. 1638 */ 1639 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1640 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1641 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1642 1643 String msg; 1644 if (deletedPkg == null) { 1645 msg = "Updated system package " + deletedAppName 1646 + " no longer exists; wiping its data"; 1647 removeDataDirsLI(deletedAppName); 1648 } else { 1649 msg = "Updated system app + " + deletedAppName 1650 + " no longer present; removing system privileges for " 1651 + deletedAppName; 1652 1653 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1654 1655 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1656 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1657 } 1658 logCriticalInfo(Log.WARN, msg); 1659 } 1660 1661 /** 1662 * Make sure all system apps that we expected to appear on 1663 * the userdata partition actually showed up. If they never 1664 * appeared, crawl back and revive the system version. 1665 */ 1666 for (int i = 0; i < expectingBetter.size(); i++) { 1667 final String packageName = expectingBetter.keyAt(i); 1668 if (!mPackages.containsKey(packageName)) { 1669 final File scanFile = expectingBetter.valueAt(i); 1670 1671 logCriticalInfo(Log.WARN, "Expected better " + packageName 1672 + " but never showed up; reverting to system"); 1673 1674 final int reparseFlags; 1675 if (FileUtils.contains(privilegedAppDir, scanFile)) { 1676 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1677 | PackageParser.PARSE_IS_SYSTEM_DIR 1678 | PackageParser.PARSE_IS_PRIVILEGED; 1679 } else if (FileUtils.contains(systemAppDir, scanFile)) { 1680 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1681 | PackageParser.PARSE_IS_SYSTEM_DIR; 1682 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 1683 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1684 | PackageParser.PARSE_IS_SYSTEM_DIR; 1685 } else if (FileUtils.contains(oemAppDir, scanFile)) { 1686 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1687 | PackageParser.PARSE_IS_SYSTEM_DIR; 1688 } else { 1689 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 1690 continue; 1691 } 1692 1693 mSettings.enableSystemPackageLPw(packageName); 1694 1695 try { 1696 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 1697 } catch (PackageManagerException e) { 1698 Slog.e(TAG, "Failed to parse original system package: " 1699 + e.getMessage()); 1700 } 1701 } 1702 } 1703 } 1704 1705 // Now that we know all of the shared libraries, update all clients to have 1706 // the correct library paths. 1707 updateAllSharedLibrariesLPw(); 1708 1709 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1710 // NOTE: We ignore potential failures here during a system scan (like 1711 // the rest of the commands above) because there's precious little we 1712 // can do about it. A settings error is reported, though. 1713 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1714 false /* force dexopt */, false /* defer dexopt */); 1715 } 1716 1717 // Now that we know all the packages we are keeping, 1718 // read and update their last usage times. 1719 mPackageUsage.readLP(); 1720 1721 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1722 SystemClock.uptimeMillis()); 1723 Slog.i(TAG, "Time to scan packages: " 1724 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1725 + " seconds"); 1726 1727 // If the platform SDK has changed since the last time we booted, 1728 // we need to re-grant app permission to catch any new ones that 1729 // appear. This is really a hack, and means that apps can in some 1730 // cases get permissions that the user didn't initially explicitly 1731 // allow... it would be nice to have some better way to handle 1732 // this situation. 1733 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1734 != mSdkVersion; 1735 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1736 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1737 + "; regranting permissions for internal storage"); 1738 mSettings.mInternalSdkPlatform = mSdkVersion; 1739 1740 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1741 | (regrantPermissions 1742 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1743 : 0)); 1744 1745 // If this is the first boot, and it is a normal boot, then 1746 // we need to initialize the default preferred apps. 1747 if (!mRestoredSettings && !onlyCore) { 1748 mSettings.readDefaultPreferredAppsLPw(this, 0); 1749 } 1750 1751 // If this is first boot after an OTA, and a normal boot, then 1752 // we need to clear code cache directories. 1753 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1754 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1755 for (String pkgName : mSettings.mPackages.keySet()) { 1756 deleteCodeCacheDirsLI(pkgName); 1757 } 1758 mSettings.mFingerprint = Build.FINGERPRINT; 1759 } 1760 1761 // All the changes are done during package scanning. 1762 mSettings.updateInternalDatabaseVersion(); 1763 1764 // can downgrade to reader 1765 mSettings.writeLPr(); 1766 1767 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1768 SystemClock.uptimeMillis()); 1769 1770 1771 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1772 } // synchronized (mPackages) 1773 } // synchronized (mInstallLock) 1774 1775 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1776 1777 // Now after opening every single application zip, make sure they 1778 // are all flushed. Not really needed, but keeps things nice and 1779 // tidy. 1780 Runtime.getRuntime().gc(); 1781 } 1782 1783 @Override 1784 public boolean isFirstBoot() { 1785 return !mRestoredSettings; 1786 } 1787 1788 @Override 1789 public boolean isOnlyCoreApps() { 1790 return mOnlyCore; 1791 } 1792 1793 private String getRequiredVerifierLPr() { 1794 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1795 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1796 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1797 1798 String requiredVerifier = null; 1799 1800 final int N = receivers.size(); 1801 for (int i = 0; i < N; i++) { 1802 final ResolveInfo info = receivers.get(i); 1803 1804 if (info.activityInfo == null) { 1805 continue; 1806 } 1807 1808 final String packageName = info.activityInfo.packageName; 1809 1810 final PackageSetting ps = mSettings.mPackages.get(packageName); 1811 if (ps == null) { 1812 continue; 1813 } 1814 1815 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1816 if (!gp.grantedPermissions 1817 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1818 continue; 1819 } 1820 1821 if (requiredVerifier != null) { 1822 throw new RuntimeException("There can be only one required verifier"); 1823 } 1824 1825 requiredVerifier = packageName; 1826 } 1827 1828 return requiredVerifier; 1829 } 1830 1831 @Override 1832 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1833 throws RemoteException { 1834 try { 1835 return super.onTransact(code, data, reply, flags); 1836 } catch (RuntimeException e) { 1837 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1838 Slog.wtf(TAG, "Package Manager Crash", e); 1839 } 1840 throw e; 1841 } 1842 } 1843 1844 void cleanupInstallFailedPackage(PackageSetting ps) { 1845 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 1846 1847 removeDataDirsLI(ps.name); 1848 if (ps.codePath != null) { 1849 if (ps.codePath.isDirectory()) { 1850 FileUtils.deleteContents(ps.codePath); 1851 } 1852 ps.codePath.delete(); 1853 } 1854 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 1855 if (ps.resourcePath.isDirectory()) { 1856 FileUtils.deleteContents(ps.resourcePath); 1857 } 1858 ps.resourcePath.delete(); 1859 } 1860 mSettings.removePackageLPw(ps.name); 1861 } 1862 1863 static int[] appendInts(int[] cur, int[] add) { 1864 if (add == null) return cur; 1865 if (cur == null) return add; 1866 final int N = add.length; 1867 for (int i=0; i<N; i++) { 1868 cur = appendInt(cur, add[i]); 1869 } 1870 return cur; 1871 } 1872 1873 static int[] removeInts(int[] cur, int[] rem) { 1874 if (rem == null) return cur; 1875 if (cur == null) return cur; 1876 final int N = rem.length; 1877 for (int i=0; i<N; i++) { 1878 cur = removeInt(cur, rem[i]); 1879 } 1880 return cur; 1881 } 1882 1883 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1884 if (!sUserManager.exists(userId)) return null; 1885 final PackageSetting ps = (PackageSetting) p.mExtras; 1886 if (ps == null) { 1887 return null; 1888 } 1889 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1890 final PackageUserState state = ps.readUserState(userId); 1891 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1892 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1893 state, userId); 1894 } 1895 1896 @Override 1897 public boolean isPackageAvailable(String packageName, int userId) { 1898 if (!sUserManager.exists(userId)) return false; 1899 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 1900 synchronized (mPackages) { 1901 PackageParser.Package p = mPackages.get(packageName); 1902 if (p != null) { 1903 final PackageSetting ps = (PackageSetting) p.mExtras; 1904 if (ps != null) { 1905 final PackageUserState state = ps.readUserState(userId); 1906 if (state != null) { 1907 return PackageParser.isAvailable(state); 1908 } 1909 } 1910 } 1911 } 1912 return false; 1913 } 1914 1915 @Override 1916 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1917 if (!sUserManager.exists(userId)) return null; 1918 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 1919 // reader 1920 synchronized (mPackages) { 1921 PackageParser.Package p = mPackages.get(packageName); 1922 if (DEBUG_PACKAGE_INFO) 1923 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1924 if (p != null) { 1925 return generatePackageInfo(p, flags, userId); 1926 } 1927 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1928 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1929 } 1930 } 1931 return null; 1932 } 1933 1934 @Override 1935 public String[] currentToCanonicalPackageNames(String[] names) { 1936 String[] out = new String[names.length]; 1937 // reader 1938 synchronized (mPackages) { 1939 for (int i=names.length-1; i>=0; i--) { 1940 PackageSetting ps = mSettings.mPackages.get(names[i]); 1941 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1942 } 1943 } 1944 return out; 1945 } 1946 1947 @Override 1948 public String[] canonicalToCurrentPackageNames(String[] names) { 1949 String[] out = new String[names.length]; 1950 // reader 1951 synchronized (mPackages) { 1952 for (int i=names.length-1; i>=0; i--) { 1953 String cur = mSettings.mRenamedPackages.get(names[i]); 1954 out[i] = cur != null ? cur : names[i]; 1955 } 1956 } 1957 return out; 1958 } 1959 1960 @Override 1961 public int getPackageUid(String packageName, int userId) { 1962 if (!sUserManager.exists(userId)) return -1; 1963 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 1964 // reader 1965 synchronized (mPackages) { 1966 PackageParser.Package p = mPackages.get(packageName); 1967 if(p != null) { 1968 return UserHandle.getUid(userId, p.applicationInfo.uid); 1969 } 1970 PackageSetting ps = mSettings.mPackages.get(packageName); 1971 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1972 return -1; 1973 } 1974 p = ps.pkg; 1975 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1976 } 1977 } 1978 1979 @Override 1980 public int[] getPackageGids(String packageName) { 1981 // reader 1982 synchronized (mPackages) { 1983 PackageParser.Package p = mPackages.get(packageName); 1984 if (DEBUG_PACKAGE_INFO) 1985 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1986 if (p != null) { 1987 final PackageSetting ps = (PackageSetting)p.mExtras; 1988 return ps.getGids(); 1989 } 1990 } 1991 // stupid thing to indicate an error. 1992 return new int[0]; 1993 } 1994 1995 static final PermissionInfo generatePermissionInfo( 1996 BasePermission bp, int flags) { 1997 if (bp.perm != null) { 1998 return PackageParser.generatePermissionInfo(bp.perm, flags); 1999 } 2000 PermissionInfo pi = new PermissionInfo(); 2001 pi.name = bp.name; 2002 pi.packageName = bp.sourcePackage; 2003 pi.nonLocalizedLabel = bp.name; 2004 pi.protectionLevel = bp.protectionLevel; 2005 return pi; 2006 } 2007 2008 @Override 2009 public PermissionInfo getPermissionInfo(String name, int flags) { 2010 // reader 2011 synchronized (mPackages) { 2012 final BasePermission p = mSettings.mPermissions.get(name); 2013 if (p != null) { 2014 return generatePermissionInfo(p, flags); 2015 } 2016 return null; 2017 } 2018 } 2019 2020 @Override 2021 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2022 // reader 2023 synchronized (mPackages) { 2024 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2025 for (BasePermission p : mSettings.mPermissions.values()) { 2026 if (group == null) { 2027 if (p.perm == null || p.perm.info.group == null) { 2028 out.add(generatePermissionInfo(p, flags)); 2029 } 2030 } else { 2031 if (p.perm != null && group.equals(p.perm.info.group)) { 2032 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2033 } 2034 } 2035 } 2036 2037 if (out.size() > 0) { 2038 return out; 2039 } 2040 return mPermissionGroups.containsKey(group) ? out : null; 2041 } 2042 } 2043 2044 @Override 2045 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2046 // reader 2047 synchronized (mPackages) { 2048 return PackageParser.generatePermissionGroupInfo( 2049 mPermissionGroups.get(name), flags); 2050 } 2051 } 2052 2053 @Override 2054 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2055 // reader 2056 synchronized (mPackages) { 2057 final int N = mPermissionGroups.size(); 2058 ArrayList<PermissionGroupInfo> out 2059 = new ArrayList<PermissionGroupInfo>(N); 2060 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2061 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2062 } 2063 return out; 2064 } 2065 } 2066 2067 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2068 int userId) { 2069 if (!sUserManager.exists(userId)) return null; 2070 PackageSetting ps = mSettings.mPackages.get(packageName); 2071 if (ps != null) { 2072 if (ps.pkg == null) { 2073 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2074 flags, userId); 2075 if (pInfo != null) { 2076 return pInfo.applicationInfo; 2077 } 2078 return null; 2079 } 2080 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2081 ps.readUserState(userId), userId); 2082 } 2083 return null; 2084 } 2085 2086 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2087 int userId) { 2088 if (!sUserManager.exists(userId)) return null; 2089 PackageSetting ps = mSettings.mPackages.get(packageName); 2090 if (ps != null) { 2091 PackageParser.Package pkg = ps.pkg; 2092 if (pkg == null) { 2093 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2094 return null; 2095 } 2096 // Only data remains, so we aren't worried about code paths 2097 pkg = new PackageParser.Package(packageName); 2098 pkg.applicationInfo.packageName = packageName; 2099 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2100 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2101 pkg.applicationInfo.dataDir = 2102 getDataPathForPackage(packageName, 0).getPath(); 2103 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2104 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2105 } 2106 return generatePackageInfo(pkg, flags, userId); 2107 } 2108 return null; 2109 } 2110 2111 @Override 2112 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2113 if (!sUserManager.exists(userId)) return null; 2114 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2115 // writer 2116 synchronized (mPackages) { 2117 PackageParser.Package p = mPackages.get(packageName); 2118 if (DEBUG_PACKAGE_INFO) Log.v( 2119 TAG, "getApplicationInfo " + packageName 2120 + ": " + p); 2121 if (p != null) { 2122 PackageSetting ps = mSettings.mPackages.get(packageName); 2123 if (ps == null) return null; 2124 // Note: isEnabledLP() does not apply here - always return info 2125 return PackageParser.generateApplicationInfo( 2126 p, flags, ps.readUserState(userId), userId); 2127 } 2128 if ("android".equals(packageName)||"system".equals(packageName)) { 2129 return mAndroidApplication; 2130 } 2131 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2132 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2133 } 2134 } 2135 return null; 2136 } 2137 2138 2139 @Override 2140 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2141 mContext.enforceCallingOrSelfPermission( 2142 android.Manifest.permission.CLEAR_APP_CACHE, null); 2143 // Queue up an async operation since clearing cache may take a little while. 2144 mHandler.post(new Runnable() { 2145 public void run() { 2146 mHandler.removeCallbacks(this); 2147 int retCode = -1; 2148 synchronized (mInstallLock) { 2149 retCode = mInstaller.freeCache(freeStorageSize); 2150 if (retCode < 0) { 2151 Slog.w(TAG, "Couldn't clear application caches"); 2152 } 2153 } 2154 if (observer != null) { 2155 try { 2156 observer.onRemoveCompleted(null, (retCode >= 0)); 2157 } catch (RemoteException e) { 2158 Slog.w(TAG, "RemoveException when invoking call back"); 2159 } 2160 } 2161 } 2162 }); 2163 } 2164 2165 @Override 2166 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2167 mContext.enforceCallingOrSelfPermission( 2168 android.Manifest.permission.CLEAR_APP_CACHE, null); 2169 // Queue up an async operation since clearing cache may take a little while. 2170 mHandler.post(new Runnable() { 2171 public void run() { 2172 mHandler.removeCallbacks(this); 2173 int retCode = -1; 2174 synchronized (mInstallLock) { 2175 retCode = mInstaller.freeCache(freeStorageSize); 2176 if (retCode < 0) { 2177 Slog.w(TAG, "Couldn't clear application caches"); 2178 } 2179 } 2180 if(pi != null) { 2181 try { 2182 // Callback via pending intent 2183 int code = (retCode >= 0) ? 1 : 0; 2184 pi.sendIntent(null, code, null, 2185 null, null); 2186 } catch (SendIntentException e1) { 2187 Slog.i(TAG, "Failed to send pending intent"); 2188 } 2189 } 2190 } 2191 }); 2192 } 2193 2194 void freeStorage(long freeStorageSize) throws IOException { 2195 synchronized (mInstallLock) { 2196 if (mInstaller.freeCache(freeStorageSize) < 0) { 2197 throw new IOException("Failed to free enough space"); 2198 } 2199 } 2200 } 2201 2202 @Override 2203 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2204 if (!sUserManager.exists(userId)) return null; 2205 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2206 synchronized (mPackages) { 2207 PackageParser.Activity a = mActivities.mActivities.get(component); 2208 2209 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2210 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2211 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2212 if (ps == null) return null; 2213 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2214 userId); 2215 } 2216 if (mResolveComponentName.equals(component)) { 2217 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2218 new PackageUserState(), userId); 2219 } 2220 } 2221 return null; 2222 } 2223 2224 @Override 2225 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2226 String resolvedType) { 2227 synchronized (mPackages) { 2228 PackageParser.Activity a = mActivities.mActivities.get(component); 2229 if (a == null) { 2230 return false; 2231 } 2232 for (int i=0; i<a.intents.size(); i++) { 2233 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2234 intent.getData(), intent.getCategories(), TAG) >= 0) { 2235 return true; 2236 } 2237 } 2238 return false; 2239 } 2240 } 2241 2242 @Override 2243 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2244 if (!sUserManager.exists(userId)) return null; 2245 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2246 synchronized (mPackages) { 2247 PackageParser.Activity a = mReceivers.mActivities.get(component); 2248 if (DEBUG_PACKAGE_INFO) Log.v( 2249 TAG, "getReceiverInfo " + component + ": " + a); 2250 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2251 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2252 if (ps == null) return null; 2253 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2254 userId); 2255 } 2256 } 2257 return null; 2258 } 2259 2260 @Override 2261 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2262 if (!sUserManager.exists(userId)) return null; 2263 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2264 synchronized (mPackages) { 2265 PackageParser.Service s = mServices.mServices.get(component); 2266 if (DEBUG_PACKAGE_INFO) Log.v( 2267 TAG, "getServiceInfo " + component + ": " + s); 2268 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2269 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2270 if (ps == null) return null; 2271 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2272 userId); 2273 } 2274 } 2275 return null; 2276 } 2277 2278 @Override 2279 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2280 if (!sUserManager.exists(userId)) return null; 2281 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2282 synchronized (mPackages) { 2283 PackageParser.Provider p = mProviders.mProviders.get(component); 2284 if (DEBUG_PACKAGE_INFO) Log.v( 2285 TAG, "getProviderInfo " + component + ": " + p); 2286 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2287 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2288 if (ps == null) return null; 2289 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2290 userId); 2291 } 2292 } 2293 return null; 2294 } 2295 2296 @Override 2297 public String[] getSystemSharedLibraryNames() { 2298 Set<String> libSet; 2299 synchronized (mPackages) { 2300 libSet = mSharedLibraries.keySet(); 2301 int size = libSet.size(); 2302 if (size > 0) { 2303 String[] libs = new String[size]; 2304 libSet.toArray(libs); 2305 return libs; 2306 } 2307 } 2308 return null; 2309 } 2310 2311 @Override 2312 public FeatureInfo[] getSystemAvailableFeatures() { 2313 Collection<FeatureInfo> featSet; 2314 synchronized (mPackages) { 2315 featSet = mAvailableFeatures.values(); 2316 int size = featSet.size(); 2317 if (size > 0) { 2318 FeatureInfo[] features = new FeatureInfo[size+1]; 2319 featSet.toArray(features); 2320 FeatureInfo fi = new FeatureInfo(); 2321 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2322 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2323 features[size] = fi; 2324 return features; 2325 } 2326 } 2327 return null; 2328 } 2329 2330 @Override 2331 public boolean hasSystemFeature(String name) { 2332 synchronized (mPackages) { 2333 return mAvailableFeatures.containsKey(name); 2334 } 2335 } 2336 2337 private void checkValidCaller(int uid, int userId) { 2338 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2339 return; 2340 2341 throw new SecurityException("Caller uid=" + uid 2342 + " is not privileged to communicate with user=" + userId); 2343 } 2344 2345 @Override 2346 public int checkPermission(String permName, String pkgName) { 2347 synchronized (mPackages) { 2348 PackageParser.Package p = mPackages.get(pkgName); 2349 if (p != null && p.mExtras != null) { 2350 PackageSetting ps = (PackageSetting)p.mExtras; 2351 if (ps.sharedUser != null) { 2352 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2353 return PackageManager.PERMISSION_GRANTED; 2354 } 2355 } else if (ps.grantedPermissions.contains(permName)) { 2356 return PackageManager.PERMISSION_GRANTED; 2357 } 2358 } 2359 } 2360 return PackageManager.PERMISSION_DENIED; 2361 } 2362 2363 @Override 2364 public int checkUidPermission(String permName, int uid) { 2365 synchronized (mPackages) { 2366 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2367 if (obj != null) { 2368 GrantedPermissions gp = (GrantedPermissions)obj; 2369 if (gp.grantedPermissions.contains(permName)) { 2370 return PackageManager.PERMISSION_GRANTED; 2371 } 2372 } else { 2373 HashSet<String> perms = mSystemPermissions.get(uid); 2374 if (perms != null && perms.contains(permName)) { 2375 return PackageManager.PERMISSION_GRANTED; 2376 } 2377 } 2378 } 2379 return PackageManager.PERMISSION_DENIED; 2380 } 2381 2382 /** 2383 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2384 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2385 * @param checkShell TODO(yamasani): 2386 * @param message the message to log on security exception 2387 */ 2388 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2389 boolean checkShell, String message) { 2390 if (userId < 0) { 2391 throw new IllegalArgumentException("Invalid userId " + userId); 2392 } 2393 if (checkShell) { 2394 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2395 } 2396 if (userId == UserHandle.getUserId(callingUid)) return; 2397 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2398 if (requireFullPermission) { 2399 mContext.enforceCallingOrSelfPermission( 2400 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2401 } else { 2402 try { 2403 mContext.enforceCallingOrSelfPermission( 2404 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2405 } catch (SecurityException se) { 2406 mContext.enforceCallingOrSelfPermission( 2407 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2408 } 2409 } 2410 } 2411 } 2412 2413 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2414 if (callingUid == Process.SHELL_UID) { 2415 if (userHandle >= 0 2416 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2417 throw new SecurityException("Shell does not have permission to access user " 2418 + userHandle); 2419 } else if (userHandle < 0) { 2420 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2421 + Debug.getCallers(3)); 2422 } 2423 } 2424 } 2425 2426 private BasePermission findPermissionTreeLP(String permName) { 2427 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2428 if (permName.startsWith(bp.name) && 2429 permName.length() > bp.name.length() && 2430 permName.charAt(bp.name.length()) == '.') { 2431 return bp; 2432 } 2433 } 2434 return null; 2435 } 2436 2437 private BasePermission checkPermissionTreeLP(String permName) { 2438 if (permName != null) { 2439 BasePermission bp = findPermissionTreeLP(permName); 2440 if (bp != null) { 2441 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2442 return bp; 2443 } 2444 throw new SecurityException("Calling uid " 2445 + Binder.getCallingUid() 2446 + " is not allowed to add to permission tree " 2447 + bp.name + " owned by uid " + bp.uid); 2448 } 2449 } 2450 throw new SecurityException("No permission tree found for " + permName); 2451 } 2452 2453 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2454 if (s1 == null) { 2455 return s2 == null; 2456 } 2457 if (s2 == null) { 2458 return false; 2459 } 2460 if (s1.getClass() != s2.getClass()) { 2461 return false; 2462 } 2463 return s1.equals(s2); 2464 } 2465 2466 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2467 if (pi1.icon != pi2.icon) return false; 2468 if (pi1.logo != pi2.logo) return false; 2469 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2470 if (!compareStrings(pi1.name, pi2.name)) return false; 2471 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2472 // We'll take care of setting this one. 2473 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2474 // These are not currently stored in settings. 2475 //if (!compareStrings(pi1.group, pi2.group)) return false; 2476 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2477 //if (pi1.labelRes != pi2.labelRes) return false; 2478 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2479 return true; 2480 } 2481 2482 int permissionInfoFootprint(PermissionInfo info) { 2483 int size = info.name.length(); 2484 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2485 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2486 return size; 2487 } 2488 2489 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2490 int size = 0; 2491 for (BasePermission perm : mSettings.mPermissions.values()) { 2492 if (perm.uid == tree.uid) { 2493 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2494 } 2495 } 2496 return size; 2497 } 2498 2499 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2500 // We calculate the max size of permissions defined by this uid and throw 2501 // if that plus the size of 'info' would exceed our stated maximum. 2502 if (tree.uid != Process.SYSTEM_UID) { 2503 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2504 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2505 throw new SecurityException("Permission tree size cap exceeded"); 2506 } 2507 } 2508 } 2509 2510 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2511 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2512 throw new SecurityException("Label must be specified in permission"); 2513 } 2514 BasePermission tree = checkPermissionTreeLP(info.name); 2515 BasePermission bp = mSettings.mPermissions.get(info.name); 2516 boolean added = bp == null; 2517 boolean changed = true; 2518 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2519 if (added) { 2520 enforcePermissionCapLocked(info, tree); 2521 bp = new BasePermission(info.name, tree.sourcePackage, 2522 BasePermission.TYPE_DYNAMIC); 2523 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2524 throw new SecurityException( 2525 "Not allowed to modify non-dynamic permission " 2526 + info.name); 2527 } else { 2528 if (bp.protectionLevel == fixedLevel 2529 && bp.perm.owner.equals(tree.perm.owner) 2530 && bp.uid == tree.uid 2531 && comparePermissionInfos(bp.perm.info, info)) { 2532 changed = false; 2533 } 2534 } 2535 bp.protectionLevel = fixedLevel; 2536 info = new PermissionInfo(info); 2537 info.protectionLevel = fixedLevel; 2538 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2539 bp.perm.info.packageName = tree.perm.info.packageName; 2540 bp.uid = tree.uid; 2541 if (added) { 2542 mSettings.mPermissions.put(info.name, bp); 2543 } 2544 if (changed) { 2545 if (!async) { 2546 mSettings.writeLPr(); 2547 } else { 2548 scheduleWriteSettingsLocked(); 2549 } 2550 } 2551 return added; 2552 } 2553 2554 @Override 2555 public boolean addPermission(PermissionInfo info) { 2556 synchronized (mPackages) { 2557 return addPermissionLocked(info, false); 2558 } 2559 } 2560 2561 @Override 2562 public boolean addPermissionAsync(PermissionInfo info) { 2563 synchronized (mPackages) { 2564 return addPermissionLocked(info, true); 2565 } 2566 } 2567 2568 @Override 2569 public void removePermission(String name) { 2570 synchronized (mPackages) { 2571 checkPermissionTreeLP(name); 2572 BasePermission bp = mSettings.mPermissions.get(name); 2573 if (bp != null) { 2574 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2575 throw new SecurityException( 2576 "Not allowed to modify non-dynamic permission " 2577 + name); 2578 } 2579 mSettings.mPermissions.remove(name); 2580 mSettings.writeLPr(); 2581 } 2582 } 2583 } 2584 2585 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2586 int index = pkg.requestedPermissions.indexOf(bp.name); 2587 if (index == -1) { 2588 throw new SecurityException("Package " + pkg.packageName 2589 + " has not requested permission " + bp.name); 2590 } 2591 boolean isNormal = 2592 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2593 == PermissionInfo.PROTECTION_NORMAL); 2594 boolean isDangerous = 2595 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2596 == PermissionInfo.PROTECTION_DANGEROUS); 2597 boolean isDevelopment = 2598 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2599 2600 if (!isNormal && !isDangerous && !isDevelopment) { 2601 throw new SecurityException("Permission " + bp.name 2602 + " is not a changeable permission type"); 2603 } 2604 2605 if (isNormal || isDangerous) { 2606 if (pkg.requestedPermissionsRequired.get(index)) { 2607 throw new SecurityException("Can't change " + bp.name 2608 + ". It is required by the application"); 2609 } 2610 } 2611 } 2612 2613 @Override 2614 public void grantPermission(String packageName, String permissionName) { 2615 mContext.enforceCallingOrSelfPermission( 2616 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2617 synchronized (mPackages) { 2618 final PackageParser.Package pkg = mPackages.get(packageName); 2619 if (pkg == null) { 2620 throw new IllegalArgumentException("Unknown package: " + packageName); 2621 } 2622 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2623 if (bp == null) { 2624 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2625 } 2626 2627 checkGrantRevokePermissions(pkg, bp); 2628 2629 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2630 if (ps == null) { 2631 return; 2632 } 2633 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2634 if (gp.grantedPermissions.add(permissionName)) { 2635 if (ps.haveGids) { 2636 gp.gids = appendInts(gp.gids, bp.gids); 2637 } 2638 mSettings.writeLPr(); 2639 } 2640 } 2641 } 2642 2643 @Override 2644 public void revokePermission(String packageName, String permissionName) { 2645 int changedAppId = -1; 2646 2647 synchronized (mPackages) { 2648 final PackageParser.Package pkg = mPackages.get(packageName); 2649 if (pkg == null) { 2650 throw new IllegalArgumentException("Unknown package: " + packageName); 2651 } 2652 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2653 mContext.enforceCallingOrSelfPermission( 2654 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2655 } 2656 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2657 if (bp == null) { 2658 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2659 } 2660 2661 checkGrantRevokePermissions(pkg, bp); 2662 2663 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2664 if (ps == null) { 2665 return; 2666 } 2667 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2668 if (gp.grantedPermissions.remove(permissionName)) { 2669 gp.grantedPermissions.remove(permissionName); 2670 if (ps.haveGids) { 2671 gp.gids = removeInts(gp.gids, bp.gids); 2672 } 2673 mSettings.writeLPr(); 2674 changedAppId = ps.appId; 2675 } 2676 } 2677 2678 if (changedAppId >= 0) { 2679 // We changed the perm on someone, kill its processes. 2680 IActivityManager am = ActivityManagerNative.getDefault(); 2681 if (am != null) { 2682 final int callingUserId = UserHandle.getCallingUserId(); 2683 final long ident = Binder.clearCallingIdentity(); 2684 try { 2685 //XXX we should only revoke for the calling user's app permissions, 2686 // but for now we impact all users. 2687 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2688 // "revoke " + permissionName); 2689 int[] users = sUserManager.getUserIds(); 2690 for (int user : users) { 2691 am.killUid(UserHandle.getUid(user, changedAppId), 2692 "revoke " + permissionName); 2693 } 2694 } catch (RemoteException e) { 2695 } finally { 2696 Binder.restoreCallingIdentity(ident); 2697 } 2698 } 2699 } 2700 } 2701 2702 @Override 2703 public boolean isProtectedBroadcast(String actionName) { 2704 synchronized (mPackages) { 2705 return mProtectedBroadcasts.contains(actionName); 2706 } 2707 } 2708 2709 @Override 2710 public int checkSignatures(String pkg1, String pkg2) { 2711 synchronized (mPackages) { 2712 final PackageParser.Package p1 = mPackages.get(pkg1); 2713 final PackageParser.Package p2 = mPackages.get(pkg2); 2714 if (p1 == null || p1.mExtras == null 2715 || p2 == null || p2.mExtras == null) { 2716 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2717 } 2718 return compareSignatures(p1.mSignatures, p2.mSignatures); 2719 } 2720 } 2721 2722 @Override 2723 public int checkUidSignatures(int uid1, int uid2) { 2724 // Map to base uids. 2725 uid1 = UserHandle.getAppId(uid1); 2726 uid2 = UserHandle.getAppId(uid2); 2727 // reader 2728 synchronized (mPackages) { 2729 Signature[] s1; 2730 Signature[] s2; 2731 Object obj = mSettings.getUserIdLPr(uid1); 2732 if (obj != null) { 2733 if (obj instanceof SharedUserSetting) { 2734 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2735 } else if (obj instanceof PackageSetting) { 2736 s1 = ((PackageSetting)obj).signatures.mSignatures; 2737 } else { 2738 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2739 } 2740 } else { 2741 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2742 } 2743 obj = mSettings.getUserIdLPr(uid2); 2744 if (obj != null) { 2745 if (obj instanceof SharedUserSetting) { 2746 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2747 } else if (obj instanceof PackageSetting) { 2748 s2 = ((PackageSetting)obj).signatures.mSignatures; 2749 } else { 2750 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2751 } 2752 } else { 2753 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2754 } 2755 return compareSignatures(s1, s2); 2756 } 2757 } 2758 2759 /** 2760 * Compares two sets of signatures. Returns: 2761 * <br /> 2762 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2763 * <br /> 2764 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2765 * <br /> 2766 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2767 * <br /> 2768 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2769 * <br /> 2770 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2771 */ 2772 static int compareSignatures(Signature[] s1, Signature[] s2) { 2773 if (s1 == null) { 2774 return s2 == null 2775 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2776 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2777 } 2778 2779 if (s2 == null) { 2780 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2781 } 2782 2783 if (s1.length != s2.length) { 2784 return PackageManager.SIGNATURE_NO_MATCH; 2785 } 2786 2787 // Since both signature sets are of size 1, we can compare without HashSets. 2788 if (s1.length == 1) { 2789 return s1[0].equals(s2[0]) ? 2790 PackageManager.SIGNATURE_MATCH : 2791 PackageManager.SIGNATURE_NO_MATCH; 2792 } 2793 2794 HashSet<Signature> set1 = new HashSet<Signature>(); 2795 for (Signature sig : s1) { 2796 set1.add(sig); 2797 } 2798 HashSet<Signature> set2 = new HashSet<Signature>(); 2799 for (Signature sig : s2) { 2800 set2.add(sig); 2801 } 2802 // Make sure s2 contains all signatures in s1. 2803 if (set1.equals(set2)) { 2804 return PackageManager.SIGNATURE_MATCH; 2805 } 2806 return PackageManager.SIGNATURE_NO_MATCH; 2807 } 2808 2809 /** 2810 * If the database version for this type of package (internal storage or 2811 * external storage) is less than the version where package signatures 2812 * were updated, return true. 2813 */ 2814 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2815 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2816 DatabaseVersion.SIGNATURE_END_ENTITY)) 2817 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2818 DatabaseVersion.SIGNATURE_END_ENTITY)); 2819 } 2820 2821 /** 2822 * Used for backward compatibility to make sure any packages with 2823 * certificate chains get upgraded to the new style. {@code existingSigs} 2824 * will be in the old format (since they were stored on disk from before the 2825 * system upgrade) and {@code scannedSigs} will be in the newer format. 2826 */ 2827 private int compareSignaturesCompat(PackageSignatures existingSigs, 2828 PackageParser.Package scannedPkg) { 2829 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2830 return PackageManager.SIGNATURE_NO_MATCH; 2831 } 2832 2833 HashSet<Signature> existingSet = new HashSet<Signature>(); 2834 for (Signature sig : existingSigs.mSignatures) { 2835 existingSet.add(sig); 2836 } 2837 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2838 for (Signature sig : scannedPkg.mSignatures) { 2839 try { 2840 Signature[] chainSignatures = sig.getChainSignatures(); 2841 for (Signature chainSig : chainSignatures) { 2842 scannedCompatSet.add(chainSig); 2843 } 2844 } catch (CertificateEncodingException e) { 2845 scannedCompatSet.add(sig); 2846 } 2847 } 2848 /* 2849 * Make sure the expanded scanned set contains all signatures in the 2850 * existing one. 2851 */ 2852 if (scannedCompatSet.equals(existingSet)) { 2853 // Migrate the old signatures to the new scheme. 2854 existingSigs.assignSignatures(scannedPkg.mSignatures); 2855 // The new KeySets will be re-added later in the scanning process. 2856 synchronized (mPackages) { 2857 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2858 } 2859 return PackageManager.SIGNATURE_MATCH; 2860 } 2861 return PackageManager.SIGNATURE_NO_MATCH; 2862 } 2863 2864 @Override 2865 public String[] getPackagesForUid(int uid) { 2866 uid = UserHandle.getAppId(uid); 2867 // reader 2868 synchronized (mPackages) { 2869 Object obj = mSettings.getUserIdLPr(uid); 2870 if (obj instanceof SharedUserSetting) { 2871 final SharedUserSetting sus = (SharedUserSetting) obj; 2872 final int N = sus.packages.size(); 2873 final String[] res = new String[N]; 2874 final Iterator<PackageSetting> it = sus.packages.iterator(); 2875 int i = 0; 2876 while (it.hasNext()) { 2877 res[i++] = it.next().name; 2878 } 2879 return res; 2880 } else if (obj instanceof PackageSetting) { 2881 final PackageSetting ps = (PackageSetting) obj; 2882 return new String[] { ps.name }; 2883 } 2884 } 2885 return null; 2886 } 2887 2888 @Override 2889 public String getNameForUid(int uid) { 2890 // reader 2891 synchronized (mPackages) { 2892 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2893 if (obj instanceof SharedUserSetting) { 2894 final SharedUserSetting sus = (SharedUserSetting) obj; 2895 return sus.name + ":" + sus.userId; 2896 } else if (obj instanceof PackageSetting) { 2897 final PackageSetting ps = (PackageSetting) obj; 2898 return ps.name; 2899 } 2900 } 2901 return null; 2902 } 2903 2904 @Override 2905 public int getUidForSharedUser(String sharedUserName) { 2906 if(sharedUserName == null) { 2907 return -1; 2908 } 2909 // reader 2910 synchronized (mPackages) { 2911 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 2912 if (suid == null) { 2913 return -1; 2914 } 2915 return suid.userId; 2916 } 2917 } 2918 2919 @Override 2920 public int getFlagsForUid(int uid) { 2921 synchronized (mPackages) { 2922 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2923 if (obj instanceof SharedUserSetting) { 2924 final SharedUserSetting sus = (SharedUserSetting) obj; 2925 return sus.pkgFlags; 2926 } else if (obj instanceof PackageSetting) { 2927 final PackageSetting ps = (PackageSetting) obj; 2928 return ps.pkgFlags; 2929 } 2930 } 2931 return 0; 2932 } 2933 2934 @Override 2935 public int getPrivateFlagsForUid(int uid) { 2936 synchronized (mPackages) { 2937 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2938 if (obj instanceof SharedUserSetting) { 2939 final SharedUserSetting sus = (SharedUserSetting) obj; 2940 return sus.pkgPrivateFlags; 2941 } else if (obj instanceof PackageSetting) { 2942 final PackageSetting ps = (PackageSetting) obj; 2943 return ps.pkgPrivateFlags; 2944 } 2945 } 2946 return 0; 2947 } 2948 2949 @Override 2950 public boolean isUidPrivileged(int uid) { 2951 uid = UserHandle.getAppId(uid); 2952 // reader 2953 synchronized (mPackages) { 2954 Object obj = mSettings.getUserIdLPr(uid); 2955 if (obj instanceof SharedUserSetting) { 2956 final SharedUserSetting sus = (SharedUserSetting) obj; 2957 final Iterator<PackageSetting> it = sus.packages.iterator(); 2958 while (it.hasNext()) { 2959 if (it.next().isPrivileged()) { 2960 return true; 2961 } 2962 } 2963 } else if (obj instanceof PackageSetting) { 2964 final PackageSetting ps = (PackageSetting) obj; 2965 return ps.isPrivileged(); 2966 } 2967 } 2968 return false; 2969 } 2970 2971 @Override 2972 public String[] getAppOpPermissionPackages(String permissionName) { 2973 synchronized (mPackages) { 2974 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 2975 if (pkgs == null) { 2976 return null; 2977 } 2978 return pkgs.toArray(new String[pkgs.size()]); 2979 } 2980 } 2981 2982 @Override 2983 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2984 int flags, int userId) { 2985 if (!sUserManager.exists(userId)) return null; 2986 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 2987 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2988 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2989 } 2990 2991 @Override 2992 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2993 IntentFilter filter, int match, ComponentName activity) { 2994 final int userId = UserHandle.getCallingUserId(); 2995 if (DEBUG_PREFERRED) { 2996 Log.v(TAG, "setLastChosenActivity intent=" + intent 2997 + " resolvedType=" + resolvedType 2998 + " flags=" + flags 2999 + " filter=" + filter 3000 + " match=" + match 3001 + " activity=" + activity); 3002 filter.dump(new PrintStreamPrinter(System.out), " "); 3003 } 3004 intent.setComponent(null); 3005 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3006 // Find any earlier preferred or last chosen entries and nuke them 3007 findPreferredActivity(intent, resolvedType, 3008 flags, query, 0, false, true, false, userId); 3009 // Add the new activity as the last chosen for this filter 3010 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3011 "Setting last chosen"); 3012 } 3013 3014 @Override 3015 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3016 final int userId = UserHandle.getCallingUserId(); 3017 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3018 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3019 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3020 false, false, false, userId); 3021 } 3022 3023 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3024 int flags, List<ResolveInfo> query, int userId) { 3025 if (query != null) { 3026 final int N = query.size(); 3027 if (N == 1) { 3028 return query.get(0); 3029 } else if (N > 1) { 3030 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3031 // If there is more than one activity with the same priority, 3032 // then let the user decide between them. 3033 ResolveInfo r0 = query.get(0); 3034 ResolveInfo r1 = query.get(1); 3035 if (DEBUG_INTENT_MATCHING || debug) { 3036 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3037 + r1.activityInfo.name + "=" + r1.priority); 3038 } 3039 // If the first activity has a higher priority, or a different 3040 // default, then it is always desireable to pick it. 3041 if (r0.priority != r1.priority 3042 || r0.preferredOrder != r1.preferredOrder 3043 || r0.isDefault != r1.isDefault) { 3044 return query.get(0); 3045 } 3046 // If we have saved a preference for a preferred activity for 3047 // this Intent, use that. 3048 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3049 flags, query, r0.priority, true, false, debug, userId); 3050 if (ri != null) { 3051 return ri; 3052 } 3053 if (userId != 0) { 3054 ri = new ResolveInfo(mResolveInfo); 3055 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3056 ri.activityInfo.applicationInfo = new ApplicationInfo( 3057 ri.activityInfo.applicationInfo); 3058 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3059 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3060 return ri; 3061 } 3062 return mResolveInfo; 3063 } 3064 } 3065 return null; 3066 } 3067 3068 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3069 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3070 final int N = query.size(); 3071 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3072 .get(userId); 3073 // Get the list of persistent preferred activities that handle the intent 3074 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3075 List<PersistentPreferredActivity> pprefs = ppir != null 3076 ? ppir.queryIntent(intent, resolvedType, 3077 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3078 : null; 3079 if (pprefs != null && pprefs.size() > 0) { 3080 final int M = pprefs.size(); 3081 for (int i=0; i<M; i++) { 3082 final PersistentPreferredActivity ppa = pprefs.get(i); 3083 if (DEBUG_PREFERRED || debug) { 3084 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3085 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3086 + "\n component=" + ppa.mComponent); 3087 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3088 } 3089 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3090 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3091 if (DEBUG_PREFERRED || debug) { 3092 Slog.v(TAG, "Found persistent preferred activity:"); 3093 if (ai != null) { 3094 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3095 } else { 3096 Slog.v(TAG, " null"); 3097 } 3098 } 3099 if (ai == null) { 3100 // This previously registered persistent preferred activity 3101 // component is no longer known. Ignore it and do NOT remove it. 3102 continue; 3103 } 3104 for (int j=0; j<N; j++) { 3105 final ResolveInfo ri = query.get(j); 3106 if (!ri.activityInfo.applicationInfo.packageName 3107 .equals(ai.applicationInfo.packageName)) { 3108 continue; 3109 } 3110 if (!ri.activityInfo.name.equals(ai.name)) { 3111 continue; 3112 } 3113 // Found a persistent preference that can handle the intent. 3114 if (DEBUG_PREFERRED || debug) { 3115 Slog.v(TAG, "Returning persistent preferred activity: " + 3116 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3117 } 3118 return ri; 3119 } 3120 } 3121 } 3122 return null; 3123 } 3124 3125 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3126 List<ResolveInfo> query, int priority, boolean always, 3127 boolean removeMatches, boolean debug, int userId) { 3128 if (!sUserManager.exists(userId)) return null; 3129 // writer 3130 synchronized (mPackages) { 3131 if (intent.getSelector() != null) { 3132 intent = intent.getSelector(); 3133 } 3134 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3135 3136 // Try to find a matching persistent preferred activity. 3137 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3138 debug, userId); 3139 3140 // If a persistent preferred activity matched, use it. 3141 if (pri != null) { 3142 return pri; 3143 } 3144 3145 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3146 // Get the list of preferred activities that handle the intent 3147 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3148 List<PreferredActivity> prefs = pir != null 3149 ? pir.queryIntent(intent, resolvedType, 3150 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3151 : null; 3152 if (prefs != null && prefs.size() > 0) { 3153 boolean changed = false; 3154 try { 3155 // First figure out how good the original match set is. 3156 // We will only allow preferred activities that came 3157 // from the same match quality. 3158 int match = 0; 3159 3160 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3161 3162 final int N = query.size(); 3163 for (int j=0; j<N; j++) { 3164 final ResolveInfo ri = query.get(j); 3165 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3166 + ": 0x" + Integer.toHexString(match)); 3167 if (ri.match > match) { 3168 match = ri.match; 3169 } 3170 } 3171 3172 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3173 + Integer.toHexString(match)); 3174 3175 match &= IntentFilter.MATCH_CATEGORY_MASK; 3176 final int M = prefs.size(); 3177 for (int i=0; i<M; i++) { 3178 final PreferredActivity pa = prefs.get(i); 3179 if (DEBUG_PREFERRED || debug) { 3180 Slog.v(TAG, "Checking PreferredActivity ds=" 3181 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3182 + "\n component=" + pa.mPref.mComponent); 3183 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3184 } 3185 if (pa.mPref.mMatch != match) { 3186 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3187 + Integer.toHexString(pa.mPref.mMatch)); 3188 continue; 3189 } 3190 // If it's not an "always" type preferred activity and that's what we're 3191 // looking for, skip it. 3192 if (always && !pa.mPref.mAlways) { 3193 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3194 continue; 3195 } 3196 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3197 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3198 if (DEBUG_PREFERRED || debug) { 3199 Slog.v(TAG, "Found preferred activity:"); 3200 if (ai != null) { 3201 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3202 } else { 3203 Slog.v(TAG, " null"); 3204 } 3205 } 3206 if (ai == null) { 3207 // This previously registered preferred activity 3208 // component is no longer known. Most likely an update 3209 // to the app was installed and in the new version this 3210 // component no longer exists. Clean it up by removing 3211 // it from the preferred activities list, and skip it. 3212 Slog.w(TAG, "Removing dangling preferred activity: " 3213 + pa.mPref.mComponent); 3214 pir.removeFilter(pa); 3215 changed = true; 3216 continue; 3217 } 3218 for (int j=0; j<N; j++) { 3219 final ResolveInfo ri = query.get(j); 3220 if (!ri.activityInfo.applicationInfo.packageName 3221 .equals(ai.applicationInfo.packageName)) { 3222 continue; 3223 } 3224 if (!ri.activityInfo.name.equals(ai.name)) { 3225 continue; 3226 } 3227 3228 if (removeMatches) { 3229 pir.removeFilter(pa); 3230 changed = true; 3231 if (DEBUG_PREFERRED) { 3232 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3233 } 3234 break; 3235 } 3236 3237 // Okay we found a previously set preferred or last chosen app. 3238 // If the result set is different from when this 3239 // was created, we need to clear it and re-ask the 3240 // user their preference, if we're looking for an "always" type entry. 3241 if (always && !pa.mPref.sameSet(query, priority)) { 3242 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3243 + intent + " type " + resolvedType); 3244 if (DEBUG_PREFERRED) { 3245 Slog.v(TAG, "Removing preferred activity since set changed " 3246 + pa.mPref.mComponent); 3247 } 3248 pir.removeFilter(pa); 3249 // Re-add the filter as a "last chosen" entry (!always) 3250 PreferredActivity lastChosen = new PreferredActivity( 3251 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3252 pir.addFilter(lastChosen); 3253 changed = true; 3254 return null; 3255 } 3256 3257 // Yay! Either the set matched or we're looking for the last chosen 3258 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3259 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3260 return ri; 3261 } 3262 } 3263 } finally { 3264 if (changed) { 3265 if (DEBUG_PREFERRED) { 3266 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3267 } 3268 mSettings.writePackageRestrictionsLPr(userId); 3269 } 3270 } 3271 } 3272 } 3273 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3274 return null; 3275 } 3276 3277 /* 3278 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3279 */ 3280 @Override 3281 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3282 int targetUserId) { 3283 mContext.enforceCallingOrSelfPermission( 3284 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3285 List<CrossProfileIntentFilter> matches = 3286 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3287 if (matches != null) { 3288 int size = matches.size(); 3289 for (int i = 0; i < size; i++) { 3290 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3291 } 3292 } 3293 return false; 3294 } 3295 3296 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3297 String resolvedType, int userId) { 3298 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3299 if (resolver != null) { 3300 return resolver.queryIntent(intent, resolvedType, false, userId); 3301 } 3302 return null; 3303 } 3304 3305 @Override 3306 public List<ResolveInfo> queryIntentActivities(Intent intent, 3307 String resolvedType, int flags, int userId) { 3308 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3309 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3310 ComponentName comp = intent.getComponent(); 3311 if (comp == null) { 3312 if (intent.getSelector() != null) { 3313 intent = intent.getSelector(); 3314 comp = intent.getComponent(); 3315 } 3316 } 3317 3318 if (comp != null) { 3319 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3320 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3321 if (ai != null) { 3322 final ResolveInfo ri = new ResolveInfo(); 3323 ri.activityInfo = ai; 3324 list.add(ri); 3325 } 3326 return list; 3327 } 3328 3329 // reader 3330 synchronized (mPackages) { 3331 final String pkgName = intent.getPackage(); 3332 if (pkgName == null) { 3333 List<CrossProfileIntentFilter> matchingFilters = 3334 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3335 // Check for results that need to skip the current profile. 3336 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3337 resolvedType, flags, userId); 3338 if (resolveInfo != null) { 3339 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3340 result.add(resolveInfo); 3341 return result; 3342 } 3343 // Check for cross profile results. 3344 resolveInfo = queryCrossProfileIntents( 3345 matchingFilters, intent, resolvedType, flags, userId); 3346 3347 // Check for results in the current profile. 3348 List<ResolveInfo> result = mActivities.queryIntent( 3349 intent, resolvedType, flags, userId); 3350 if (resolveInfo != null) { 3351 result.add(resolveInfo); 3352 Collections.sort(result, mResolvePrioritySorter); 3353 } 3354 return result; 3355 } 3356 final PackageParser.Package pkg = mPackages.get(pkgName); 3357 if (pkg != null) { 3358 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3359 pkg.activities, userId); 3360 } 3361 return new ArrayList<ResolveInfo>(); 3362 } 3363 } 3364 3365 private ResolveInfo querySkipCurrentProfileIntents( 3366 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3367 int flags, int sourceUserId) { 3368 if (matchingFilters != null) { 3369 int size = matchingFilters.size(); 3370 for (int i = 0; i < size; i ++) { 3371 CrossProfileIntentFilter filter = matchingFilters.get(i); 3372 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3373 // Checking if there are activities in the target user that can handle the 3374 // intent. 3375 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3376 flags, sourceUserId); 3377 if (resolveInfo != null) { 3378 return resolveInfo; 3379 } 3380 } 3381 } 3382 } 3383 return null; 3384 } 3385 3386 // Return matching ResolveInfo if any for skip current profile intent filters. 3387 private ResolveInfo queryCrossProfileIntents( 3388 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3389 int flags, int sourceUserId) { 3390 if (matchingFilters != null) { 3391 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3392 // match the same intent. For performance reasons, it is better not to 3393 // run queryIntent twice for the same userId 3394 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3395 int size = matchingFilters.size(); 3396 for (int i = 0; i < size; i++) { 3397 CrossProfileIntentFilter filter = matchingFilters.get(i); 3398 int targetUserId = filter.getTargetUserId(); 3399 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3400 && !alreadyTriedUserIds.get(targetUserId)) { 3401 // Checking if there are activities in the target user that can handle the 3402 // intent. 3403 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3404 flags, sourceUserId); 3405 if (resolveInfo != null) return resolveInfo; 3406 alreadyTriedUserIds.put(targetUserId, true); 3407 } 3408 } 3409 } 3410 return null; 3411 } 3412 3413 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3414 String resolvedType, int flags, int sourceUserId) { 3415 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3416 resolvedType, flags, filter.getTargetUserId()); 3417 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3418 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3419 } 3420 return null; 3421 } 3422 3423 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3424 int sourceUserId, int targetUserId) { 3425 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3426 String className; 3427 if (targetUserId == UserHandle.USER_OWNER) { 3428 className = FORWARD_INTENT_TO_USER_OWNER; 3429 } else { 3430 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3431 } 3432 ComponentName forwardingActivityComponentName = new ComponentName( 3433 mAndroidApplication.packageName, className); 3434 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3435 sourceUserId); 3436 if (targetUserId == UserHandle.USER_OWNER) { 3437 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3438 forwardingResolveInfo.noResourceId = true; 3439 } 3440 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3441 forwardingResolveInfo.priority = 0; 3442 forwardingResolveInfo.preferredOrder = 0; 3443 forwardingResolveInfo.match = 0; 3444 forwardingResolveInfo.isDefault = true; 3445 forwardingResolveInfo.filter = filter; 3446 forwardingResolveInfo.targetUserId = targetUserId; 3447 return forwardingResolveInfo; 3448 } 3449 3450 @Override 3451 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3452 Intent[] specifics, String[] specificTypes, Intent intent, 3453 String resolvedType, int flags, int userId) { 3454 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3455 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3456 false, "query intent activity options"); 3457 final String resultsAction = intent.getAction(); 3458 3459 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3460 | PackageManager.GET_RESOLVED_FILTER, userId); 3461 3462 if (DEBUG_INTENT_MATCHING) { 3463 Log.v(TAG, "Query " + intent + ": " + results); 3464 } 3465 3466 int specificsPos = 0; 3467 int N; 3468 3469 // todo: note that the algorithm used here is O(N^2). This 3470 // isn't a problem in our current environment, but if we start running 3471 // into situations where we have more than 5 or 10 matches then this 3472 // should probably be changed to something smarter... 3473 3474 // First we go through and resolve each of the specific items 3475 // that were supplied, taking care of removing any corresponding 3476 // duplicate items in the generic resolve list. 3477 if (specifics != null) { 3478 for (int i=0; i<specifics.length; i++) { 3479 final Intent sintent = specifics[i]; 3480 if (sintent == null) { 3481 continue; 3482 } 3483 3484 if (DEBUG_INTENT_MATCHING) { 3485 Log.v(TAG, "Specific #" + i + ": " + sintent); 3486 } 3487 3488 String action = sintent.getAction(); 3489 if (resultsAction != null && resultsAction.equals(action)) { 3490 // If this action was explicitly requested, then don't 3491 // remove things that have it. 3492 action = null; 3493 } 3494 3495 ResolveInfo ri = null; 3496 ActivityInfo ai = null; 3497 3498 ComponentName comp = sintent.getComponent(); 3499 if (comp == null) { 3500 ri = resolveIntent( 3501 sintent, 3502 specificTypes != null ? specificTypes[i] : null, 3503 flags, userId); 3504 if (ri == null) { 3505 continue; 3506 } 3507 if (ri == mResolveInfo) { 3508 // ACK! Must do something better with this. 3509 } 3510 ai = ri.activityInfo; 3511 comp = new ComponentName(ai.applicationInfo.packageName, 3512 ai.name); 3513 } else { 3514 ai = getActivityInfo(comp, flags, userId); 3515 if (ai == null) { 3516 continue; 3517 } 3518 } 3519 3520 // Look for any generic query activities that are duplicates 3521 // of this specific one, and remove them from the results. 3522 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3523 N = results.size(); 3524 int j; 3525 for (j=specificsPos; j<N; j++) { 3526 ResolveInfo sri = results.get(j); 3527 if ((sri.activityInfo.name.equals(comp.getClassName()) 3528 && sri.activityInfo.applicationInfo.packageName.equals( 3529 comp.getPackageName())) 3530 || (action != null && sri.filter.matchAction(action))) { 3531 results.remove(j); 3532 if (DEBUG_INTENT_MATCHING) Log.v( 3533 TAG, "Removing duplicate item from " + j 3534 + " due to specific " + specificsPos); 3535 if (ri == null) { 3536 ri = sri; 3537 } 3538 j--; 3539 N--; 3540 } 3541 } 3542 3543 // Add this specific item to its proper place. 3544 if (ri == null) { 3545 ri = new ResolveInfo(); 3546 ri.activityInfo = ai; 3547 } 3548 results.add(specificsPos, ri); 3549 ri.specificIndex = i; 3550 specificsPos++; 3551 } 3552 } 3553 3554 // Now we go through the remaining generic results and remove any 3555 // duplicate actions that are found here. 3556 N = results.size(); 3557 for (int i=specificsPos; i<N-1; i++) { 3558 final ResolveInfo rii = results.get(i); 3559 if (rii.filter == null) { 3560 continue; 3561 } 3562 3563 // Iterate over all of the actions of this result's intent 3564 // filter... typically this should be just one. 3565 final Iterator<String> it = rii.filter.actionsIterator(); 3566 if (it == null) { 3567 continue; 3568 } 3569 while (it.hasNext()) { 3570 final String action = it.next(); 3571 if (resultsAction != null && resultsAction.equals(action)) { 3572 // If this action was explicitly requested, then don't 3573 // remove things that have it. 3574 continue; 3575 } 3576 for (int j=i+1; j<N; j++) { 3577 final ResolveInfo rij = results.get(j); 3578 if (rij.filter != null && rij.filter.hasAction(action)) { 3579 results.remove(j); 3580 if (DEBUG_INTENT_MATCHING) Log.v( 3581 TAG, "Removing duplicate item from " + j 3582 + " due to action " + action + " at " + i); 3583 j--; 3584 N--; 3585 } 3586 } 3587 } 3588 3589 // If the caller didn't request filter information, drop it now 3590 // so we don't have to marshall/unmarshall it. 3591 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3592 rii.filter = null; 3593 } 3594 } 3595 3596 // Filter out the caller activity if so requested. 3597 if (caller != null) { 3598 N = results.size(); 3599 for (int i=0; i<N; i++) { 3600 ActivityInfo ainfo = results.get(i).activityInfo; 3601 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3602 && caller.getClassName().equals(ainfo.name)) { 3603 results.remove(i); 3604 break; 3605 } 3606 } 3607 } 3608 3609 // If the caller didn't request filter information, 3610 // drop them now so we don't have to 3611 // marshall/unmarshall it. 3612 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3613 N = results.size(); 3614 for (int i=0; i<N; i++) { 3615 results.get(i).filter = null; 3616 } 3617 } 3618 3619 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3620 return results; 3621 } 3622 3623 @Override 3624 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3625 int userId) { 3626 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3627 ComponentName comp = intent.getComponent(); 3628 if (comp == null) { 3629 if (intent.getSelector() != null) { 3630 intent = intent.getSelector(); 3631 comp = intent.getComponent(); 3632 } 3633 } 3634 if (comp != null) { 3635 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3636 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3637 if (ai != null) { 3638 ResolveInfo ri = new ResolveInfo(); 3639 ri.activityInfo = ai; 3640 list.add(ri); 3641 } 3642 return list; 3643 } 3644 3645 // reader 3646 synchronized (mPackages) { 3647 String pkgName = intent.getPackage(); 3648 if (pkgName == null) { 3649 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3650 } 3651 final PackageParser.Package pkg = mPackages.get(pkgName); 3652 if (pkg != null) { 3653 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3654 userId); 3655 } 3656 return null; 3657 } 3658 } 3659 3660 @Override 3661 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3662 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3663 if (!sUserManager.exists(userId)) return null; 3664 if (query != null) { 3665 if (query.size() >= 1) { 3666 // If there is more than one service with the same priority, 3667 // just arbitrarily pick the first one. 3668 return query.get(0); 3669 } 3670 } 3671 return null; 3672 } 3673 3674 @Override 3675 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3676 int userId) { 3677 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3678 ComponentName comp = intent.getComponent(); 3679 if (comp == null) { 3680 if (intent.getSelector() != null) { 3681 intent = intent.getSelector(); 3682 comp = intent.getComponent(); 3683 } 3684 } 3685 if (comp != null) { 3686 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3687 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3688 if (si != null) { 3689 final ResolveInfo ri = new ResolveInfo(); 3690 ri.serviceInfo = si; 3691 list.add(ri); 3692 } 3693 return list; 3694 } 3695 3696 // reader 3697 synchronized (mPackages) { 3698 String pkgName = intent.getPackage(); 3699 if (pkgName == null) { 3700 return mServices.queryIntent(intent, resolvedType, flags, userId); 3701 } 3702 final PackageParser.Package pkg = mPackages.get(pkgName); 3703 if (pkg != null) { 3704 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3705 userId); 3706 } 3707 return null; 3708 } 3709 } 3710 3711 @Override 3712 public List<ResolveInfo> queryIntentContentProviders( 3713 Intent intent, String resolvedType, int flags, int userId) { 3714 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3715 ComponentName comp = intent.getComponent(); 3716 if (comp == null) { 3717 if (intent.getSelector() != null) { 3718 intent = intent.getSelector(); 3719 comp = intent.getComponent(); 3720 } 3721 } 3722 if (comp != null) { 3723 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3724 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3725 if (pi != null) { 3726 final ResolveInfo ri = new ResolveInfo(); 3727 ri.providerInfo = pi; 3728 list.add(ri); 3729 } 3730 return list; 3731 } 3732 3733 // reader 3734 synchronized (mPackages) { 3735 String pkgName = intent.getPackage(); 3736 if (pkgName == null) { 3737 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3738 } 3739 final PackageParser.Package pkg = mPackages.get(pkgName); 3740 if (pkg != null) { 3741 return mProviders.queryIntentForPackage( 3742 intent, resolvedType, flags, pkg.providers, userId); 3743 } 3744 return null; 3745 } 3746 } 3747 3748 @Override 3749 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3750 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3751 3752 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 3753 3754 // writer 3755 synchronized (mPackages) { 3756 ArrayList<PackageInfo> list; 3757 if (listUninstalled) { 3758 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3759 for (PackageSetting ps : mSettings.mPackages.values()) { 3760 PackageInfo pi; 3761 if (ps.pkg != null) { 3762 pi = generatePackageInfo(ps.pkg, flags, userId); 3763 } else { 3764 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3765 } 3766 if (pi != null) { 3767 list.add(pi); 3768 } 3769 } 3770 } else { 3771 list = new ArrayList<PackageInfo>(mPackages.size()); 3772 for (PackageParser.Package p : mPackages.values()) { 3773 PackageInfo pi = generatePackageInfo(p, flags, userId); 3774 if (pi != null) { 3775 list.add(pi); 3776 } 3777 } 3778 } 3779 3780 return new ParceledListSlice<PackageInfo>(list); 3781 } 3782 } 3783 3784 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3785 String[] permissions, boolean[] tmp, int flags, int userId) { 3786 int numMatch = 0; 3787 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3788 for (int i=0; i<permissions.length; i++) { 3789 if (gp.grantedPermissions.contains(permissions[i])) { 3790 tmp[i] = true; 3791 numMatch++; 3792 } else { 3793 tmp[i] = false; 3794 } 3795 } 3796 if (numMatch == 0) { 3797 return; 3798 } 3799 PackageInfo pi; 3800 if (ps.pkg != null) { 3801 pi = generatePackageInfo(ps.pkg, flags, userId); 3802 } else { 3803 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3804 } 3805 // The above might return null in cases of uninstalled apps or install-state 3806 // skew across users/profiles. 3807 if (pi != null) { 3808 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3809 if (numMatch == permissions.length) { 3810 pi.requestedPermissions = permissions; 3811 } else { 3812 pi.requestedPermissions = new String[numMatch]; 3813 numMatch = 0; 3814 for (int i=0; i<permissions.length; i++) { 3815 if (tmp[i]) { 3816 pi.requestedPermissions[numMatch] = permissions[i]; 3817 numMatch++; 3818 } 3819 } 3820 } 3821 } 3822 list.add(pi); 3823 } 3824 } 3825 3826 @Override 3827 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3828 String[] permissions, int flags, int userId) { 3829 if (!sUserManager.exists(userId)) return null; 3830 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3831 3832 // writer 3833 synchronized (mPackages) { 3834 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3835 boolean[] tmpBools = new boolean[permissions.length]; 3836 if (listUninstalled) { 3837 for (PackageSetting ps : mSettings.mPackages.values()) { 3838 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3839 } 3840 } else { 3841 for (PackageParser.Package pkg : mPackages.values()) { 3842 PackageSetting ps = (PackageSetting)pkg.mExtras; 3843 if (ps != null) { 3844 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3845 userId); 3846 } 3847 } 3848 } 3849 3850 return new ParceledListSlice<PackageInfo>(list); 3851 } 3852 } 3853 3854 @Override 3855 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3856 if (!sUserManager.exists(userId)) return null; 3857 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3858 3859 // writer 3860 synchronized (mPackages) { 3861 ArrayList<ApplicationInfo> list; 3862 if (listUninstalled) { 3863 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3864 for (PackageSetting ps : mSettings.mPackages.values()) { 3865 ApplicationInfo ai; 3866 if (ps.pkg != null) { 3867 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3868 ps.readUserState(userId), userId); 3869 } else { 3870 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3871 } 3872 if (ai != null) { 3873 list.add(ai); 3874 } 3875 } 3876 } else { 3877 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3878 for (PackageParser.Package p : mPackages.values()) { 3879 if (p.mExtras != null) { 3880 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3881 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3882 if (ai != null) { 3883 list.add(ai); 3884 } 3885 } 3886 } 3887 } 3888 3889 return new ParceledListSlice<ApplicationInfo>(list); 3890 } 3891 } 3892 3893 public List<ApplicationInfo> getPersistentApplications(int flags) { 3894 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3895 3896 // reader 3897 synchronized (mPackages) { 3898 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3899 final int userId = UserHandle.getCallingUserId(); 3900 while (i.hasNext()) { 3901 final PackageParser.Package p = i.next(); 3902 if (p.applicationInfo != null 3903 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3904 && (!mSafeMode || isSystemApp(p))) { 3905 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3906 if (ps != null) { 3907 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3908 ps.readUserState(userId), userId); 3909 if (ai != null) { 3910 finalList.add(ai); 3911 } 3912 } 3913 } 3914 } 3915 } 3916 3917 return finalList; 3918 } 3919 3920 @Override 3921 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3922 if (!sUserManager.exists(userId)) return null; 3923 // reader 3924 synchronized (mPackages) { 3925 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3926 PackageSetting ps = provider != null 3927 ? mSettings.mPackages.get(provider.owner.packageName) 3928 : null; 3929 return ps != null 3930 && mSettings.isEnabledLPr(provider.info, flags, userId) 3931 && (!mSafeMode || (provider.info.applicationInfo.flags 3932 &ApplicationInfo.FLAG_SYSTEM) != 0) 3933 ? PackageParser.generateProviderInfo(provider, flags, 3934 ps.readUserState(userId), userId) 3935 : null; 3936 } 3937 } 3938 3939 /** 3940 * @deprecated 3941 */ 3942 @Deprecated 3943 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3944 // reader 3945 synchronized (mPackages) { 3946 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3947 .entrySet().iterator(); 3948 final int userId = UserHandle.getCallingUserId(); 3949 while (i.hasNext()) { 3950 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3951 PackageParser.Provider p = entry.getValue(); 3952 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3953 3954 if (ps != null && p.syncable 3955 && (!mSafeMode || (p.info.applicationInfo.flags 3956 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3957 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3958 ps.readUserState(userId), userId); 3959 if (info != null) { 3960 outNames.add(entry.getKey()); 3961 outInfo.add(info); 3962 } 3963 } 3964 } 3965 } 3966 } 3967 3968 @Override 3969 public List<ProviderInfo> queryContentProviders(String processName, 3970 int uid, int flags) { 3971 ArrayList<ProviderInfo> finalList = null; 3972 // reader 3973 synchronized (mPackages) { 3974 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3975 final int userId = processName != null ? 3976 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3977 while (i.hasNext()) { 3978 final PackageParser.Provider p = i.next(); 3979 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3980 if (ps != null && p.info.authority != null 3981 && (processName == null 3982 || (p.info.processName.equals(processName) 3983 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3984 && mSettings.isEnabledLPr(p.info, flags, userId) 3985 && (!mSafeMode 3986 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3987 if (finalList == null) { 3988 finalList = new ArrayList<ProviderInfo>(3); 3989 } 3990 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3991 ps.readUserState(userId), userId); 3992 if (info != null) { 3993 finalList.add(info); 3994 } 3995 } 3996 } 3997 } 3998 3999 if (finalList != null) { 4000 Collections.sort(finalList, mProviderInitOrderSorter); 4001 } 4002 4003 return finalList; 4004 } 4005 4006 @Override 4007 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4008 int flags) { 4009 // reader 4010 synchronized (mPackages) { 4011 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4012 return PackageParser.generateInstrumentationInfo(i, flags); 4013 } 4014 } 4015 4016 @Override 4017 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4018 int flags) { 4019 ArrayList<InstrumentationInfo> finalList = 4020 new ArrayList<InstrumentationInfo>(); 4021 4022 // reader 4023 synchronized (mPackages) { 4024 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4025 while (i.hasNext()) { 4026 final PackageParser.Instrumentation p = i.next(); 4027 if (targetPackage == null 4028 || targetPackage.equals(p.info.targetPackage)) { 4029 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4030 flags); 4031 if (ii != null) { 4032 finalList.add(ii); 4033 } 4034 } 4035 } 4036 } 4037 4038 return finalList; 4039 } 4040 4041 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4042 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4043 if (overlays == null) { 4044 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4045 return; 4046 } 4047 for (PackageParser.Package opkg : overlays.values()) { 4048 // Not much to do if idmap fails: we already logged the error 4049 // and we certainly don't want to abort installation of pkg simply 4050 // because an overlay didn't fit properly. For these reasons, 4051 // ignore the return value of createIdmapForPackagePairLI. 4052 createIdmapForPackagePairLI(pkg, opkg); 4053 } 4054 } 4055 4056 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4057 PackageParser.Package opkg) { 4058 if (!opkg.mTrustedOverlay) { 4059 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4060 opkg.baseCodePath + ": overlay not trusted"); 4061 return false; 4062 } 4063 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4064 if (overlaySet == null) { 4065 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4066 opkg.baseCodePath + " but target package has no known overlays"); 4067 return false; 4068 } 4069 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4070 // TODO: generate idmap for split APKs 4071 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4072 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4073 + opkg.baseCodePath); 4074 return false; 4075 } 4076 PackageParser.Package[] overlayArray = 4077 overlaySet.values().toArray(new PackageParser.Package[0]); 4078 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4079 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4080 return p1.mOverlayPriority - p2.mOverlayPriority; 4081 } 4082 }; 4083 Arrays.sort(overlayArray, cmp); 4084 4085 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4086 int i = 0; 4087 for (PackageParser.Package p : overlayArray) { 4088 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4089 } 4090 return true; 4091 } 4092 4093 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4094 final File[] files = dir.listFiles(); 4095 if (ArrayUtils.isEmpty(files)) { 4096 Log.d(TAG, "No files in app dir " + dir); 4097 return; 4098 } 4099 4100 if (DEBUG_PACKAGE_SCANNING) { 4101 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4102 + " flags=0x" + Integer.toHexString(parseFlags)); 4103 } 4104 4105 for (File file : files) { 4106 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4107 && !PackageInstallerService.isStageName(file.getName()); 4108 if (!isPackage) { 4109 // Ignore entries which are not packages 4110 continue; 4111 } 4112 try { 4113 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4114 scanFlags, currentTime, null); 4115 } catch (PackageManagerException e) { 4116 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4117 4118 // Delete invalid userdata apps 4119 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4120 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4121 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4122 if (file.isDirectory()) { 4123 FileUtils.deleteContents(file); 4124 } 4125 file.delete(); 4126 } 4127 } 4128 } 4129 } 4130 4131 private static File getSettingsProblemFile() { 4132 File dataDir = Environment.getDataDirectory(); 4133 File systemDir = new File(dataDir, "system"); 4134 File fname = new File(systemDir, "uiderrors.txt"); 4135 return fname; 4136 } 4137 4138 static void reportSettingsProblem(int priority, String msg) { 4139 logCriticalInfo(priority, msg); 4140 } 4141 4142 static void logCriticalInfo(int priority, String msg) { 4143 Slog.println(priority, TAG, msg); 4144 EventLogTags.writePmCriticalInfo(msg); 4145 try { 4146 File fname = getSettingsProblemFile(); 4147 FileOutputStream out = new FileOutputStream(fname, true); 4148 PrintWriter pw = new FastPrintWriter(out); 4149 SimpleDateFormat formatter = new SimpleDateFormat(); 4150 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4151 pw.println(dateString + ": " + msg); 4152 pw.close(); 4153 FileUtils.setPermissions( 4154 fname.toString(), 4155 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4156 -1, -1); 4157 } catch (java.io.IOException e) { 4158 } 4159 } 4160 4161 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4162 PackageParser.Package pkg, File srcFile, int parseFlags) 4163 throws PackageManagerException { 4164 if (ps != null 4165 && ps.codePath.equals(srcFile) 4166 && ps.timeStamp == srcFile.lastModified() 4167 && !isCompatSignatureUpdateNeeded(pkg)) { 4168 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4169 if (ps.signatures.mSignatures != null 4170 && ps.signatures.mSignatures.length != 0 4171 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4172 // Optimization: reuse the existing cached certificates 4173 // if the package appears to be unchanged. 4174 pkg.mSignatures = ps.signatures.mSignatures; 4175 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4176 synchronized (mPackages) { 4177 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4178 } 4179 return; 4180 } 4181 4182 Slog.w(TAG, "PackageSetting for " + ps.name 4183 + " is missing signatures. Collecting certs again to recover them."); 4184 } else { 4185 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4186 } 4187 4188 try { 4189 pp.collectCertificates(pkg, parseFlags); 4190 pp.collectManifestDigest(pkg); 4191 } catch (PackageParserException e) { 4192 throw PackageManagerException.from(e); 4193 } 4194 } 4195 4196 /* 4197 * Scan a package and return the newly parsed package. 4198 * Returns null in case of errors and the error code is stored in mLastScanError 4199 */ 4200 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4201 long currentTime, UserHandle user) throws PackageManagerException { 4202 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4203 parseFlags |= mDefParseFlags; 4204 PackageParser pp = new PackageParser(); 4205 pp.setSeparateProcesses(mSeparateProcesses); 4206 pp.setOnlyCoreApps(mOnlyCore); 4207 pp.setDisplayMetrics(mMetrics); 4208 4209 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4210 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4211 } 4212 4213 final PackageParser.Package pkg; 4214 try { 4215 pkg = pp.parsePackage(scanFile, parseFlags); 4216 } catch (PackageParserException e) { 4217 throw PackageManagerException.from(e); 4218 } 4219 4220 PackageSetting ps = null; 4221 PackageSetting updatedPkg; 4222 // reader 4223 synchronized (mPackages) { 4224 // Look to see if we already know about this package. 4225 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4226 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4227 // This package has been renamed to its original name. Let's 4228 // use that. 4229 ps = mSettings.peekPackageLPr(oldName); 4230 } 4231 // If there was no original package, see one for the real package name. 4232 if (ps == null) { 4233 ps = mSettings.peekPackageLPr(pkg.packageName); 4234 } 4235 // Check to see if this package could be hiding/updating a system 4236 // package. Must look for it either under the original or real 4237 // package name depending on our state. 4238 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4239 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4240 } 4241 boolean updatedPkgBetter = false; 4242 // First check if this is a system package that may involve an update 4243 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4244 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4245 // it needs to drop FLAG_PRIVILEGED. 4246 if (locationIsPrivileged(scanFile)) { 4247 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4248 } else { 4249 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4250 } 4251 4252 if (ps != null && !ps.codePath.equals(scanFile)) { 4253 // The path has changed from what was last scanned... check the 4254 // version of the new path against what we have stored to determine 4255 // what to do. 4256 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4257 if (pkg.mVersionCode < ps.versionCode) { 4258 // The system package has been updated and the code path does not match 4259 // Ignore entry. Skip it. 4260 logCriticalInfo(Log.INFO, "Package " + ps.name + " at " + scanFile 4261 + " ignored: updated version " + ps.versionCode 4262 + " better than this " + pkg.mVersionCode); 4263 if (!updatedPkg.codePath.equals(scanFile)) { 4264 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4265 + ps.name + " changing from " + updatedPkg.codePathString 4266 + " to " + scanFile); 4267 updatedPkg.codePath = scanFile; 4268 updatedPkg.codePathString = scanFile.toString(); 4269 updatedPkg.resourcePath = scanFile; 4270 updatedPkg.resourcePathString = scanFile.toString(); 4271 } 4272 updatedPkg.pkg = pkg; 4273 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4274 } else { 4275 // The current app on the system partition is better than 4276 // what we have updated to on the data partition; switch 4277 // back to the system partition version. 4278 // At this point, its safely assumed that package installation for 4279 // apps in system partition will go through. If not there won't be a working 4280 // version of the app 4281 // writer 4282 synchronized (mPackages) { 4283 // Just remove the loaded entries from package lists. 4284 mPackages.remove(ps.name); 4285 } 4286 4287 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4288 + " reverting from " + ps.codePathString 4289 + ": new version " + pkg.mVersionCode 4290 + " better than installed " + ps.versionCode); 4291 4292 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4293 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4294 getAppDexInstructionSets(ps)); 4295 synchronized (mInstallLock) { 4296 args.cleanUpResourcesLI(); 4297 } 4298 synchronized (mPackages) { 4299 mSettings.enableSystemPackageLPw(ps.name); 4300 } 4301 updatedPkgBetter = true; 4302 } 4303 } 4304 } 4305 4306 if (updatedPkg != null) { 4307 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4308 // initially 4309 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4310 4311 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4312 // flag set initially 4313 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 4314 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4315 } 4316 } 4317 4318 // Verify certificates against what was last scanned 4319 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4320 4321 /* 4322 * A new system app appeared, but we already had a non-system one of the 4323 * same name installed earlier. 4324 */ 4325 boolean shouldHideSystemApp = false; 4326 if (updatedPkg == null && ps != null 4327 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4328 /* 4329 * Check to make sure the signatures match first. If they don't, 4330 * wipe the installed application and its data. 4331 */ 4332 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4333 != PackageManager.SIGNATURE_MATCH) { 4334 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4335 + " signatures don't match existing userdata copy; removing"); 4336 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4337 ps = null; 4338 } else { 4339 /* 4340 * If the newly-added system app is an older version than the 4341 * already installed version, hide it. It will be scanned later 4342 * and re-added like an update. 4343 */ 4344 if (pkg.mVersionCode < ps.versionCode) { 4345 shouldHideSystemApp = true; 4346 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4347 + " but new version " + pkg.mVersionCode + " better than installed " 4348 + ps.versionCode + "; hiding system"); 4349 } else { 4350 /* 4351 * The newly found system app is a newer version that the 4352 * one previously installed. Simply remove the 4353 * already-installed application and replace it with our own 4354 * while keeping the application data. 4355 */ 4356 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4357 + " reverting from " + ps.codePathString + ": new version " 4358 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4359 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4360 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4361 getAppDexInstructionSets(ps)); 4362 synchronized (mInstallLock) { 4363 args.cleanUpResourcesLI(); 4364 } 4365 } 4366 } 4367 } 4368 4369 // The apk is forward locked (not public) if its code and resources 4370 // are kept in different files. (except for app in either system or 4371 // vendor path). 4372 // TODO grab this value from PackageSettings 4373 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4374 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4375 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4376 } 4377 } 4378 4379 // TODO: extend to support forward-locked splits 4380 String resourcePath = null; 4381 String baseResourcePath = null; 4382 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4383 if (ps != null && ps.resourcePathString != null) { 4384 resourcePath = ps.resourcePathString; 4385 baseResourcePath = ps.resourcePathString; 4386 } else { 4387 // Should not happen at all. Just log an error. 4388 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4389 } 4390 } else { 4391 resourcePath = pkg.codePath; 4392 baseResourcePath = pkg.baseCodePath; 4393 } 4394 4395 // Set application objects path explicitly. 4396 pkg.applicationInfo.setCodePath(pkg.codePath); 4397 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4398 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4399 pkg.applicationInfo.setResourcePath(resourcePath); 4400 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4401 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4402 4403 // Note that we invoke the following method only if we are about to unpack an application 4404 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4405 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4406 4407 /* 4408 * If the system app should be overridden by a previously installed 4409 * data, hide the system app now and let the /data/app scan pick it up 4410 * again. 4411 */ 4412 if (shouldHideSystemApp) { 4413 synchronized (mPackages) { 4414 /* 4415 * We have to grant systems permissions before we hide, because 4416 * grantPermissions will assume the package update is trying to 4417 * expand its permissions. 4418 */ 4419 grantPermissionsLPw(pkg, true, pkg.packageName); 4420 mSettings.disableSystemPackageLPw(pkg.packageName); 4421 } 4422 } 4423 4424 return scannedPkg; 4425 } 4426 4427 private static String fixProcessName(String defProcessName, 4428 String processName, int uid) { 4429 if (processName == null) { 4430 return defProcessName; 4431 } 4432 return processName; 4433 } 4434 4435 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4436 throws PackageManagerException { 4437 if (pkgSetting.signatures.mSignatures != null) { 4438 // Already existing package. Make sure signatures match 4439 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4440 == PackageManager.SIGNATURE_MATCH; 4441 if (!match) { 4442 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4443 == PackageManager.SIGNATURE_MATCH; 4444 } 4445 if (!match) { 4446 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4447 + pkg.packageName + " signatures do not match the " 4448 + "previously installed version; ignoring!"); 4449 } 4450 } 4451 4452 // Check for shared user signatures 4453 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4454 // Already existing package. Make sure signatures match 4455 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4456 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4457 if (!match) { 4458 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4459 == PackageManager.SIGNATURE_MATCH; 4460 } 4461 if (!match) { 4462 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4463 "Package " + pkg.packageName 4464 + " has no signatures that match those in shared user " 4465 + pkgSetting.sharedUser.name + "; ignoring!"); 4466 } 4467 } 4468 } 4469 4470 /** 4471 * Enforces that only the system UID or root's UID can call a method exposed 4472 * via Binder. 4473 * 4474 * @param message used as message if SecurityException is thrown 4475 * @throws SecurityException if the caller is not system or root 4476 */ 4477 private static final void enforceSystemOrRoot(String message) { 4478 final int uid = Binder.getCallingUid(); 4479 if (uid != Process.SYSTEM_UID && uid != 0) { 4480 throw new SecurityException(message); 4481 } 4482 } 4483 4484 @Override 4485 public void performBootDexOpt() { 4486 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4487 4488 final HashSet<PackageParser.Package> pkgs; 4489 synchronized (mPackages) { 4490 pkgs = mDeferredDexOpt; 4491 mDeferredDexOpt = null; 4492 } 4493 4494 if (pkgs != null) { 4495 // Sort apps by importance for dexopt ordering. Important apps are given more priority 4496 // in case the device runs out of space. 4497 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 4498 // Give priority to core apps. 4499 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4500 PackageParser.Package pkg = it.next(); 4501 if (pkg.coreApp) { 4502 if (DEBUG_DEXOPT) { 4503 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 4504 } 4505 sortedPkgs.add(pkg); 4506 it.remove(); 4507 } 4508 } 4509 // Give priority to system apps that listen for pre boot complete. 4510 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 4511 HashSet<String> pkgNames = getPackageNamesForIntent(intent); 4512 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4513 PackageParser.Package pkg = it.next(); 4514 if (pkgNames.contains(pkg.packageName)) { 4515 if (DEBUG_DEXOPT) { 4516 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 4517 } 4518 sortedPkgs.add(pkg); 4519 it.remove(); 4520 } 4521 } 4522 // Give priority to system apps. 4523 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4524 PackageParser.Package pkg = it.next(); 4525 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 4526 if (DEBUG_DEXOPT) { 4527 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 4528 } 4529 sortedPkgs.add(pkg); 4530 it.remove(); 4531 } 4532 } 4533 // Give priority to updated system apps. 4534 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4535 PackageParser.Package pkg = it.next(); 4536 if (isUpdatedSystemApp(pkg)) { 4537 if (DEBUG_DEXOPT) { 4538 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 4539 } 4540 sortedPkgs.add(pkg); 4541 it.remove(); 4542 } 4543 } 4544 // Give priority to apps that listen for boot complete. 4545 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 4546 pkgNames = getPackageNamesForIntent(intent); 4547 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4548 PackageParser.Package pkg = it.next(); 4549 if (pkgNames.contains(pkg.packageName)) { 4550 if (DEBUG_DEXOPT) { 4551 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 4552 } 4553 sortedPkgs.add(pkg); 4554 it.remove(); 4555 } 4556 } 4557 // Filter out packages that aren't recently used. 4558 filterRecentlyUsedApps(pkgs); 4559 // Add all remaining apps. 4560 for (PackageParser.Package pkg : pkgs) { 4561 if (DEBUG_DEXOPT) { 4562 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 4563 } 4564 sortedPkgs.add(pkg); 4565 } 4566 4567 int i = 0; 4568 int total = sortedPkgs.size(); 4569 File dataDir = Environment.getDataDirectory(); 4570 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 4571 if (lowThreshold == 0) { 4572 throw new IllegalStateException("Invalid low memory threshold"); 4573 } 4574 for (PackageParser.Package pkg : sortedPkgs) { 4575 long usableSpace = dataDir.getUsableSpace(); 4576 if (usableSpace < lowThreshold) { 4577 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 4578 break; 4579 } 4580 performBootDexOpt(pkg, ++i, total); 4581 } 4582 } 4583 } 4584 4585 private void filterRecentlyUsedApps(HashSet<PackageParser.Package> pkgs) { 4586 // Filter out packages that aren't recently used. 4587 // 4588 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4589 // should do a full dexopt. 4590 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4591 // TODO: add a property to control this? 4592 long dexOptLRUThresholdInMinutes; 4593 if (mLazyDexOpt) { 4594 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4595 } else { 4596 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4597 } 4598 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4599 4600 int total = pkgs.size(); 4601 int skipped = 0; 4602 long now = System.currentTimeMillis(); 4603 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4604 PackageParser.Package pkg = i.next(); 4605 long then = pkg.mLastPackageUsageTimeInMills; 4606 if (then + dexOptLRUThresholdInMills < now) { 4607 if (DEBUG_DEXOPT) { 4608 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4609 ((then == 0) ? "never" : new Date(then))); 4610 } 4611 i.remove(); 4612 skipped++; 4613 } 4614 } 4615 if (DEBUG_DEXOPT) { 4616 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4617 } 4618 } 4619 } 4620 4621 private HashSet<String> getPackageNamesForIntent(Intent intent) { 4622 List<ResolveInfo> ris = null; 4623 try { 4624 ris = AppGlobals.getPackageManager().queryIntentReceivers( 4625 intent, null, 0, UserHandle.USER_OWNER); 4626 } catch (RemoteException e) { 4627 } 4628 HashSet<String> pkgNames = new HashSet<String>(); 4629 if (ris != null) { 4630 for (ResolveInfo ri : ris) { 4631 pkgNames.add(ri.activityInfo.packageName); 4632 } 4633 } 4634 return pkgNames; 4635 } 4636 4637 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 4638 if (DEBUG_DEXOPT) { 4639 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 4640 } 4641 if (!isFirstBoot()) { 4642 try { 4643 ActivityManagerNative.getDefault().showBootMessage( 4644 mContext.getResources().getString(R.string.android_upgrading_apk, 4645 curr, total), true); 4646 } catch (RemoteException e) { 4647 } 4648 } 4649 PackageParser.Package p = pkg; 4650 synchronized (mInstallLock) { 4651 performDexOptLI(p, null /* instruction sets */, false /* force dex */, 4652 false /* defer */, true /* include dependencies */); 4653 } 4654 } 4655 4656 @Override 4657 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4658 return performDexOpt(packageName, instructionSet, false); 4659 } 4660 4661 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4662 if (info.primaryCpuAbi == null) { 4663 return getPreferredInstructionSet(); 4664 } 4665 4666 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4667 } 4668 4669 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4670 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4671 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4672 if (!dexopt && !updateUsage) { 4673 // We aren't going to dexopt or update usage, so bail early. 4674 return false; 4675 } 4676 PackageParser.Package p; 4677 final String targetInstructionSet; 4678 synchronized (mPackages) { 4679 p = mPackages.get(packageName); 4680 if (p == null) { 4681 return false; 4682 } 4683 if (updateUsage) { 4684 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4685 } 4686 mPackageUsage.write(false); 4687 if (!dexopt) { 4688 // We aren't going to dexopt, so bail early. 4689 return false; 4690 } 4691 4692 targetInstructionSet = instructionSet != null ? instructionSet : 4693 getPrimaryInstructionSet(p.applicationInfo); 4694 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4695 return false; 4696 } 4697 } 4698 4699 synchronized (mInstallLock) { 4700 final String[] instructionSets = new String[] { targetInstructionSet }; 4701 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4702 true /* include dependencies */) == DEX_OPT_PERFORMED; 4703 } 4704 } 4705 4706 public HashSet<String> getPackagesThatNeedDexOpt() { 4707 HashSet<String> pkgs = null; 4708 synchronized (mPackages) { 4709 for (PackageParser.Package p : mPackages.values()) { 4710 if (DEBUG_DEXOPT) { 4711 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4712 } 4713 if (!p.mDexOptPerformed.isEmpty()) { 4714 continue; 4715 } 4716 if (pkgs == null) { 4717 pkgs = new HashSet<String>(); 4718 } 4719 pkgs.add(p.packageName); 4720 } 4721 } 4722 return pkgs; 4723 } 4724 4725 public void shutdown() { 4726 mPackageUsage.write(true); 4727 } 4728 4729 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4730 boolean forceDex, boolean defer, HashSet<String> done) { 4731 for (int i=0; i<libs.size(); i++) { 4732 PackageParser.Package libPkg; 4733 String libName; 4734 synchronized (mPackages) { 4735 libName = libs.get(i); 4736 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4737 if (lib != null && lib.apk != null) { 4738 libPkg = mPackages.get(lib.apk); 4739 } else { 4740 libPkg = null; 4741 } 4742 } 4743 if (libPkg != null && !done.contains(libName)) { 4744 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4745 } 4746 } 4747 } 4748 4749 static final int DEX_OPT_SKIPPED = 0; 4750 static final int DEX_OPT_PERFORMED = 1; 4751 static final int DEX_OPT_DEFERRED = 2; 4752 static final int DEX_OPT_FAILED = -1; 4753 4754 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4755 boolean forceDex, boolean defer, HashSet<String> done) { 4756 final String[] instructionSets = targetInstructionSets != null ? 4757 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4758 4759 if (done != null) { 4760 done.add(pkg.packageName); 4761 if (pkg.usesLibraries != null) { 4762 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4763 } 4764 if (pkg.usesOptionalLibraries != null) { 4765 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4766 } 4767 } 4768 4769 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4770 return DEX_OPT_SKIPPED; 4771 } 4772 4773 final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0; 4774 4775 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4776 boolean performedDexOpt = false; 4777 // There are three basic cases here: 4778 // 1.) we need to dexopt, either because we are forced or it is needed 4779 // 2.) we are defering a needed dexopt 4780 // 3.) we are skipping an unneeded dexopt 4781 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4782 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4783 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4784 continue; 4785 } 4786 4787 for (String path : paths) { 4788 try { 4789 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4790 // patckage or the one we find does not match the image checksum (i.e. it was 4791 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4792 // odex file and it matches the checksum of the image but not its base address, 4793 // meaning we need to move it. 4794 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4795 pkg.packageName, dexCodeInstructionSet, defer); 4796 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4797 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4798 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet 4799 + " vmSafeMode=" + vmSafeMode); 4800 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4801 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4802 pkg.packageName, dexCodeInstructionSet, vmSafeMode); 4803 4804 if (ret < 0) { 4805 // Don't bother running dexopt again if we failed, it will probably 4806 // just result in an error again. Also, don't bother dexopting for other 4807 // paths & ISAs. 4808 return DEX_OPT_FAILED; 4809 } 4810 4811 performedDexOpt = true; 4812 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4813 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4814 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4815 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4816 pkg.packageName, dexCodeInstructionSet); 4817 4818 if (ret < 0) { 4819 // Don't bother running patchoat again if we failed, it will probably 4820 // just result in an error again. Also, don't bother dexopting for other 4821 // paths & ISAs. 4822 return DEX_OPT_FAILED; 4823 } 4824 4825 performedDexOpt = true; 4826 } 4827 4828 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4829 // paths and instruction sets. We'll deal with them all together when we process 4830 // our list of deferred dexopts. 4831 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4832 if (mDeferredDexOpt == null) { 4833 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4834 } 4835 mDeferredDexOpt.add(pkg); 4836 return DEX_OPT_DEFERRED; 4837 } 4838 } catch (FileNotFoundException e) { 4839 Slog.w(TAG, "Apk not found for dexopt: " + path); 4840 return DEX_OPT_FAILED; 4841 } catch (IOException e) { 4842 Slog.w(TAG, "IOException reading apk: " + path, e); 4843 return DEX_OPT_FAILED; 4844 } catch (StaleDexCacheError e) { 4845 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4846 return DEX_OPT_FAILED; 4847 } catch (Exception e) { 4848 Slog.w(TAG, "Exception when doing dexopt : ", e); 4849 return DEX_OPT_FAILED; 4850 } 4851 } 4852 4853 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4854 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4855 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4856 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4857 // it. 4858 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4859 } 4860 4861 // If we've gotten here, we're sure that no error occurred and that we haven't 4862 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4863 // we've skipped all of them because they are up to date. In both cases this 4864 // package doesn't need dexopt any longer. 4865 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4866 } 4867 4868 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4869 if (info.primaryCpuAbi != null) { 4870 if (info.secondaryCpuAbi != null) { 4871 return new String[] { 4872 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4873 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4874 } else { 4875 return new String[] { 4876 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4877 } 4878 } 4879 4880 return new String[] { getPreferredInstructionSet() }; 4881 } 4882 4883 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4884 if (ps.primaryCpuAbiString != null) { 4885 if (ps.secondaryCpuAbiString != null) { 4886 return new String[] { 4887 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4888 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4889 } else { 4890 return new String[] { 4891 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4892 } 4893 } 4894 4895 return new String[] { getPreferredInstructionSet() }; 4896 } 4897 4898 private static String getPreferredInstructionSet() { 4899 if (sPreferredInstructionSet == null) { 4900 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4901 } 4902 4903 return sPreferredInstructionSet; 4904 } 4905 4906 private static List<String> getAllInstructionSets() { 4907 final String[] allAbis = Build.SUPPORTED_ABIS; 4908 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4909 4910 for (String abi : allAbis) { 4911 final String instructionSet = VMRuntime.getInstructionSet(abi); 4912 if (!allInstructionSets.contains(instructionSet)) { 4913 allInstructionSets.add(instructionSet); 4914 } 4915 } 4916 4917 return allInstructionSets; 4918 } 4919 4920 /** 4921 * Returns the instruction set that should be used to compile dex code. In the presence of 4922 * a native bridge this might be different than the one shared libraries use. 4923 */ 4924 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4925 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4926 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4927 } 4928 4929 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4930 HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length); 4931 for (String instructionSet : instructionSets) { 4932 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4933 } 4934 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4935 } 4936 4937 /** 4938 * Returns deduplicated list of supported instructions for dex code. 4939 */ 4940 public static String[] getAllDexCodeInstructionSets() { 4941 String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length]; 4942 for (int i = 0; i < supportedInstructionSets.length; i++) { 4943 String abi = Build.SUPPORTED_ABIS[i]; 4944 supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi); 4945 } 4946 return getDexCodeInstructionSets(supportedInstructionSets); 4947 } 4948 4949 @Override 4950 public void forceDexOpt(String packageName) { 4951 enforceSystemOrRoot("forceDexOpt"); 4952 4953 PackageParser.Package pkg; 4954 synchronized (mPackages) { 4955 pkg = mPackages.get(packageName); 4956 if (pkg == null) { 4957 throw new IllegalArgumentException("Missing package: " + packageName); 4958 } 4959 } 4960 4961 synchronized (mInstallLock) { 4962 final String[] instructionSets = new String[] { 4963 getPrimaryInstructionSet(pkg.applicationInfo) }; 4964 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4965 if (res != DEX_OPT_PERFORMED) { 4966 throw new IllegalStateException("Failed to dexopt: " + res); 4967 } 4968 } 4969 } 4970 4971 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4972 boolean forceDex, boolean defer, boolean inclDependencies) { 4973 HashSet<String> done; 4974 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4975 done = new HashSet<String>(); 4976 done.add(pkg.packageName); 4977 } else { 4978 done = null; 4979 } 4980 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4981 } 4982 4983 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4984 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4985 Slog.w(TAG, "Unable to update from " + oldPkg.name 4986 + " to " + newPkg.packageName 4987 + ": old package not in system partition"); 4988 return false; 4989 } else if (mPackages.get(oldPkg.name) != null) { 4990 Slog.w(TAG, "Unable to update from " + oldPkg.name 4991 + " to " + newPkg.packageName 4992 + ": old package still exists"); 4993 return false; 4994 } 4995 return true; 4996 } 4997 4998 File getDataPathForUser(int userId) { 4999 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 5000 } 5001 5002 private File getDataPathForPackage(String packageName, int userId) { 5003 /* 5004 * Until we fully support multiple users, return the directory we 5005 * previously would have. The PackageManagerTests will need to be 5006 * revised when this is changed back.. 5007 */ 5008 if (userId == 0) { 5009 return new File(mAppDataDir, packageName); 5010 } else { 5011 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 5012 + File.separator + packageName); 5013 } 5014 } 5015 5016 private int createDataDirsLI(String packageName, int uid, String seinfo) { 5017 int[] users = sUserManager.getUserIds(); 5018 int res = mInstaller.install(packageName, uid, uid, seinfo); 5019 if (res < 0) { 5020 return res; 5021 } 5022 for (int user : users) { 5023 if (user != 0) { 5024 res = mInstaller.createUserData(packageName, 5025 UserHandle.getUid(user, uid), user, seinfo); 5026 if (res < 0) { 5027 return res; 5028 } 5029 } 5030 } 5031 return res; 5032 } 5033 5034 private int removeDataDirsLI(String packageName) { 5035 int[] users = sUserManager.getUserIds(); 5036 int res = 0; 5037 for (int user : users) { 5038 int resInner = mInstaller.remove(packageName, user); 5039 if (resInner < 0) { 5040 res = resInner; 5041 } 5042 } 5043 5044 return res; 5045 } 5046 5047 private int deleteCodeCacheDirsLI(String packageName) { 5048 int[] users = sUserManager.getUserIds(); 5049 int res = 0; 5050 for (int user : users) { 5051 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 5052 if (resInner < 0) { 5053 res = resInner; 5054 } 5055 } 5056 return res; 5057 } 5058 5059 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5060 PackageParser.Package changingLib) { 5061 if (file.path != null) { 5062 usesLibraryFiles.add(file.path); 5063 return; 5064 } 5065 PackageParser.Package p = mPackages.get(file.apk); 5066 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5067 // If we are doing this while in the middle of updating a library apk, 5068 // then we need to make sure to use that new apk for determining the 5069 // dependencies here. (We haven't yet finished committing the new apk 5070 // to the package manager state.) 5071 if (p == null || p.packageName.equals(changingLib.packageName)) { 5072 p = changingLib; 5073 } 5074 } 5075 if (p != null) { 5076 usesLibraryFiles.addAll(p.getAllCodePaths()); 5077 } 5078 } 5079 5080 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5081 PackageParser.Package changingLib) throws PackageManagerException { 5082 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5083 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5084 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5085 for (int i=0; i<N; i++) { 5086 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5087 if (file == null) { 5088 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5089 "Package " + pkg.packageName + " requires unavailable shared library " 5090 + pkg.usesLibraries.get(i) + "; failing!"); 5091 } 5092 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5093 } 5094 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5095 for (int i=0; i<N; i++) { 5096 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5097 if (file == null) { 5098 Slog.w(TAG, "Package " + pkg.packageName 5099 + " desires unavailable shared library " 5100 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5101 } else { 5102 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5103 } 5104 } 5105 N = usesLibraryFiles.size(); 5106 if (N > 0) { 5107 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5108 } else { 5109 pkg.usesLibraryFiles = null; 5110 } 5111 } 5112 } 5113 5114 private static boolean hasString(List<String> list, List<String> which) { 5115 if (list == null) { 5116 return false; 5117 } 5118 for (int i=list.size()-1; i>=0; i--) { 5119 for (int j=which.size()-1; j>=0; j--) { 5120 if (which.get(j).equals(list.get(i))) { 5121 return true; 5122 } 5123 } 5124 } 5125 return false; 5126 } 5127 5128 private void updateAllSharedLibrariesLPw() { 5129 for (PackageParser.Package pkg : mPackages.values()) { 5130 try { 5131 updateSharedLibrariesLPw(pkg, null); 5132 } catch (PackageManagerException e) { 5133 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5134 } 5135 } 5136 } 5137 5138 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5139 PackageParser.Package changingPkg) { 5140 ArrayList<PackageParser.Package> res = null; 5141 for (PackageParser.Package pkg : mPackages.values()) { 5142 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5143 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5144 if (res == null) { 5145 res = new ArrayList<PackageParser.Package>(); 5146 } 5147 res.add(pkg); 5148 try { 5149 updateSharedLibrariesLPw(pkg, changingPkg); 5150 } catch (PackageManagerException e) { 5151 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5152 } 5153 } 5154 } 5155 return res; 5156 } 5157 5158 /** 5159 * Derive the value of the {@code cpuAbiOverride} based on the provided 5160 * value and an optional stored value from the package settings. 5161 */ 5162 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5163 String cpuAbiOverride = null; 5164 5165 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5166 cpuAbiOverride = null; 5167 } else if (abiOverride != null) { 5168 cpuAbiOverride = abiOverride; 5169 } else if (settings != null) { 5170 cpuAbiOverride = settings.cpuAbiOverrideString; 5171 } 5172 5173 return cpuAbiOverride; 5174 } 5175 5176 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5177 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5178 boolean success = false; 5179 try { 5180 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5181 currentTime, user); 5182 success = true; 5183 return res; 5184 } finally { 5185 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5186 removeDataDirsLI(pkg.packageName); 5187 } 5188 } 5189 } 5190 5191 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5192 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5193 final File scanFile = new File(pkg.codePath); 5194 if (pkg.applicationInfo.getCodePath() == null || 5195 pkg.applicationInfo.getResourcePath() == null) { 5196 // Bail out. The resource and code paths haven't been set. 5197 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5198 "Code and resource paths haven't been set correctly"); 5199 } 5200 5201 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5202 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5203 } else { 5204 // Only allow system apps to be flagged as core apps. 5205 pkg.coreApp = false; 5206 } 5207 5208 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5209 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5210 } 5211 5212 if (mCustomResolverComponentName != null && 5213 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5214 setUpCustomResolverActivity(pkg); 5215 } 5216 5217 if (pkg.packageName.equals("android")) { 5218 synchronized (mPackages) { 5219 if (mAndroidApplication != null) { 5220 Slog.w(TAG, "*************************************************"); 5221 Slog.w(TAG, "Core android package being redefined. Skipping."); 5222 Slog.w(TAG, " file=" + scanFile); 5223 Slog.w(TAG, "*************************************************"); 5224 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5225 "Core android package being redefined. Skipping."); 5226 } 5227 5228 // Set up information for our fall-back user intent resolution activity. 5229 mPlatformPackage = pkg; 5230 pkg.mVersionCode = mSdkVersion; 5231 mAndroidApplication = pkg.applicationInfo; 5232 5233 if (!mResolverReplaced) { 5234 mResolveActivity.applicationInfo = mAndroidApplication; 5235 mResolveActivity.name = ResolverActivity.class.getName(); 5236 mResolveActivity.packageName = mAndroidApplication.packageName; 5237 mResolveActivity.processName = "system:ui"; 5238 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5239 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5240 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5241 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5242 mResolveActivity.exported = true; 5243 mResolveActivity.enabled = true; 5244 mResolveInfo.activityInfo = mResolveActivity; 5245 mResolveInfo.priority = 0; 5246 mResolveInfo.preferredOrder = 0; 5247 mResolveInfo.match = 0; 5248 mResolveComponentName = new ComponentName( 5249 mAndroidApplication.packageName, mResolveActivity.name); 5250 } 5251 } 5252 } 5253 5254 if (DEBUG_PACKAGE_SCANNING) { 5255 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5256 Log.d(TAG, "Scanning package " + pkg.packageName); 5257 } 5258 5259 if (mPackages.containsKey(pkg.packageName) 5260 || mSharedLibraries.containsKey(pkg.packageName)) { 5261 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5262 "Application package " + pkg.packageName 5263 + " already installed. Skipping duplicate."); 5264 } 5265 5266 // Initialize package source and resource directories 5267 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5268 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5269 5270 SharedUserSetting suid = null; 5271 PackageSetting pkgSetting = null; 5272 5273 if (!isSystemApp(pkg)) { 5274 // Only system apps can use these features. 5275 pkg.mOriginalPackages = null; 5276 pkg.mRealPackage = null; 5277 pkg.mAdoptPermissions = null; 5278 } 5279 5280 // writer 5281 synchronized (mPackages) { 5282 if (pkg.mSharedUserId != null) { 5283 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5284 if (suid == null) { 5285 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5286 "Creating application package " + pkg.packageName 5287 + " for shared user failed"); 5288 } 5289 if (DEBUG_PACKAGE_SCANNING) { 5290 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5291 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5292 + "): packages=" + suid.packages); 5293 } 5294 } 5295 5296 // Check if we are renaming from an original package name. 5297 PackageSetting origPackage = null; 5298 String realName = null; 5299 if (pkg.mOriginalPackages != null) { 5300 // This package may need to be renamed to a previously 5301 // installed name. Let's check on that... 5302 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5303 if (pkg.mOriginalPackages.contains(renamed)) { 5304 // This package had originally been installed as the 5305 // original name, and we have already taken care of 5306 // transitioning to the new one. Just update the new 5307 // one to continue using the old name. 5308 realName = pkg.mRealPackage; 5309 if (!pkg.packageName.equals(renamed)) { 5310 // Callers into this function may have already taken 5311 // care of renaming the package; only do it here if 5312 // it is not already done. 5313 pkg.setPackageName(renamed); 5314 } 5315 5316 } else { 5317 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5318 if ((origPackage = mSettings.peekPackageLPr( 5319 pkg.mOriginalPackages.get(i))) != null) { 5320 // We do have the package already installed under its 5321 // original name... should we use it? 5322 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5323 // New package is not compatible with original. 5324 origPackage = null; 5325 continue; 5326 } else if (origPackage.sharedUser != null) { 5327 // Make sure uid is compatible between packages. 5328 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5329 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5330 + " to " + pkg.packageName + ": old uid " 5331 + origPackage.sharedUser.name 5332 + " differs from " + pkg.mSharedUserId); 5333 origPackage = null; 5334 continue; 5335 } 5336 } else { 5337 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5338 + pkg.packageName + " to old name " + origPackage.name); 5339 } 5340 break; 5341 } 5342 } 5343 } 5344 } 5345 5346 if (mTransferedPackages.contains(pkg.packageName)) { 5347 Slog.w(TAG, "Package " + pkg.packageName 5348 + " was transferred to another, but its .apk remains"); 5349 } 5350 5351 // Just create the setting, don't add it yet. For already existing packages 5352 // the PkgSetting exists already and doesn't have to be created. 5353 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5354 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5355 pkg.applicationInfo.primaryCpuAbi, 5356 pkg.applicationInfo.secondaryCpuAbi, 5357 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5358 user, false); 5359 if (pkgSetting == null) { 5360 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5361 "Creating application package " + pkg.packageName + " failed"); 5362 } 5363 5364 if (pkgSetting.origPackage != null) { 5365 // If we are first transitioning from an original package, 5366 // fix up the new package's name now. We need to do this after 5367 // looking up the package under its new name, so getPackageLP 5368 // can take care of fiddling things correctly. 5369 pkg.setPackageName(origPackage.name); 5370 5371 // File a report about this. 5372 String msg = "New package " + pkgSetting.realName 5373 + " renamed to replace old package " + pkgSetting.name; 5374 reportSettingsProblem(Log.WARN, msg); 5375 5376 // Make a note of it. 5377 mTransferedPackages.add(origPackage.name); 5378 5379 // No longer need to retain this. 5380 pkgSetting.origPackage = null; 5381 } 5382 5383 if (realName != null) { 5384 // Make a note of it. 5385 mTransferedPackages.add(pkg.packageName); 5386 } 5387 5388 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5389 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5390 } 5391 5392 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5393 // Check all shared libraries and map to their actual file path. 5394 // We only do this here for apps not on a system dir, because those 5395 // are the only ones that can fail an install due to this. We 5396 // will take care of the system apps by updating all of their 5397 // library paths after the scan is done. 5398 updateSharedLibrariesLPw(pkg, null); 5399 } 5400 5401 if (mFoundPolicyFile) { 5402 SELinuxMMAC.assignSeinfoValue(pkg); 5403 } 5404 5405 pkg.applicationInfo.uid = pkgSetting.appId; 5406 pkg.mExtras = pkgSetting; 5407 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5408 try { 5409 verifySignaturesLP(pkgSetting, pkg); 5410 } catch (PackageManagerException e) { 5411 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5412 throw e; 5413 } 5414 // The signature has changed, but this package is in the system 5415 // image... let's recover! 5416 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5417 // However... if this package is part of a shared user, but it 5418 // doesn't match the signature of the shared user, let's fail. 5419 // What this means is that you can't change the signatures 5420 // associated with an overall shared user, which doesn't seem all 5421 // that unreasonable. 5422 if (pkgSetting.sharedUser != null) { 5423 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5424 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5425 throw new PackageManagerException( 5426 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5427 "Signature mismatch for shared user : " 5428 + pkgSetting.sharedUser); 5429 } 5430 } 5431 // File a report about this. 5432 String msg = "System package " + pkg.packageName 5433 + " signature changed; retaining data."; 5434 reportSettingsProblem(Log.WARN, msg); 5435 } 5436 } else { 5437 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5438 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5439 + pkg.packageName + " upgrade keys do not match the " 5440 + "previously installed version"); 5441 } else { 5442 // signatures may have changed as result of upgrade 5443 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5444 } 5445 } 5446 // Verify that this new package doesn't have any content providers 5447 // that conflict with existing packages. Only do this if the 5448 // package isn't already installed, since we don't want to break 5449 // things that are installed. 5450 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5451 final int N = pkg.providers.size(); 5452 int i; 5453 for (i=0; i<N; i++) { 5454 PackageParser.Provider p = pkg.providers.get(i); 5455 if (p.info.authority != null) { 5456 String names[] = p.info.authority.split(";"); 5457 for (int j = 0; j < names.length; j++) { 5458 if (mProvidersByAuthority.containsKey(names[j])) { 5459 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5460 final String otherPackageName = 5461 ((other != null && other.getComponentName() != null) ? 5462 other.getComponentName().getPackageName() : "?"); 5463 throw new PackageManagerException( 5464 INSTALL_FAILED_CONFLICTING_PROVIDER, 5465 "Can't install because provider name " + names[j] 5466 + " (in package " + pkg.applicationInfo.packageName 5467 + ") is already used by " + otherPackageName); 5468 } 5469 } 5470 } 5471 } 5472 } 5473 5474 if (pkg.mAdoptPermissions != null) { 5475 // This package wants to adopt ownership of permissions from 5476 // another package. 5477 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5478 final String origName = pkg.mAdoptPermissions.get(i); 5479 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5480 if (orig != null) { 5481 if (verifyPackageUpdateLPr(orig, pkg)) { 5482 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5483 + pkg.packageName); 5484 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5485 } 5486 } 5487 } 5488 } 5489 } 5490 5491 final String pkgName = pkg.packageName; 5492 5493 final long scanFileTime = scanFile.lastModified(); 5494 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5495 pkg.applicationInfo.processName = fixProcessName( 5496 pkg.applicationInfo.packageName, 5497 pkg.applicationInfo.processName, 5498 pkg.applicationInfo.uid); 5499 5500 File dataPath; 5501 if (mPlatformPackage == pkg) { 5502 // The system package is special. 5503 dataPath = new File(Environment.getDataDirectory(), "system"); 5504 5505 pkg.applicationInfo.dataDir = dataPath.getPath(); 5506 5507 } else { 5508 // This is a normal package, need to make its data directory. 5509 dataPath = getDataPathForPackage(pkg.packageName, 0); 5510 5511 boolean uidError = false; 5512 if (dataPath.exists()) { 5513 int currentUid = 0; 5514 try { 5515 StructStat stat = Os.stat(dataPath.getPath()); 5516 currentUid = stat.st_uid; 5517 } catch (ErrnoException e) { 5518 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5519 } 5520 5521 // If we have mismatched owners for the data path, we have a problem. 5522 if (currentUid != pkg.applicationInfo.uid) { 5523 boolean recovered = false; 5524 if (currentUid == 0) { 5525 // The directory somehow became owned by root. Wow. 5526 // This is probably because the system was stopped while 5527 // installd was in the middle of messing with its libs 5528 // directory. Ask installd to fix that. 5529 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5530 pkg.applicationInfo.uid); 5531 if (ret >= 0) { 5532 recovered = true; 5533 String msg = "Package " + pkg.packageName 5534 + " unexpectedly changed to uid 0; recovered to " + 5535 + pkg.applicationInfo.uid; 5536 reportSettingsProblem(Log.WARN, msg); 5537 } 5538 } 5539 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5540 || (scanFlags&SCAN_BOOTING) != 0)) { 5541 // If this is a system app, we can at least delete its 5542 // current data so the application will still work. 5543 int ret = removeDataDirsLI(pkgName); 5544 if (ret >= 0) { 5545 // TODO: Kill the processes first 5546 // Old data gone! 5547 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5548 ? "System package " : "Third party package "; 5549 String msg = prefix + pkg.packageName 5550 + " has changed from uid: " 5551 + currentUid + " to " 5552 + pkg.applicationInfo.uid + "; old data erased"; 5553 reportSettingsProblem(Log.WARN, msg); 5554 recovered = true; 5555 5556 // And now re-install the app. 5557 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5558 pkg.applicationInfo.seinfo); 5559 if (ret == -1) { 5560 // Ack should not happen! 5561 msg = prefix + pkg.packageName 5562 + " could not have data directory re-created after delete."; 5563 reportSettingsProblem(Log.WARN, msg); 5564 throw new PackageManagerException( 5565 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5566 } 5567 } 5568 if (!recovered) { 5569 mHasSystemUidErrors = true; 5570 } 5571 } else if (!recovered) { 5572 // If we allow this install to proceed, we will be broken. 5573 // Abort, abort! 5574 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5575 "scanPackageLI"); 5576 } 5577 if (!recovered) { 5578 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5579 + pkg.applicationInfo.uid + "/fs_" 5580 + currentUid; 5581 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5582 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5583 String msg = "Package " + pkg.packageName 5584 + " has mismatched uid: " 5585 + currentUid + " on disk, " 5586 + pkg.applicationInfo.uid + " in settings"; 5587 // writer 5588 synchronized (mPackages) { 5589 mSettings.mReadMessages.append(msg); 5590 mSettings.mReadMessages.append('\n'); 5591 uidError = true; 5592 if (!pkgSetting.uidError) { 5593 reportSettingsProblem(Log.ERROR, msg); 5594 } 5595 } 5596 } 5597 } 5598 pkg.applicationInfo.dataDir = dataPath.getPath(); 5599 if (mShouldRestoreconData) { 5600 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5601 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5602 pkg.applicationInfo.uid); 5603 } 5604 } else { 5605 if (DEBUG_PACKAGE_SCANNING) { 5606 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5607 Log.v(TAG, "Want this data dir: " + dataPath); 5608 } 5609 //invoke installer to do the actual installation 5610 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5611 pkg.applicationInfo.seinfo); 5612 if (ret < 0) { 5613 // Error from installer 5614 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5615 "Unable to create data dirs [errorCode=" + ret + "]"); 5616 } 5617 5618 if (dataPath.exists()) { 5619 pkg.applicationInfo.dataDir = dataPath.getPath(); 5620 } else { 5621 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5622 pkg.applicationInfo.dataDir = null; 5623 } 5624 } 5625 5626 pkgSetting.uidError = uidError; 5627 } 5628 5629 final String path = scanFile.getPath(); 5630 final String codePath = pkg.applicationInfo.getCodePath(); 5631 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5632 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5633 setBundledAppAbisAndRoots(pkg, pkgSetting); 5634 5635 // If we haven't found any native libraries for the app, check if it has 5636 // renderscript code. We'll need to force the app to 32 bit if it has 5637 // renderscript bitcode. 5638 if (pkg.applicationInfo.primaryCpuAbi == null 5639 && pkg.applicationInfo.secondaryCpuAbi == null 5640 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5641 NativeLibraryHelper.Handle handle = null; 5642 try { 5643 handle = NativeLibraryHelper.Handle.create(scanFile); 5644 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5645 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5646 } 5647 } catch (IOException ioe) { 5648 Slog.w(TAG, "Error scanning system app : " + ioe); 5649 } finally { 5650 IoUtils.closeQuietly(handle); 5651 } 5652 } 5653 5654 setNativeLibraryPaths(pkg); 5655 } else { 5656 // TODO: We can probably be smarter about this stuff. For installed apps, 5657 // we can calculate this information at install time once and for all. For 5658 // system apps, we can probably assume that this information doesn't change 5659 // after the first boot scan. As things stand, we do lots of unnecessary work. 5660 5661 // Give ourselves some initial paths; we'll come back for another 5662 // pass once we've determined ABI below. 5663 setNativeLibraryPaths(pkg); 5664 5665 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5666 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5667 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5668 5669 NativeLibraryHelper.Handle handle = null; 5670 try { 5671 handle = NativeLibraryHelper.Handle.create(scanFile); 5672 // TODO(multiArch): This can be null for apps that didn't go through the 5673 // usual installation process. We can calculate it again, like we 5674 // do during install time. 5675 // 5676 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5677 // unnecessary. 5678 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5679 5680 // Null out the abis so that they can be recalculated. 5681 pkg.applicationInfo.primaryCpuAbi = null; 5682 pkg.applicationInfo.secondaryCpuAbi = null; 5683 if (isMultiArch(pkg.applicationInfo)) { 5684 // Warn if we've set an abiOverride for multi-lib packages.. 5685 // By definition, we need to copy both 32 and 64 bit libraries for 5686 // such packages. 5687 if (pkg.cpuAbiOverride != null 5688 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5689 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5690 } 5691 5692 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5693 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5694 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5695 if (isAsec) { 5696 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5697 } else { 5698 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5699 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5700 useIsaSpecificSubdirs); 5701 } 5702 } 5703 5704 maybeThrowExceptionForMultiArchCopy( 5705 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5706 5707 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5708 if (isAsec) { 5709 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5710 } else { 5711 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5712 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5713 useIsaSpecificSubdirs); 5714 } 5715 } 5716 5717 maybeThrowExceptionForMultiArchCopy( 5718 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5719 5720 if (abi64 >= 0) { 5721 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5722 } 5723 5724 if (abi32 >= 0) { 5725 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5726 if (abi64 >= 0) { 5727 pkg.applicationInfo.secondaryCpuAbi = abi; 5728 } else { 5729 pkg.applicationInfo.primaryCpuAbi = abi; 5730 } 5731 } 5732 } else { 5733 String[] abiList = (cpuAbiOverride != null) ? 5734 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5735 5736 // Enable gross and lame hacks for apps that are built with old 5737 // SDK tools. We must scan their APKs for renderscript bitcode and 5738 // not launch them if it's present. Don't bother checking on devices 5739 // that don't have 64 bit support. 5740 boolean needsRenderScriptOverride = false; 5741 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5742 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5743 abiList = Build.SUPPORTED_32_BIT_ABIS; 5744 needsRenderScriptOverride = true; 5745 } 5746 5747 final int copyRet; 5748 if (isAsec) { 5749 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5750 } else { 5751 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5752 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5753 } 5754 5755 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5756 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5757 "Error unpackaging native libs for app, errorCode=" + copyRet); 5758 } 5759 5760 if (copyRet >= 0) { 5761 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5762 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5763 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5764 } else if (needsRenderScriptOverride) { 5765 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5766 } 5767 } 5768 } catch (IOException ioe) { 5769 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5770 } finally { 5771 IoUtils.closeQuietly(handle); 5772 } 5773 5774 // Now that we've calculated the ABIs and determined if it's an internal app, 5775 // we will go ahead and populate the nativeLibraryPath. 5776 setNativeLibraryPaths(pkg); 5777 5778 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5779 final int[] userIds = sUserManager.getUserIds(); 5780 synchronized (mInstallLock) { 5781 // Create a native library symlink only if we have native libraries 5782 // and if the native libraries are 32 bit libraries. We do not provide 5783 // this symlink for 64 bit libraries. 5784 if (pkg.applicationInfo.primaryCpuAbi != null && 5785 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5786 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5787 for (int userId : userIds) { 5788 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5789 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5790 "Failed linking native library dir (user=" + userId + ")"); 5791 } 5792 } 5793 } 5794 } 5795 } 5796 5797 // This is a special case for the "system" package, where the ABI is 5798 // dictated by the zygote configuration (and init.rc). We should keep track 5799 // of this ABI so that we can deal with "normal" applications that run under 5800 // the same UID correctly. 5801 if (mPlatformPackage == pkg) { 5802 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5803 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5804 } 5805 5806 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5807 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5808 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5809 // Copy the derived override back to the parsed package, so that we can 5810 // update the package settings accordingly. 5811 pkg.cpuAbiOverride = cpuAbiOverride; 5812 5813 if (DEBUG_ABI_SELECTION) { 5814 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5815 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5816 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5817 } 5818 5819 // Push the derived path down into PackageSettings so we know what to 5820 // clean up at uninstall time. 5821 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5822 5823 if (DEBUG_ABI_SELECTION) { 5824 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5825 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5826 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5827 } 5828 5829 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5830 // We don't do this here during boot because we can do it all 5831 // at once after scanning all existing packages. 5832 // 5833 // We also do this *before* we perform dexopt on this package, so that 5834 // we can avoid redundant dexopts, and also to make sure we've got the 5835 // code and package path correct. 5836 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5837 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5838 } 5839 5840 if ((scanFlags & SCAN_NO_DEX) == 0) { 5841 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, 5842 (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { 5843 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5844 } 5845 } 5846 5847 if (mFactoryTest && pkg.requestedPermissions.contains( 5848 android.Manifest.permission.FACTORY_TEST)) { 5849 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5850 } 5851 5852 ArrayList<PackageParser.Package> clientLibPkgs = null; 5853 5854 // writer 5855 synchronized (mPackages) { 5856 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5857 // Only system apps can add new shared libraries. 5858 if (pkg.libraryNames != null) { 5859 for (int i=0; i<pkg.libraryNames.size(); i++) { 5860 String name = pkg.libraryNames.get(i); 5861 boolean allowed = false; 5862 if (isUpdatedSystemApp(pkg)) { 5863 // New library entries can only be added through the 5864 // system image. This is important to get rid of a lot 5865 // of nasty edge cases: for example if we allowed a non- 5866 // system update of the app to add a library, then uninstalling 5867 // the update would make the library go away, and assumptions 5868 // we made such as through app install filtering would now 5869 // have allowed apps on the device which aren't compatible 5870 // with it. Better to just have the restriction here, be 5871 // conservative, and create many fewer cases that can negatively 5872 // impact the user experience. 5873 final PackageSetting sysPs = mSettings 5874 .getDisabledSystemPkgLPr(pkg.packageName); 5875 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5876 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5877 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5878 allowed = true; 5879 allowed = true; 5880 break; 5881 } 5882 } 5883 } 5884 } else { 5885 allowed = true; 5886 } 5887 if (allowed) { 5888 if (!mSharedLibraries.containsKey(name)) { 5889 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5890 } else if (!name.equals(pkg.packageName)) { 5891 Slog.w(TAG, "Package " + pkg.packageName + " library " 5892 + name + " already exists; skipping"); 5893 } 5894 } else { 5895 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5896 + name + " that is not declared on system image; skipping"); 5897 } 5898 } 5899 if ((scanFlags&SCAN_BOOTING) == 0) { 5900 // If we are not booting, we need to update any applications 5901 // that are clients of our shared library. If we are booting, 5902 // this will all be done once the scan is complete. 5903 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5904 } 5905 } 5906 } 5907 } 5908 5909 // We also need to dexopt any apps that are dependent on this library. Note that 5910 // if these fail, we should abort the install since installing the library will 5911 // result in some apps being broken. 5912 if (clientLibPkgs != null) { 5913 if ((scanFlags & SCAN_NO_DEX) == 0) { 5914 for (int i = 0; i < clientLibPkgs.size(); i++) { 5915 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5916 if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex, 5917 (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { 5918 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5919 "scanPackageLI failed to dexopt clientLibPkgs"); 5920 } 5921 } 5922 } 5923 } 5924 5925 // Request the ActivityManager to kill the process(only for existing packages) 5926 // so that we do not end up in a confused state while the user is still using the older 5927 // version of the application while the new one gets installed. 5928 if ((scanFlags & SCAN_REPLACING) != 0) { 5929 killApplication(pkg.applicationInfo.packageName, 5930 pkg.applicationInfo.uid, "update pkg"); 5931 } 5932 5933 // Also need to kill any apps that are dependent on the library. 5934 if (clientLibPkgs != null) { 5935 for (int i=0; i<clientLibPkgs.size(); i++) { 5936 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5937 killApplication(clientPkg.applicationInfo.packageName, 5938 clientPkg.applicationInfo.uid, "update lib"); 5939 } 5940 } 5941 5942 // writer 5943 synchronized (mPackages) { 5944 // We don't expect installation to fail beyond this point 5945 5946 // Add the new setting to mSettings 5947 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5948 // Add the new setting to mPackages 5949 mPackages.put(pkg.applicationInfo.packageName, pkg); 5950 // Make sure we don't accidentally delete its data. 5951 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5952 while (iter.hasNext()) { 5953 PackageCleanItem item = iter.next(); 5954 if (pkgName.equals(item.packageName)) { 5955 iter.remove(); 5956 } 5957 } 5958 5959 // Take care of first install / last update times. 5960 if (currentTime != 0) { 5961 if (pkgSetting.firstInstallTime == 0) { 5962 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5963 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5964 pkgSetting.lastUpdateTime = currentTime; 5965 } 5966 } else if (pkgSetting.firstInstallTime == 0) { 5967 // We need *something*. Take time time stamp of the file. 5968 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5969 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5970 if (scanFileTime != pkgSetting.timeStamp) { 5971 // A package on the system image has changed; consider this 5972 // to be an update. 5973 pkgSetting.lastUpdateTime = scanFileTime; 5974 } 5975 } 5976 5977 // Add the package's KeySets to the global KeySetManagerService 5978 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5979 try { 5980 // Old KeySetData no longer valid. 5981 ksms.removeAppKeySetDataLPw(pkg.packageName); 5982 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5983 if (pkg.mKeySetMapping != null) { 5984 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5985 pkg.mKeySetMapping.entrySet()) { 5986 if (entry.getValue() != null) { 5987 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5988 entry.getValue(), entry.getKey()); 5989 } 5990 } 5991 if (pkg.mUpgradeKeySets != null) { 5992 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5993 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5994 } 5995 } 5996 } 5997 } catch (NullPointerException e) { 5998 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5999 } catch (IllegalArgumentException e) { 6000 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6001 } 6002 6003 int N = pkg.providers.size(); 6004 StringBuilder r = null; 6005 int i; 6006 for (i=0; i<N; i++) { 6007 PackageParser.Provider p = pkg.providers.get(i); 6008 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6009 p.info.processName, pkg.applicationInfo.uid); 6010 mProviders.addProvider(p); 6011 p.syncable = p.info.isSyncable; 6012 if (p.info.authority != null) { 6013 String names[] = p.info.authority.split(";"); 6014 p.info.authority = null; 6015 for (int j = 0; j < names.length; j++) { 6016 if (j == 1 && p.syncable) { 6017 // We only want the first authority for a provider to possibly be 6018 // syncable, so if we already added this provider using a different 6019 // authority clear the syncable flag. We copy the provider before 6020 // changing it because the mProviders object contains a reference 6021 // to a provider that we don't want to change. 6022 // Only do this for the second authority since the resulting provider 6023 // object can be the same for all future authorities for this provider. 6024 p = new PackageParser.Provider(p); 6025 p.syncable = false; 6026 } 6027 if (!mProvidersByAuthority.containsKey(names[j])) { 6028 mProvidersByAuthority.put(names[j], p); 6029 if (p.info.authority == null) { 6030 p.info.authority = names[j]; 6031 } else { 6032 p.info.authority = p.info.authority + ";" + names[j]; 6033 } 6034 if (DEBUG_PACKAGE_SCANNING) { 6035 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6036 Log.d(TAG, "Registered content provider: " + names[j] 6037 + ", className = " + p.info.name + ", isSyncable = " 6038 + p.info.isSyncable); 6039 } 6040 } else { 6041 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6042 Slog.w(TAG, "Skipping provider name " + names[j] + 6043 " (in package " + pkg.applicationInfo.packageName + 6044 "): name already used by " 6045 + ((other != null && other.getComponentName() != null) 6046 ? other.getComponentName().getPackageName() : "?")); 6047 } 6048 } 6049 } 6050 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6051 if (r == null) { 6052 r = new StringBuilder(256); 6053 } else { 6054 r.append(' '); 6055 } 6056 r.append(p.info.name); 6057 } 6058 } 6059 if (r != null) { 6060 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6061 } 6062 6063 N = pkg.services.size(); 6064 r = null; 6065 for (i=0; i<N; i++) { 6066 PackageParser.Service s = pkg.services.get(i); 6067 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6068 s.info.processName, pkg.applicationInfo.uid); 6069 mServices.addService(s); 6070 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6071 if (r == null) { 6072 r = new StringBuilder(256); 6073 } else { 6074 r.append(' '); 6075 } 6076 r.append(s.info.name); 6077 } 6078 } 6079 if (r != null) { 6080 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6081 } 6082 6083 N = pkg.receivers.size(); 6084 r = null; 6085 for (i=0; i<N; i++) { 6086 PackageParser.Activity a = pkg.receivers.get(i); 6087 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6088 a.info.processName, pkg.applicationInfo.uid); 6089 mReceivers.addActivity(a, "receiver"); 6090 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6091 if (r == null) { 6092 r = new StringBuilder(256); 6093 } else { 6094 r.append(' '); 6095 } 6096 r.append(a.info.name); 6097 } 6098 } 6099 if (r != null) { 6100 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6101 } 6102 6103 N = pkg.activities.size(); 6104 r = null; 6105 for (i=0; i<N; i++) { 6106 PackageParser.Activity a = pkg.activities.get(i); 6107 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6108 a.info.processName, pkg.applicationInfo.uid); 6109 mActivities.addActivity(a, "activity"); 6110 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6111 if (r == null) { 6112 r = new StringBuilder(256); 6113 } else { 6114 r.append(' '); 6115 } 6116 r.append(a.info.name); 6117 } 6118 } 6119 if (r != null) { 6120 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6121 } 6122 6123 N = pkg.permissionGroups.size(); 6124 r = null; 6125 for (i=0; i<N; i++) { 6126 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6127 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6128 if (cur == null) { 6129 mPermissionGroups.put(pg.info.name, pg); 6130 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6131 if (r == null) { 6132 r = new StringBuilder(256); 6133 } else { 6134 r.append(' '); 6135 } 6136 r.append(pg.info.name); 6137 } 6138 } else { 6139 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6140 + pg.info.packageName + " ignored: original from " 6141 + cur.info.packageName); 6142 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6143 if (r == null) { 6144 r = new StringBuilder(256); 6145 } else { 6146 r.append(' '); 6147 } 6148 r.append("DUP:"); 6149 r.append(pg.info.name); 6150 } 6151 } 6152 } 6153 if (r != null) { 6154 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6155 } 6156 6157 N = pkg.permissions.size(); 6158 r = null; 6159 for (i=0; i<N; i++) { 6160 PackageParser.Permission p = pkg.permissions.get(i); 6161 HashMap<String, BasePermission> permissionMap = 6162 p.tree ? mSettings.mPermissionTrees 6163 : mSettings.mPermissions; 6164 p.group = mPermissionGroups.get(p.info.group); 6165 if (p.info.group == null || p.group != null) { 6166 BasePermission bp = permissionMap.get(p.info.name); 6167 6168 // Allow system apps to redefine non-system permissions 6169 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6170 final boolean currentOwnerIsSystem = (bp.perm != null 6171 && isSystemApp(bp.perm.owner)); 6172 if (isSystemApp(p.owner)) { 6173 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6174 // It's a built-in permission and no owner, take ownership now 6175 bp.packageSetting = pkgSetting; 6176 bp.perm = p; 6177 bp.uid = pkg.applicationInfo.uid; 6178 bp.sourcePackage = p.info.packageName; 6179 } else if (!currentOwnerIsSystem) { 6180 String msg = "New decl " + p.owner + " of permission " 6181 + p.info.name + " is system; overriding " + bp.sourcePackage; 6182 reportSettingsProblem(Log.WARN, msg); 6183 bp = null; 6184 } 6185 } 6186 } 6187 6188 if (bp == null) { 6189 bp = new BasePermission(p.info.name, p.info.packageName, 6190 BasePermission.TYPE_NORMAL); 6191 permissionMap.put(p.info.name, bp); 6192 } 6193 6194 if (bp.perm == null) { 6195 if (bp.sourcePackage == null 6196 || bp.sourcePackage.equals(p.info.packageName)) { 6197 BasePermission tree = findPermissionTreeLP(p.info.name); 6198 if (tree == null 6199 || tree.sourcePackage.equals(p.info.packageName)) { 6200 bp.packageSetting = pkgSetting; 6201 bp.perm = p; 6202 bp.uid = pkg.applicationInfo.uid; 6203 bp.sourcePackage = p.info.packageName; 6204 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6205 if (r == null) { 6206 r = new StringBuilder(256); 6207 } else { 6208 r.append(' '); 6209 } 6210 r.append(p.info.name); 6211 } 6212 } else { 6213 Slog.w(TAG, "Permission " + p.info.name + " from package " 6214 + p.info.packageName + " ignored: base tree " 6215 + tree.name + " is from package " 6216 + tree.sourcePackage); 6217 } 6218 } else { 6219 Slog.w(TAG, "Permission " + p.info.name + " from package " 6220 + p.info.packageName + " ignored: original from " 6221 + bp.sourcePackage); 6222 } 6223 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6224 if (r == null) { 6225 r = new StringBuilder(256); 6226 } else { 6227 r.append(' '); 6228 } 6229 r.append("DUP:"); 6230 r.append(p.info.name); 6231 } 6232 if (bp.perm == p) { 6233 bp.protectionLevel = p.info.protectionLevel; 6234 } 6235 } else { 6236 Slog.w(TAG, "Permission " + p.info.name + " from package " 6237 + p.info.packageName + " ignored: no group " 6238 + p.group); 6239 } 6240 } 6241 if (r != null) { 6242 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6243 } 6244 6245 N = pkg.instrumentation.size(); 6246 r = null; 6247 for (i=0; i<N; i++) { 6248 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6249 a.info.packageName = pkg.applicationInfo.packageName; 6250 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6251 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6252 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6253 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6254 a.info.dataDir = pkg.applicationInfo.dataDir; 6255 6256 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6257 // need other information about the application, like the ABI and what not ? 6258 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6259 mInstrumentation.put(a.getComponentName(), a); 6260 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6261 if (r == null) { 6262 r = new StringBuilder(256); 6263 } else { 6264 r.append(' '); 6265 } 6266 r.append(a.info.name); 6267 } 6268 } 6269 if (r != null) { 6270 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6271 } 6272 6273 if (pkg.protectedBroadcasts != null) { 6274 N = pkg.protectedBroadcasts.size(); 6275 for (i=0; i<N; i++) { 6276 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6277 } 6278 } 6279 6280 pkgSetting.setTimeStamp(scanFileTime); 6281 6282 // Create idmap files for pairs of (packages, overlay packages). 6283 // Note: "android", ie framework-res.apk, is handled by native layers. 6284 if (pkg.mOverlayTarget != null) { 6285 // This is an overlay package. 6286 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6287 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6288 mOverlays.put(pkg.mOverlayTarget, 6289 new HashMap<String, PackageParser.Package>()); 6290 } 6291 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6292 map.put(pkg.packageName, pkg); 6293 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6294 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6295 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6296 "scanPackageLI failed to createIdmap"); 6297 } 6298 } 6299 } else if (mOverlays.containsKey(pkg.packageName) && 6300 !pkg.packageName.equals("android")) { 6301 // This is a regular package, with one or more known overlay packages. 6302 createIdmapsForPackageLI(pkg); 6303 } 6304 } 6305 6306 return pkg; 6307 } 6308 6309 /** 6310 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6311 * i.e, so that all packages can be run inside a single process if required. 6312 * 6313 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6314 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6315 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6316 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6317 * updating a package that belongs to a shared user. 6318 * 6319 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6320 * adds unnecessary complexity. 6321 */ 6322 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6323 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6324 String requiredInstructionSet = null; 6325 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6326 requiredInstructionSet = VMRuntime.getInstructionSet( 6327 scannedPackage.applicationInfo.primaryCpuAbi); 6328 } 6329 6330 PackageSetting requirer = null; 6331 for (PackageSetting ps : packagesForUser) { 6332 // If packagesForUser contains scannedPackage, we skip it. This will happen 6333 // when scannedPackage is an update of an existing package. Without this check, 6334 // we will never be able to change the ABI of any package belonging to a shared 6335 // user, even if it's compatible with other packages. 6336 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6337 if (ps.primaryCpuAbiString == null) { 6338 continue; 6339 } 6340 6341 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6342 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6343 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6344 // this but there's not much we can do. 6345 String errorMessage = "Instruction set mismatch, " 6346 + ((requirer == null) ? "[caller]" : requirer) 6347 + " requires " + requiredInstructionSet + " whereas " + ps 6348 + " requires " + instructionSet; 6349 Slog.w(TAG, errorMessage); 6350 } 6351 6352 if (requiredInstructionSet == null) { 6353 requiredInstructionSet = instructionSet; 6354 requirer = ps; 6355 } 6356 } 6357 } 6358 6359 if (requiredInstructionSet != null) { 6360 String adjustedAbi; 6361 if (requirer != null) { 6362 // requirer != null implies that either scannedPackage was null or that scannedPackage 6363 // did not require an ABI, in which case we have to adjust scannedPackage to match 6364 // the ABI of the set (which is the same as requirer's ABI) 6365 adjustedAbi = requirer.primaryCpuAbiString; 6366 if (scannedPackage != null) { 6367 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6368 } 6369 } else { 6370 // requirer == null implies that we're updating all ABIs in the set to 6371 // match scannedPackage. 6372 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6373 } 6374 6375 for (PackageSetting ps : packagesForUser) { 6376 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6377 if (ps.primaryCpuAbiString != null) { 6378 continue; 6379 } 6380 6381 ps.primaryCpuAbiString = adjustedAbi; 6382 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6383 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6384 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6385 6386 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6387 deferDexOpt, true) == DEX_OPT_FAILED) { 6388 ps.primaryCpuAbiString = null; 6389 ps.pkg.applicationInfo.primaryCpuAbi = null; 6390 return; 6391 } else { 6392 mInstaller.rmdex(ps.codePathString, 6393 getDexCodeInstructionSet(getPreferredInstructionSet())); 6394 } 6395 } 6396 } 6397 } 6398 } 6399 } 6400 6401 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6402 synchronized (mPackages) { 6403 mResolverReplaced = true; 6404 // Set up information for custom user intent resolution activity. 6405 mResolveActivity.applicationInfo = pkg.applicationInfo; 6406 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6407 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6408 mResolveActivity.processName = null; 6409 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6410 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6411 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6412 mResolveActivity.theme = 0; 6413 mResolveActivity.exported = true; 6414 mResolveActivity.enabled = true; 6415 mResolveInfo.activityInfo = mResolveActivity; 6416 mResolveInfo.priority = 0; 6417 mResolveInfo.preferredOrder = 0; 6418 mResolveInfo.match = 0; 6419 mResolveComponentName = mCustomResolverComponentName; 6420 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6421 mResolveComponentName); 6422 } 6423 } 6424 6425 private static String calculateBundledApkRoot(final String codePathString) { 6426 final File codePath = new File(codePathString); 6427 final File codeRoot; 6428 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6429 codeRoot = Environment.getRootDirectory(); 6430 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6431 codeRoot = Environment.getOemDirectory(); 6432 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6433 codeRoot = Environment.getVendorDirectory(); 6434 } else { 6435 // Unrecognized code path; take its top real segment as the apk root: 6436 // e.g. /something/app/blah.apk => /something 6437 try { 6438 File f = codePath.getCanonicalFile(); 6439 File parent = f.getParentFile(); // non-null because codePath is a file 6440 File tmp; 6441 while ((tmp = parent.getParentFile()) != null) { 6442 f = parent; 6443 parent = tmp; 6444 } 6445 codeRoot = f; 6446 Slog.w(TAG, "Unrecognized code path " 6447 + codePath + " - using " + codeRoot); 6448 } catch (IOException e) { 6449 // Can't canonicalize the code path -- shenanigans? 6450 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6451 return Environment.getRootDirectory().getPath(); 6452 } 6453 } 6454 return codeRoot.getPath(); 6455 } 6456 6457 /** 6458 * Derive and set the location of native libraries for the given package, 6459 * which varies depending on where and how the package was installed. 6460 */ 6461 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6462 final ApplicationInfo info = pkg.applicationInfo; 6463 final String codePath = pkg.codePath; 6464 final File codeFile = new File(codePath); 6465 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6466 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6467 6468 info.nativeLibraryRootDir = null; 6469 info.nativeLibraryRootRequiresIsa = false; 6470 info.nativeLibraryDir = null; 6471 info.secondaryNativeLibraryDir = null; 6472 6473 if (isApkFile(codeFile)) { 6474 // Monolithic install 6475 if (bundledApp) { 6476 // If "/system/lib64/apkname" exists, assume that is the per-package 6477 // native library directory to use; otherwise use "/system/lib/apkname". 6478 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6479 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6480 getPrimaryInstructionSet(info)); 6481 6482 // This is a bundled system app so choose the path based on the ABI. 6483 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6484 // is just the default path. 6485 final String apkName = deriveCodePathName(codePath); 6486 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6487 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6488 apkName).getAbsolutePath(); 6489 6490 if (info.secondaryCpuAbi != null) { 6491 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6492 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6493 secondaryLibDir, apkName).getAbsolutePath(); 6494 } 6495 } else if (asecApp) { 6496 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6497 .getAbsolutePath(); 6498 } else { 6499 final String apkName = deriveCodePathName(codePath); 6500 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6501 .getAbsolutePath(); 6502 } 6503 6504 info.nativeLibraryRootRequiresIsa = false; 6505 info.nativeLibraryDir = info.nativeLibraryRootDir; 6506 } else { 6507 // Cluster install 6508 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6509 info.nativeLibraryRootRequiresIsa = true; 6510 6511 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6512 getPrimaryInstructionSet(info)).getAbsolutePath(); 6513 6514 if (info.secondaryCpuAbi != null) { 6515 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6516 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6517 } 6518 } 6519 } 6520 6521 /** 6522 * Calculate the abis and roots for a bundled app. These can uniquely 6523 * be determined from the contents of the system partition, i.e whether 6524 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6525 * of this information, and instead assume that the system was built 6526 * sensibly. 6527 */ 6528 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6529 PackageSetting pkgSetting) { 6530 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6531 6532 // If "/system/lib64/apkname" exists, assume that is the per-package 6533 // native library directory to use; otherwise use "/system/lib/apkname". 6534 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6535 setBundledAppAbi(pkg, apkRoot, apkName); 6536 // pkgSetting might be null during rescan following uninstall of updates 6537 // to a bundled app, so accommodate that possibility. The settings in 6538 // that case will be established later from the parsed package. 6539 // 6540 // If the settings aren't null, sync them up with what we've just derived. 6541 // note that apkRoot isn't stored in the package settings. 6542 if (pkgSetting != null) { 6543 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6544 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6545 } 6546 } 6547 6548 /** 6549 * Deduces the ABI of a bundled app and sets the relevant fields on the 6550 * parsed pkg object. 6551 * 6552 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6553 * under which system libraries are installed. 6554 * @param apkName the name of the installed package. 6555 */ 6556 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6557 final File codeFile = new File(pkg.codePath); 6558 6559 final boolean has64BitLibs; 6560 final boolean has32BitLibs; 6561 if (isApkFile(codeFile)) { 6562 // Monolithic install 6563 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6564 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6565 } else { 6566 // Cluster install 6567 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6568 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6569 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6570 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6571 has64BitLibs = (new File(rootDir, isa)).exists(); 6572 } else { 6573 has64BitLibs = false; 6574 } 6575 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6576 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6577 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6578 has32BitLibs = (new File(rootDir, isa)).exists(); 6579 } else { 6580 has32BitLibs = false; 6581 } 6582 } 6583 6584 if (has64BitLibs && !has32BitLibs) { 6585 // The package has 64 bit libs, but not 32 bit libs. Its primary 6586 // ABI should be 64 bit. We can safely assume here that the bundled 6587 // native libraries correspond to the most preferred ABI in the list. 6588 6589 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6590 pkg.applicationInfo.secondaryCpuAbi = null; 6591 } else if (has32BitLibs && !has64BitLibs) { 6592 // The package has 32 bit libs but not 64 bit libs. Its primary 6593 // ABI should be 32 bit. 6594 6595 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6596 pkg.applicationInfo.secondaryCpuAbi = null; 6597 } else if (has32BitLibs && has64BitLibs) { 6598 // The application has both 64 and 32 bit bundled libraries. We check 6599 // here that the app declares multiArch support, and warn if it doesn't. 6600 // 6601 // We will be lenient here and record both ABIs. The primary will be the 6602 // ABI that's higher on the list, i.e, a device that's configured to prefer 6603 // 64 bit apps will see a 64 bit primary ABI, 6604 6605 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6606 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6607 } 6608 6609 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6610 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6611 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6612 } else { 6613 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6614 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6615 } 6616 } else { 6617 pkg.applicationInfo.primaryCpuAbi = null; 6618 pkg.applicationInfo.secondaryCpuAbi = null; 6619 } 6620 } 6621 6622 private void killApplication(String pkgName, int appId, String reason) { 6623 // Request the ActivityManager to kill the process(only for existing packages) 6624 // so that we do not end up in a confused state while the user is still using the older 6625 // version of the application while the new one gets installed. 6626 IActivityManager am = ActivityManagerNative.getDefault(); 6627 if (am != null) { 6628 try { 6629 am.killApplicationWithAppId(pkgName, appId, reason); 6630 } catch (RemoteException e) { 6631 } 6632 } 6633 } 6634 6635 void removePackageLI(PackageSetting ps, boolean chatty) { 6636 if (DEBUG_INSTALL) { 6637 if (chatty) 6638 Log.d(TAG, "Removing package " + ps.name); 6639 } 6640 6641 // writer 6642 synchronized (mPackages) { 6643 mPackages.remove(ps.name); 6644 final PackageParser.Package pkg = ps.pkg; 6645 if (pkg != null) { 6646 cleanPackageDataStructuresLILPw(pkg, chatty); 6647 } 6648 } 6649 } 6650 6651 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6652 if (DEBUG_INSTALL) { 6653 if (chatty) 6654 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6655 } 6656 6657 // writer 6658 synchronized (mPackages) { 6659 mPackages.remove(pkg.applicationInfo.packageName); 6660 cleanPackageDataStructuresLILPw(pkg, chatty); 6661 } 6662 } 6663 6664 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6665 int N = pkg.providers.size(); 6666 StringBuilder r = null; 6667 int i; 6668 for (i=0; i<N; i++) { 6669 PackageParser.Provider p = pkg.providers.get(i); 6670 mProviders.removeProvider(p); 6671 if (p.info.authority == null) { 6672 6673 /* There was another ContentProvider with this authority when 6674 * this app was installed so this authority is null, 6675 * Ignore it as we don't have to unregister the provider. 6676 */ 6677 continue; 6678 } 6679 String names[] = p.info.authority.split(";"); 6680 for (int j = 0; j < names.length; j++) { 6681 if (mProvidersByAuthority.get(names[j]) == p) { 6682 mProvidersByAuthority.remove(names[j]); 6683 if (DEBUG_REMOVE) { 6684 if (chatty) 6685 Log.d(TAG, "Unregistered content provider: " + names[j] 6686 + ", className = " + p.info.name + ", isSyncable = " 6687 + p.info.isSyncable); 6688 } 6689 } 6690 } 6691 if (DEBUG_REMOVE && chatty) { 6692 if (r == null) { 6693 r = new StringBuilder(256); 6694 } else { 6695 r.append(' '); 6696 } 6697 r.append(p.info.name); 6698 } 6699 } 6700 if (r != null) { 6701 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6702 } 6703 6704 N = pkg.services.size(); 6705 r = null; 6706 for (i=0; i<N; i++) { 6707 PackageParser.Service s = pkg.services.get(i); 6708 mServices.removeService(s); 6709 if (chatty) { 6710 if (r == null) { 6711 r = new StringBuilder(256); 6712 } else { 6713 r.append(' '); 6714 } 6715 r.append(s.info.name); 6716 } 6717 } 6718 if (r != null) { 6719 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6720 } 6721 6722 N = pkg.receivers.size(); 6723 r = null; 6724 for (i=0; i<N; i++) { 6725 PackageParser.Activity a = pkg.receivers.get(i); 6726 mReceivers.removeActivity(a, "receiver"); 6727 if (DEBUG_REMOVE && chatty) { 6728 if (r == null) { 6729 r = new StringBuilder(256); 6730 } else { 6731 r.append(' '); 6732 } 6733 r.append(a.info.name); 6734 } 6735 } 6736 if (r != null) { 6737 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6738 } 6739 6740 N = pkg.activities.size(); 6741 r = null; 6742 for (i=0; i<N; i++) { 6743 PackageParser.Activity a = pkg.activities.get(i); 6744 mActivities.removeActivity(a, "activity"); 6745 if (DEBUG_REMOVE && chatty) { 6746 if (r == null) { 6747 r = new StringBuilder(256); 6748 } else { 6749 r.append(' '); 6750 } 6751 r.append(a.info.name); 6752 } 6753 } 6754 if (r != null) { 6755 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6756 } 6757 6758 N = pkg.permissions.size(); 6759 r = null; 6760 for (i=0; i<N; i++) { 6761 PackageParser.Permission p = pkg.permissions.get(i); 6762 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6763 if (bp == null) { 6764 bp = mSettings.mPermissionTrees.get(p.info.name); 6765 } 6766 if (bp != null && bp.perm == p) { 6767 bp.perm = null; 6768 if (DEBUG_REMOVE && chatty) { 6769 if (r == null) { 6770 r = new StringBuilder(256); 6771 } else { 6772 r.append(' '); 6773 } 6774 r.append(p.info.name); 6775 } 6776 } 6777 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6778 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6779 if (appOpPerms != null) { 6780 appOpPerms.remove(pkg.packageName); 6781 } 6782 } 6783 } 6784 if (r != null) { 6785 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6786 } 6787 6788 N = pkg.requestedPermissions.size(); 6789 r = null; 6790 for (i=0; i<N; i++) { 6791 String perm = pkg.requestedPermissions.get(i); 6792 BasePermission bp = mSettings.mPermissions.get(perm); 6793 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6794 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6795 if (appOpPerms != null) { 6796 appOpPerms.remove(pkg.packageName); 6797 if (appOpPerms.isEmpty()) { 6798 mAppOpPermissionPackages.remove(perm); 6799 } 6800 } 6801 } 6802 } 6803 if (r != null) { 6804 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6805 } 6806 6807 N = pkg.instrumentation.size(); 6808 r = null; 6809 for (i=0; i<N; i++) { 6810 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6811 mInstrumentation.remove(a.getComponentName()); 6812 if (DEBUG_REMOVE && chatty) { 6813 if (r == null) { 6814 r = new StringBuilder(256); 6815 } else { 6816 r.append(' '); 6817 } 6818 r.append(a.info.name); 6819 } 6820 } 6821 if (r != null) { 6822 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6823 } 6824 6825 r = null; 6826 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6827 // Only system apps can hold shared libraries. 6828 if (pkg.libraryNames != null) { 6829 for (i=0; i<pkg.libraryNames.size(); i++) { 6830 String name = pkg.libraryNames.get(i); 6831 SharedLibraryEntry cur = mSharedLibraries.get(name); 6832 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6833 mSharedLibraries.remove(name); 6834 if (DEBUG_REMOVE && chatty) { 6835 if (r == null) { 6836 r = new StringBuilder(256); 6837 } else { 6838 r.append(' '); 6839 } 6840 r.append(name); 6841 } 6842 } 6843 } 6844 } 6845 } 6846 if (r != null) { 6847 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6848 } 6849 } 6850 6851 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6852 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6853 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6854 return true; 6855 } 6856 } 6857 return false; 6858 } 6859 6860 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6861 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6862 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6863 6864 private void updatePermissionsLPw(String changingPkg, 6865 PackageParser.Package pkgInfo, int flags) { 6866 // Make sure there are no dangling permission trees. 6867 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6868 while (it.hasNext()) { 6869 final BasePermission bp = it.next(); 6870 if (bp.packageSetting == null) { 6871 // We may not yet have parsed the package, so just see if 6872 // we still know about its settings. 6873 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6874 } 6875 if (bp.packageSetting == null) { 6876 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6877 + " from package " + bp.sourcePackage); 6878 it.remove(); 6879 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6880 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6881 Slog.i(TAG, "Removing old permission tree: " + bp.name 6882 + " from package " + bp.sourcePackage); 6883 flags |= UPDATE_PERMISSIONS_ALL; 6884 it.remove(); 6885 } 6886 } 6887 } 6888 6889 // Make sure all dynamic permissions have been assigned to a package, 6890 // and make sure there are no dangling permissions. 6891 it = mSettings.mPermissions.values().iterator(); 6892 while (it.hasNext()) { 6893 final BasePermission bp = it.next(); 6894 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6895 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6896 + bp.name + " pkg=" + bp.sourcePackage 6897 + " info=" + bp.pendingInfo); 6898 if (bp.packageSetting == null && bp.pendingInfo != null) { 6899 final BasePermission tree = findPermissionTreeLP(bp.name); 6900 if (tree != null && tree.perm != null) { 6901 bp.packageSetting = tree.packageSetting; 6902 bp.perm = new PackageParser.Permission(tree.perm.owner, 6903 new PermissionInfo(bp.pendingInfo)); 6904 bp.perm.info.packageName = tree.perm.info.packageName; 6905 bp.perm.info.name = bp.name; 6906 bp.uid = tree.uid; 6907 } 6908 } 6909 } 6910 if (bp.packageSetting == null) { 6911 // We may not yet have parsed the package, so just see if 6912 // we still know about its settings. 6913 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6914 } 6915 if (bp.packageSetting == null) { 6916 Slog.w(TAG, "Removing dangling permission: " + bp.name 6917 + " from package " + bp.sourcePackage); 6918 it.remove(); 6919 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6920 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6921 Slog.i(TAG, "Removing old permission: " + bp.name 6922 + " from package " + bp.sourcePackage); 6923 flags |= UPDATE_PERMISSIONS_ALL; 6924 it.remove(); 6925 } 6926 } 6927 } 6928 6929 // Now update the permissions for all packages, in particular 6930 // replace the granted permissions of the system packages. 6931 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6932 for (PackageParser.Package pkg : mPackages.values()) { 6933 if (pkg != pkgInfo) { 6934 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 6935 changingPkg); 6936 } 6937 } 6938 } 6939 6940 if (pkgInfo != null) { 6941 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 6942 } 6943 } 6944 6945 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 6946 String packageOfInterest) { 6947 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6948 if (ps == null) { 6949 return; 6950 } 6951 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6952 HashSet<String> origPermissions = gp.grantedPermissions; 6953 boolean changedPermission = false; 6954 6955 if (replace) { 6956 ps.permissionsFixed = false; 6957 if (gp == ps) { 6958 origPermissions = new HashSet<String>(gp.grantedPermissions); 6959 gp.grantedPermissions.clear(); 6960 gp.gids = mGlobalGids; 6961 } 6962 } 6963 6964 if (gp.gids == null) { 6965 gp.gids = mGlobalGids; 6966 } 6967 6968 final int N = pkg.requestedPermissions.size(); 6969 for (int i=0; i<N; i++) { 6970 final String name = pkg.requestedPermissions.get(i); 6971 final boolean required = pkg.requestedPermissionsRequired.get(i); 6972 final BasePermission bp = mSettings.mPermissions.get(name); 6973 if (DEBUG_INSTALL) { 6974 if (gp != ps) { 6975 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6976 } 6977 } 6978 6979 if (bp == null || bp.packageSetting == null) { 6980 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6981 Slog.w(TAG, "Unknown permission " + name 6982 + " in package " + pkg.packageName); 6983 } 6984 continue; 6985 } 6986 6987 final String perm = bp.name; 6988 boolean allowed; 6989 boolean allowedSig = false; 6990 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6991 // Keep track of app op permissions. 6992 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6993 if (pkgs == null) { 6994 pkgs = new ArraySet<>(); 6995 mAppOpPermissionPackages.put(bp.name, pkgs); 6996 } 6997 pkgs.add(pkg.packageName); 6998 } 6999 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7000 if (level == PermissionInfo.PROTECTION_NORMAL 7001 || level == PermissionInfo.PROTECTION_DANGEROUS) { 7002 // We grant a normal or dangerous permission if any of the following 7003 // are true: 7004 // 1) The permission is required 7005 // 2) The permission is optional, but was granted in the past 7006 // 3) The permission is optional, but was requested by an 7007 // app in /system (not /data) 7008 // 7009 // Otherwise, reject the permission. 7010 allowed = (required || origPermissions.contains(perm) 7011 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 7012 } else if (bp.packageSetting == null) { 7013 // This permission is invalid; skip it. 7014 allowed = false; 7015 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 7016 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 7017 if (allowed) { 7018 allowedSig = true; 7019 } 7020 } else { 7021 allowed = false; 7022 } 7023 if (DEBUG_INSTALL) { 7024 if (gp != ps) { 7025 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7026 } 7027 } 7028 if (allowed) { 7029 if (!isSystemApp(ps) && ps.permissionsFixed) { 7030 // If this is an existing, non-system package, then 7031 // we can't add any new permissions to it. 7032 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 7033 // Except... if this is a permission that was added 7034 // to the platform (note: need to only do this when 7035 // updating the platform). 7036 allowed = isNewPlatformPermissionForPackage(perm, pkg); 7037 } 7038 } 7039 if (allowed) { 7040 if (!gp.grantedPermissions.contains(perm)) { 7041 changedPermission = true; 7042 gp.grantedPermissions.add(perm); 7043 gp.gids = appendInts(gp.gids, bp.gids); 7044 } else if (!ps.haveGids) { 7045 gp.gids = appendInts(gp.gids, bp.gids); 7046 } 7047 } else { 7048 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7049 Slog.w(TAG, "Not granting permission " + perm 7050 + " to package " + pkg.packageName 7051 + " because it was previously installed without"); 7052 } 7053 } 7054 } else { 7055 if (gp.grantedPermissions.remove(perm)) { 7056 changedPermission = true; 7057 gp.gids = removeInts(gp.gids, bp.gids); 7058 Slog.i(TAG, "Un-granting permission " + perm 7059 + " from package " + pkg.packageName 7060 + " (protectionLevel=" + bp.protectionLevel 7061 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7062 + ")"); 7063 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7064 // Don't print warning for app op permissions, since it is fine for them 7065 // not to be granted, there is a UI for the user to decide. 7066 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7067 Slog.w(TAG, "Not granting permission " + perm 7068 + " to package " + pkg.packageName 7069 + " (protectionLevel=" + bp.protectionLevel 7070 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7071 + ")"); 7072 } 7073 } 7074 } 7075 } 7076 7077 if ((changedPermission || replace) && !ps.permissionsFixed && 7078 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7079 // This is the first that we have heard about this package, so the 7080 // permissions we have now selected are fixed until explicitly 7081 // changed. 7082 ps.permissionsFixed = true; 7083 } 7084 ps.haveGids = true; 7085 } 7086 7087 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7088 boolean allowed = false; 7089 final int NP = PackageParser.NEW_PERMISSIONS.length; 7090 for (int ip=0; ip<NP; ip++) { 7091 final PackageParser.NewPermissionInfo npi 7092 = PackageParser.NEW_PERMISSIONS[ip]; 7093 if (npi.name.equals(perm) 7094 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7095 allowed = true; 7096 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7097 + pkg.packageName); 7098 break; 7099 } 7100 } 7101 return allowed; 7102 } 7103 7104 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7105 BasePermission bp, HashSet<String> origPermissions) { 7106 boolean allowed; 7107 allowed = (compareSignatures( 7108 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7109 == PackageManager.SIGNATURE_MATCH) 7110 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7111 == PackageManager.SIGNATURE_MATCH); 7112 if (!allowed && (bp.protectionLevel 7113 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7114 if (isSystemApp(pkg)) { 7115 // For updated system applications, a system permission 7116 // is granted only if it had been defined by the original application. 7117 if (isUpdatedSystemApp(pkg)) { 7118 final PackageSetting sysPs = mSettings 7119 .getDisabledSystemPkgLPr(pkg.packageName); 7120 final GrantedPermissions origGp = sysPs.sharedUser != null 7121 ? sysPs.sharedUser : sysPs; 7122 7123 if (origGp.grantedPermissions.contains(perm)) { 7124 // If the original was granted this permission, we take 7125 // that grant decision as read and propagate it to the 7126 // update. 7127 if (sysPs.isPrivileged()) { 7128 allowed = true; 7129 } 7130 } else { 7131 // The system apk may have been updated with an older 7132 // version of the one on the data partition, but which 7133 // granted a new system permission that it didn't have 7134 // before. In this case we do want to allow the app to 7135 // now get the new permission if the ancestral apk is 7136 // privileged to get it. 7137 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7138 for (int j=0; 7139 j<sysPs.pkg.requestedPermissions.size(); j++) { 7140 if (perm.equals( 7141 sysPs.pkg.requestedPermissions.get(j))) { 7142 allowed = true; 7143 break; 7144 } 7145 } 7146 } 7147 } 7148 } else { 7149 allowed = isPrivilegedApp(pkg); 7150 } 7151 } 7152 } 7153 if (!allowed && (bp.protectionLevel 7154 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7155 // For development permissions, a development permission 7156 // is granted only if it was already granted. 7157 allowed = origPermissions.contains(perm); 7158 } 7159 return allowed; 7160 } 7161 7162 final class ActivityIntentResolver 7163 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7164 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7165 boolean defaultOnly, int userId) { 7166 if (!sUserManager.exists(userId)) return null; 7167 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7168 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7169 } 7170 7171 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7172 int userId) { 7173 if (!sUserManager.exists(userId)) return null; 7174 mFlags = flags; 7175 return super.queryIntent(intent, resolvedType, 7176 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7177 } 7178 7179 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7180 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7181 if (!sUserManager.exists(userId)) return null; 7182 if (packageActivities == null) { 7183 return null; 7184 } 7185 mFlags = flags; 7186 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7187 final int N = packageActivities.size(); 7188 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7189 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7190 7191 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7192 for (int i = 0; i < N; ++i) { 7193 intentFilters = packageActivities.get(i).intents; 7194 if (intentFilters != null && intentFilters.size() > 0) { 7195 PackageParser.ActivityIntentInfo[] array = 7196 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7197 intentFilters.toArray(array); 7198 listCut.add(array); 7199 } 7200 } 7201 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7202 } 7203 7204 public final void addActivity(PackageParser.Activity a, String type) { 7205 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7206 mActivities.put(a.getComponentName(), a); 7207 if (DEBUG_SHOW_INFO) 7208 Log.v( 7209 TAG, " " + type + " " + 7210 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7211 if (DEBUG_SHOW_INFO) 7212 Log.v(TAG, " Class=" + a.info.name); 7213 final int NI = a.intents.size(); 7214 for (int j=0; j<NI; j++) { 7215 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7216 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7217 intent.setPriority(0); 7218 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7219 + a.className + " with priority > 0, forcing to 0"); 7220 } 7221 if (DEBUG_SHOW_INFO) { 7222 Log.v(TAG, " IntentFilter:"); 7223 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7224 } 7225 if (!intent.debugCheck()) { 7226 Log.w(TAG, "==> For Activity " + a.info.name); 7227 } 7228 addFilter(intent); 7229 } 7230 } 7231 7232 public final void removeActivity(PackageParser.Activity a, String type) { 7233 mActivities.remove(a.getComponentName()); 7234 if (DEBUG_SHOW_INFO) { 7235 Log.v(TAG, " " + type + " " 7236 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7237 : a.info.name) + ":"); 7238 Log.v(TAG, " Class=" + a.info.name); 7239 } 7240 final int NI = a.intents.size(); 7241 for (int j=0; j<NI; j++) { 7242 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7243 if (DEBUG_SHOW_INFO) { 7244 Log.v(TAG, " IntentFilter:"); 7245 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7246 } 7247 removeFilter(intent); 7248 } 7249 } 7250 7251 @Override 7252 protected boolean allowFilterResult( 7253 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7254 ActivityInfo filterAi = filter.activity.info; 7255 for (int i=dest.size()-1; i>=0; i--) { 7256 ActivityInfo destAi = dest.get(i).activityInfo; 7257 if (destAi.name == filterAi.name 7258 && destAi.packageName == filterAi.packageName) { 7259 return false; 7260 } 7261 } 7262 return true; 7263 } 7264 7265 @Override 7266 protected ActivityIntentInfo[] newArray(int size) { 7267 return new ActivityIntentInfo[size]; 7268 } 7269 7270 @Override 7271 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7272 if (!sUserManager.exists(userId)) return true; 7273 PackageParser.Package p = filter.activity.owner; 7274 if (p != null) { 7275 PackageSetting ps = (PackageSetting)p.mExtras; 7276 if (ps != null) { 7277 // System apps are never considered stopped for purposes of 7278 // filtering, because there may be no way for the user to 7279 // actually re-launch them. 7280 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7281 && ps.getStopped(userId); 7282 } 7283 } 7284 return false; 7285 } 7286 7287 @Override 7288 protected boolean isPackageForFilter(String packageName, 7289 PackageParser.ActivityIntentInfo info) { 7290 return packageName.equals(info.activity.owner.packageName); 7291 } 7292 7293 @Override 7294 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7295 int match, int userId) { 7296 if (!sUserManager.exists(userId)) return null; 7297 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7298 return null; 7299 } 7300 final PackageParser.Activity activity = info.activity; 7301 if (mSafeMode && (activity.info.applicationInfo.flags 7302 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7303 return null; 7304 } 7305 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7306 if (ps == null) { 7307 return null; 7308 } 7309 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7310 ps.readUserState(userId), userId); 7311 if (ai == null) { 7312 return null; 7313 } 7314 final ResolveInfo res = new ResolveInfo(); 7315 res.activityInfo = ai; 7316 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7317 res.filter = info; 7318 } 7319 res.priority = info.getPriority(); 7320 res.preferredOrder = activity.owner.mPreferredOrder; 7321 //System.out.println("Result: " + res.activityInfo.className + 7322 // " = " + res.priority); 7323 res.match = match; 7324 res.isDefault = info.hasDefault; 7325 res.labelRes = info.labelRes; 7326 res.nonLocalizedLabel = info.nonLocalizedLabel; 7327 if (userNeedsBadging(userId)) { 7328 res.noResourceId = true; 7329 } else { 7330 res.icon = info.icon; 7331 } 7332 res.system = isSystemApp(res.activityInfo.applicationInfo); 7333 return res; 7334 } 7335 7336 @Override 7337 protected void sortResults(List<ResolveInfo> results) { 7338 Collections.sort(results, mResolvePrioritySorter); 7339 } 7340 7341 @Override 7342 protected void dumpFilter(PrintWriter out, String prefix, 7343 PackageParser.ActivityIntentInfo filter) { 7344 out.print(prefix); out.print( 7345 Integer.toHexString(System.identityHashCode(filter.activity))); 7346 out.print(' '); 7347 filter.activity.printComponentShortName(out); 7348 out.print(" filter "); 7349 out.println(Integer.toHexString(System.identityHashCode(filter))); 7350 } 7351 7352// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7353// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7354// final List<ResolveInfo> retList = Lists.newArrayList(); 7355// while (i.hasNext()) { 7356// final ResolveInfo resolveInfo = i.next(); 7357// if (isEnabledLP(resolveInfo.activityInfo)) { 7358// retList.add(resolveInfo); 7359// } 7360// } 7361// return retList; 7362// } 7363 7364 // Keys are String (activity class name), values are Activity. 7365 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7366 = new HashMap<ComponentName, PackageParser.Activity>(); 7367 private int mFlags; 7368 } 7369 7370 private final class ServiceIntentResolver 7371 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7372 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7373 boolean defaultOnly, int userId) { 7374 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7375 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7376 } 7377 7378 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7379 int userId) { 7380 if (!sUserManager.exists(userId)) return null; 7381 mFlags = flags; 7382 return super.queryIntent(intent, resolvedType, 7383 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7384 } 7385 7386 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7387 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7388 if (!sUserManager.exists(userId)) return null; 7389 if (packageServices == null) { 7390 return null; 7391 } 7392 mFlags = flags; 7393 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7394 final int N = packageServices.size(); 7395 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7396 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7397 7398 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7399 for (int i = 0; i < N; ++i) { 7400 intentFilters = packageServices.get(i).intents; 7401 if (intentFilters != null && intentFilters.size() > 0) { 7402 PackageParser.ServiceIntentInfo[] array = 7403 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7404 intentFilters.toArray(array); 7405 listCut.add(array); 7406 } 7407 } 7408 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7409 } 7410 7411 public final void addService(PackageParser.Service s) { 7412 mServices.put(s.getComponentName(), s); 7413 if (DEBUG_SHOW_INFO) { 7414 Log.v(TAG, " " 7415 + (s.info.nonLocalizedLabel != null 7416 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7417 Log.v(TAG, " Class=" + s.info.name); 7418 } 7419 final int NI = s.intents.size(); 7420 int j; 7421 for (j=0; j<NI; j++) { 7422 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7423 if (DEBUG_SHOW_INFO) { 7424 Log.v(TAG, " IntentFilter:"); 7425 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7426 } 7427 if (!intent.debugCheck()) { 7428 Log.w(TAG, "==> For Service " + s.info.name); 7429 } 7430 addFilter(intent); 7431 } 7432 } 7433 7434 public final void removeService(PackageParser.Service s) { 7435 mServices.remove(s.getComponentName()); 7436 if (DEBUG_SHOW_INFO) { 7437 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7438 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7439 Log.v(TAG, " Class=" + s.info.name); 7440 } 7441 final int NI = s.intents.size(); 7442 int j; 7443 for (j=0; j<NI; j++) { 7444 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7445 if (DEBUG_SHOW_INFO) { 7446 Log.v(TAG, " IntentFilter:"); 7447 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7448 } 7449 removeFilter(intent); 7450 } 7451 } 7452 7453 @Override 7454 protected boolean allowFilterResult( 7455 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7456 ServiceInfo filterSi = filter.service.info; 7457 for (int i=dest.size()-1; i>=0; i--) { 7458 ServiceInfo destAi = dest.get(i).serviceInfo; 7459 if (destAi.name == filterSi.name 7460 && destAi.packageName == filterSi.packageName) { 7461 return false; 7462 } 7463 } 7464 return true; 7465 } 7466 7467 @Override 7468 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7469 return new PackageParser.ServiceIntentInfo[size]; 7470 } 7471 7472 @Override 7473 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7474 if (!sUserManager.exists(userId)) return true; 7475 PackageParser.Package p = filter.service.owner; 7476 if (p != null) { 7477 PackageSetting ps = (PackageSetting)p.mExtras; 7478 if (ps != null) { 7479 // System apps are never considered stopped for purposes of 7480 // filtering, because there may be no way for the user to 7481 // actually re-launch them. 7482 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7483 && ps.getStopped(userId); 7484 } 7485 } 7486 return false; 7487 } 7488 7489 @Override 7490 protected boolean isPackageForFilter(String packageName, 7491 PackageParser.ServiceIntentInfo info) { 7492 return packageName.equals(info.service.owner.packageName); 7493 } 7494 7495 @Override 7496 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7497 int match, int userId) { 7498 if (!sUserManager.exists(userId)) return null; 7499 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7500 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7501 return null; 7502 } 7503 final PackageParser.Service service = info.service; 7504 if (mSafeMode && (service.info.applicationInfo.flags 7505 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7506 return null; 7507 } 7508 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7509 if (ps == null) { 7510 return null; 7511 } 7512 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7513 ps.readUserState(userId), userId); 7514 if (si == null) { 7515 return null; 7516 } 7517 final ResolveInfo res = new ResolveInfo(); 7518 res.serviceInfo = si; 7519 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7520 res.filter = filter; 7521 } 7522 res.priority = info.getPriority(); 7523 res.preferredOrder = service.owner.mPreferredOrder; 7524 //System.out.println("Result: " + res.activityInfo.className + 7525 // " = " + res.priority); 7526 res.match = match; 7527 res.isDefault = info.hasDefault; 7528 res.labelRes = info.labelRes; 7529 res.nonLocalizedLabel = info.nonLocalizedLabel; 7530 res.icon = info.icon; 7531 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7532 return res; 7533 } 7534 7535 @Override 7536 protected void sortResults(List<ResolveInfo> results) { 7537 Collections.sort(results, mResolvePrioritySorter); 7538 } 7539 7540 @Override 7541 protected void dumpFilter(PrintWriter out, String prefix, 7542 PackageParser.ServiceIntentInfo filter) { 7543 out.print(prefix); out.print( 7544 Integer.toHexString(System.identityHashCode(filter.service))); 7545 out.print(' '); 7546 filter.service.printComponentShortName(out); 7547 out.print(" filter "); 7548 out.println(Integer.toHexString(System.identityHashCode(filter))); 7549 } 7550 7551// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7552// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7553// final List<ResolveInfo> retList = Lists.newArrayList(); 7554// while (i.hasNext()) { 7555// final ResolveInfo resolveInfo = (ResolveInfo) i; 7556// if (isEnabledLP(resolveInfo.serviceInfo)) { 7557// retList.add(resolveInfo); 7558// } 7559// } 7560// return retList; 7561// } 7562 7563 // Keys are String (activity class name), values are Activity. 7564 private final HashMap<ComponentName, PackageParser.Service> mServices 7565 = new HashMap<ComponentName, PackageParser.Service>(); 7566 private int mFlags; 7567 }; 7568 7569 private final class ProviderIntentResolver 7570 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7571 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7572 boolean defaultOnly, int userId) { 7573 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7574 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7575 } 7576 7577 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7578 int userId) { 7579 if (!sUserManager.exists(userId)) 7580 return null; 7581 mFlags = flags; 7582 return super.queryIntent(intent, resolvedType, 7583 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7584 } 7585 7586 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7587 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7588 if (!sUserManager.exists(userId)) 7589 return null; 7590 if (packageProviders == null) { 7591 return null; 7592 } 7593 mFlags = flags; 7594 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7595 final int N = packageProviders.size(); 7596 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7597 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7598 7599 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7600 for (int i = 0; i < N; ++i) { 7601 intentFilters = packageProviders.get(i).intents; 7602 if (intentFilters != null && intentFilters.size() > 0) { 7603 PackageParser.ProviderIntentInfo[] array = 7604 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7605 intentFilters.toArray(array); 7606 listCut.add(array); 7607 } 7608 } 7609 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7610 } 7611 7612 public final void addProvider(PackageParser.Provider p) { 7613 if (mProviders.containsKey(p.getComponentName())) { 7614 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7615 return; 7616 } 7617 7618 mProviders.put(p.getComponentName(), p); 7619 if (DEBUG_SHOW_INFO) { 7620 Log.v(TAG, " " 7621 + (p.info.nonLocalizedLabel != null 7622 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7623 Log.v(TAG, " Class=" + p.info.name); 7624 } 7625 final int NI = p.intents.size(); 7626 int j; 7627 for (j = 0; j < NI; j++) { 7628 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7629 if (DEBUG_SHOW_INFO) { 7630 Log.v(TAG, " IntentFilter:"); 7631 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7632 } 7633 if (!intent.debugCheck()) { 7634 Log.w(TAG, "==> For Provider " + p.info.name); 7635 } 7636 addFilter(intent); 7637 } 7638 } 7639 7640 public final void removeProvider(PackageParser.Provider p) { 7641 mProviders.remove(p.getComponentName()); 7642 if (DEBUG_SHOW_INFO) { 7643 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7644 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7645 Log.v(TAG, " Class=" + p.info.name); 7646 } 7647 final int NI = p.intents.size(); 7648 int j; 7649 for (j = 0; j < NI; j++) { 7650 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7651 if (DEBUG_SHOW_INFO) { 7652 Log.v(TAG, " IntentFilter:"); 7653 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7654 } 7655 removeFilter(intent); 7656 } 7657 } 7658 7659 @Override 7660 protected boolean allowFilterResult( 7661 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7662 ProviderInfo filterPi = filter.provider.info; 7663 for (int i = dest.size() - 1; i >= 0; i--) { 7664 ProviderInfo destPi = dest.get(i).providerInfo; 7665 if (destPi.name == filterPi.name 7666 && destPi.packageName == filterPi.packageName) { 7667 return false; 7668 } 7669 } 7670 return true; 7671 } 7672 7673 @Override 7674 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7675 return new PackageParser.ProviderIntentInfo[size]; 7676 } 7677 7678 @Override 7679 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7680 if (!sUserManager.exists(userId)) 7681 return true; 7682 PackageParser.Package p = filter.provider.owner; 7683 if (p != null) { 7684 PackageSetting ps = (PackageSetting) p.mExtras; 7685 if (ps != null) { 7686 // System apps are never considered stopped for purposes of 7687 // filtering, because there may be no way for the user to 7688 // actually re-launch them. 7689 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7690 && ps.getStopped(userId); 7691 } 7692 } 7693 return false; 7694 } 7695 7696 @Override 7697 protected boolean isPackageForFilter(String packageName, 7698 PackageParser.ProviderIntentInfo info) { 7699 return packageName.equals(info.provider.owner.packageName); 7700 } 7701 7702 @Override 7703 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7704 int match, int userId) { 7705 if (!sUserManager.exists(userId)) 7706 return null; 7707 final PackageParser.ProviderIntentInfo info = filter; 7708 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7709 return null; 7710 } 7711 final PackageParser.Provider provider = info.provider; 7712 if (mSafeMode && (provider.info.applicationInfo.flags 7713 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7714 return null; 7715 } 7716 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7717 if (ps == null) { 7718 return null; 7719 } 7720 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7721 ps.readUserState(userId), userId); 7722 if (pi == null) { 7723 return null; 7724 } 7725 final ResolveInfo res = new ResolveInfo(); 7726 res.providerInfo = pi; 7727 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7728 res.filter = filter; 7729 } 7730 res.priority = info.getPriority(); 7731 res.preferredOrder = provider.owner.mPreferredOrder; 7732 res.match = match; 7733 res.isDefault = info.hasDefault; 7734 res.labelRes = info.labelRes; 7735 res.nonLocalizedLabel = info.nonLocalizedLabel; 7736 res.icon = info.icon; 7737 res.system = isSystemApp(res.providerInfo.applicationInfo); 7738 return res; 7739 } 7740 7741 @Override 7742 protected void sortResults(List<ResolveInfo> results) { 7743 Collections.sort(results, mResolvePrioritySorter); 7744 } 7745 7746 @Override 7747 protected void dumpFilter(PrintWriter out, String prefix, 7748 PackageParser.ProviderIntentInfo filter) { 7749 out.print(prefix); 7750 out.print( 7751 Integer.toHexString(System.identityHashCode(filter.provider))); 7752 out.print(' '); 7753 filter.provider.printComponentShortName(out); 7754 out.print(" filter "); 7755 out.println(Integer.toHexString(System.identityHashCode(filter))); 7756 } 7757 7758 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7759 = new HashMap<ComponentName, PackageParser.Provider>(); 7760 private int mFlags; 7761 }; 7762 7763 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7764 new Comparator<ResolveInfo>() { 7765 public int compare(ResolveInfo r1, ResolveInfo r2) { 7766 int v1 = r1.priority; 7767 int v2 = r2.priority; 7768 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7769 if (v1 != v2) { 7770 return (v1 > v2) ? -1 : 1; 7771 } 7772 v1 = r1.preferredOrder; 7773 v2 = r2.preferredOrder; 7774 if (v1 != v2) { 7775 return (v1 > v2) ? -1 : 1; 7776 } 7777 if (r1.isDefault != r2.isDefault) { 7778 return r1.isDefault ? -1 : 1; 7779 } 7780 v1 = r1.match; 7781 v2 = r2.match; 7782 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7783 if (v1 != v2) { 7784 return (v1 > v2) ? -1 : 1; 7785 } 7786 if (r1.system != r2.system) { 7787 return r1.system ? -1 : 1; 7788 } 7789 return 0; 7790 } 7791 }; 7792 7793 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7794 new Comparator<ProviderInfo>() { 7795 public int compare(ProviderInfo p1, ProviderInfo p2) { 7796 final int v1 = p1.initOrder; 7797 final int v2 = p2.initOrder; 7798 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7799 } 7800 }; 7801 7802 static final void sendPackageBroadcast(String action, String pkg, 7803 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7804 int[] userIds) { 7805 IActivityManager am = ActivityManagerNative.getDefault(); 7806 if (am != null) { 7807 try { 7808 if (userIds == null) { 7809 userIds = am.getRunningUserIds(); 7810 } 7811 for (int id : userIds) { 7812 final Intent intent = new Intent(action, 7813 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7814 if (extras != null) { 7815 intent.putExtras(extras); 7816 } 7817 if (targetPkg != null) { 7818 intent.setPackage(targetPkg); 7819 } 7820 // Modify the UID when posting to other users 7821 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7822 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7823 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7824 intent.putExtra(Intent.EXTRA_UID, uid); 7825 } 7826 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7827 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7828 if (DEBUG_BROADCASTS) { 7829 RuntimeException here = new RuntimeException("here"); 7830 here.fillInStackTrace(); 7831 Slog.d(TAG, "Sending to user " + id + ": " 7832 + intent.toShortString(false, true, false, false) 7833 + " " + intent.getExtras(), here); 7834 } 7835 am.broadcastIntent(null, intent, null, finishedReceiver, 7836 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7837 finishedReceiver != null, false, id); 7838 } 7839 } catch (RemoteException ex) { 7840 } 7841 } 7842 } 7843 7844 /** 7845 * Check if the external storage media is available. This is true if there 7846 * is a mounted external storage medium or if the external storage is 7847 * emulated. 7848 */ 7849 private boolean isExternalMediaAvailable() { 7850 return mMediaMounted || Environment.isExternalStorageEmulated(); 7851 } 7852 7853 @Override 7854 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7855 // writer 7856 synchronized (mPackages) { 7857 if (!isExternalMediaAvailable()) { 7858 // If the external storage is no longer mounted at this point, 7859 // the caller may not have been able to delete all of this 7860 // packages files and can not delete any more. Bail. 7861 return null; 7862 } 7863 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7864 if (lastPackage != null) { 7865 pkgs.remove(lastPackage); 7866 } 7867 if (pkgs.size() > 0) { 7868 return pkgs.get(0); 7869 } 7870 } 7871 return null; 7872 } 7873 7874 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7875 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 7876 userId, andCode ? 1 : 0, packageName); 7877 if (mSystemReady) { 7878 msg.sendToTarget(); 7879 } else { 7880 if (mPostSystemReadyMessages == null) { 7881 mPostSystemReadyMessages = new ArrayList<>(); 7882 } 7883 mPostSystemReadyMessages.add(msg); 7884 } 7885 } 7886 7887 void startCleaningPackages() { 7888 // reader 7889 synchronized (mPackages) { 7890 if (!isExternalMediaAvailable()) { 7891 return; 7892 } 7893 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7894 return; 7895 } 7896 } 7897 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7898 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7899 IActivityManager am = ActivityManagerNative.getDefault(); 7900 if (am != null) { 7901 try { 7902 am.startService(null, intent, null, UserHandle.USER_OWNER); 7903 } catch (RemoteException e) { 7904 } 7905 } 7906 } 7907 7908 @Override 7909 public void installPackage(String originPath, IPackageInstallObserver2 observer, 7910 int installFlags, String installerPackageName, VerificationParams verificationParams, 7911 String packageAbiOverride) { 7912 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 7913 packageAbiOverride, UserHandle.getCallingUserId()); 7914 } 7915 7916 @Override 7917 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 7918 int installFlags, String installerPackageName, VerificationParams verificationParams, 7919 String packageAbiOverride, int userId) { 7920 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 7921 7922 final int callingUid = Binder.getCallingUid(); 7923 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 7924 7925 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7926 try { 7927 if (observer != null) { 7928 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7929 } 7930 } catch (RemoteException re) { 7931 } 7932 return; 7933 } 7934 7935 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 7936 installFlags |= PackageManager.INSTALL_FROM_ADB; 7937 7938 } else { 7939 // Caller holds INSTALL_PACKAGES permission, so we're less strict 7940 // about installerPackageName. 7941 7942 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 7943 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 7944 } 7945 7946 UserHandle user; 7947 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 7948 user = UserHandle.ALL; 7949 } else { 7950 user = new UserHandle(userId); 7951 } 7952 7953 verificationParams.setInstallerUid(callingUid); 7954 7955 final File originFile = new File(originPath); 7956 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 7957 7958 final Message msg = mHandler.obtainMessage(INIT_COPY); 7959 msg.obj = new InstallParams(origin, observer, installFlags, 7960 installerPackageName, verificationParams, user, packageAbiOverride); 7961 mHandler.sendMessage(msg); 7962 } 7963 7964 void installStage(String packageName, File stagedDir, String stagedCid, 7965 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 7966 String installerPackageName, int installerUid, UserHandle user) { 7967 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7968 params.referrerUri, installerUid, null); 7969 7970 final OriginInfo origin; 7971 if (stagedDir != null) { 7972 origin = OriginInfo.fromStagedFile(stagedDir); 7973 } else { 7974 origin = OriginInfo.fromStagedContainer(stagedCid); 7975 } 7976 7977 final Message msg = mHandler.obtainMessage(INIT_COPY); 7978 msg.obj = new InstallParams(origin, observer, params.installFlags, 7979 installerPackageName, verifParams, user, params.abiOverride); 7980 mHandler.sendMessage(msg); 7981 } 7982 7983 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7984 Bundle extras = new Bundle(1); 7985 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7986 7987 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7988 packageName, extras, null, null, new int[] {userId}); 7989 try { 7990 IActivityManager am = ActivityManagerNative.getDefault(); 7991 final boolean isSystem = 7992 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7993 if (isSystem && am.isUserRunning(userId, false)) { 7994 // The just-installed/enabled app is bundled on the system, so presumed 7995 // to be able to run automatically without needing an explicit launch. 7996 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7997 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7998 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7999 .setPackage(packageName); 8000 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8001 android.app.AppOpsManager.OP_NONE, false, false, userId); 8002 } 8003 } catch (RemoteException e) { 8004 // shouldn't happen 8005 Slog.w(TAG, "Unable to bootstrap installed package", e); 8006 } 8007 } 8008 8009 @Override 8010 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8011 int userId) { 8012 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8013 PackageSetting pkgSetting; 8014 final int uid = Binder.getCallingUid(); 8015 enforceCrossUserPermission(uid, userId, true, true, 8016 "setApplicationHiddenSetting for user " + userId); 8017 8018 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8019 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8020 return false; 8021 } 8022 8023 long callingId = Binder.clearCallingIdentity(); 8024 try { 8025 boolean sendAdded = false; 8026 boolean sendRemoved = false; 8027 // writer 8028 synchronized (mPackages) { 8029 pkgSetting = mSettings.mPackages.get(packageName); 8030 if (pkgSetting == null) { 8031 return false; 8032 } 8033 if (pkgSetting.getHidden(userId) != hidden) { 8034 pkgSetting.setHidden(hidden, userId); 8035 mSettings.writePackageRestrictionsLPr(userId); 8036 if (hidden) { 8037 sendRemoved = true; 8038 } else { 8039 sendAdded = true; 8040 } 8041 } 8042 } 8043 if (sendAdded) { 8044 sendPackageAddedForUser(packageName, pkgSetting, userId); 8045 return true; 8046 } 8047 if (sendRemoved) { 8048 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8049 "hiding pkg"); 8050 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8051 } 8052 } finally { 8053 Binder.restoreCallingIdentity(callingId); 8054 } 8055 return false; 8056 } 8057 8058 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8059 int userId) { 8060 final PackageRemovedInfo info = new PackageRemovedInfo(); 8061 info.removedPackage = packageName; 8062 info.removedUsers = new int[] {userId}; 8063 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8064 info.sendBroadcast(false, false, false); 8065 } 8066 8067 /** 8068 * Returns true if application is not found or there was an error. Otherwise it returns 8069 * the hidden state of the package for the given user. 8070 */ 8071 @Override 8072 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8073 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8074 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8075 false, "getApplicationHidden for user " + userId); 8076 PackageSetting pkgSetting; 8077 long callingId = Binder.clearCallingIdentity(); 8078 try { 8079 // writer 8080 synchronized (mPackages) { 8081 pkgSetting = mSettings.mPackages.get(packageName); 8082 if (pkgSetting == null) { 8083 return true; 8084 } 8085 return pkgSetting.getHidden(userId); 8086 } 8087 } finally { 8088 Binder.restoreCallingIdentity(callingId); 8089 } 8090 } 8091 8092 /** 8093 * @hide 8094 */ 8095 @Override 8096 public int installExistingPackageAsUser(String packageName, int userId) { 8097 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8098 null); 8099 PackageSetting pkgSetting; 8100 final int uid = Binder.getCallingUid(); 8101 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8102 + userId); 8103 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8104 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8105 } 8106 8107 long callingId = Binder.clearCallingIdentity(); 8108 try { 8109 boolean sendAdded = false; 8110 Bundle extras = new Bundle(1); 8111 8112 // writer 8113 synchronized (mPackages) { 8114 pkgSetting = mSettings.mPackages.get(packageName); 8115 if (pkgSetting == null) { 8116 return PackageManager.INSTALL_FAILED_INVALID_URI; 8117 } 8118 if (!pkgSetting.getInstalled(userId)) { 8119 pkgSetting.setInstalled(true, userId); 8120 pkgSetting.setHidden(false, userId); 8121 mSettings.writePackageRestrictionsLPr(userId); 8122 sendAdded = true; 8123 } 8124 } 8125 8126 if (sendAdded) { 8127 sendPackageAddedForUser(packageName, pkgSetting, userId); 8128 } 8129 } finally { 8130 Binder.restoreCallingIdentity(callingId); 8131 } 8132 8133 return PackageManager.INSTALL_SUCCEEDED; 8134 } 8135 8136 boolean isUserRestricted(int userId, String restrictionKey) { 8137 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8138 if (restrictions.getBoolean(restrictionKey, false)) { 8139 Log.w(TAG, "User is restricted: " + restrictionKey); 8140 return true; 8141 } 8142 return false; 8143 } 8144 8145 @Override 8146 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8147 mContext.enforceCallingOrSelfPermission( 8148 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8149 "Only package verification agents can verify applications"); 8150 8151 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8152 final PackageVerificationResponse response = new PackageVerificationResponse( 8153 verificationCode, Binder.getCallingUid()); 8154 msg.arg1 = id; 8155 msg.obj = response; 8156 mHandler.sendMessage(msg); 8157 } 8158 8159 @Override 8160 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8161 long millisecondsToDelay) { 8162 mContext.enforceCallingOrSelfPermission( 8163 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8164 "Only package verification agents can extend verification timeouts"); 8165 8166 final PackageVerificationState state = mPendingVerification.get(id); 8167 final PackageVerificationResponse response = new PackageVerificationResponse( 8168 verificationCodeAtTimeout, Binder.getCallingUid()); 8169 8170 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8171 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8172 } 8173 if (millisecondsToDelay < 0) { 8174 millisecondsToDelay = 0; 8175 } 8176 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8177 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8178 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8179 } 8180 8181 if ((state != null) && !state.timeoutExtended()) { 8182 state.extendTimeout(); 8183 8184 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8185 msg.arg1 = id; 8186 msg.obj = response; 8187 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8188 } 8189 } 8190 8191 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8192 int verificationCode, UserHandle user) { 8193 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8194 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8195 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8196 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8197 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8198 8199 mContext.sendBroadcastAsUser(intent, user, 8200 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8201 } 8202 8203 private ComponentName matchComponentForVerifier(String packageName, 8204 List<ResolveInfo> receivers) { 8205 ActivityInfo targetReceiver = null; 8206 8207 final int NR = receivers.size(); 8208 for (int i = 0; i < NR; i++) { 8209 final ResolveInfo info = receivers.get(i); 8210 if (info.activityInfo == null) { 8211 continue; 8212 } 8213 8214 if (packageName.equals(info.activityInfo.packageName)) { 8215 targetReceiver = info.activityInfo; 8216 break; 8217 } 8218 } 8219 8220 if (targetReceiver == null) { 8221 return null; 8222 } 8223 8224 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8225 } 8226 8227 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8228 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8229 if (pkgInfo.verifiers.length == 0) { 8230 return null; 8231 } 8232 8233 final int N = pkgInfo.verifiers.length; 8234 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8235 for (int i = 0; i < N; i++) { 8236 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8237 8238 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8239 receivers); 8240 if (comp == null) { 8241 continue; 8242 } 8243 8244 final int verifierUid = getUidForVerifier(verifierInfo); 8245 if (verifierUid == -1) { 8246 continue; 8247 } 8248 8249 if (DEBUG_VERIFY) { 8250 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8251 + " with the correct signature"); 8252 } 8253 sufficientVerifiers.add(comp); 8254 verificationState.addSufficientVerifier(verifierUid); 8255 } 8256 8257 return sufficientVerifiers; 8258 } 8259 8260 private int getUidForVerifier(VerifierInfo verifierInfo) { 8261 synchronized (mPackages) { 8262 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8263 if (pkg == null) { 8264 return -1; 8265 } else if (pkg.mSignatures.length != 1) { 8266 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8267 + " has more than one signature; ignoring"); 8268 return -1; 8269 } 8270 8271 /* 8272 * If the public key of the package's signature does not match 8273 * our expected public key, then this is a different package and 8274 * we should skip. 8275 */ 8276 8277 final byte[] expectedPublicKey; 8278 try { 8279 final Signature verifierSig = pkg.mSignatures[0]; 8280 final PublicKey publicKey = verifierSig.getPublicKey(); 8281 expectedPublicKey = publicKey.getEncoded(); 8282 } catch (CertificateException e) { 8283 return -1; 8284 } 8285 8286 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8287 8288 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8289 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8290 + " does not have the expected public key; ignoring"); 8291 return -1; 8292 } 8293 8294 return pkg.applicationInfo.uid; 8295 } 8296 } 8297 8298 @Override 8299 public void finishPackageInstall(int token) { 8300 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8301 8302 if (DEBUG_INSTALL) { 8303 Slog.v(TAG, "BM finishing package install for " + token); 8304 } 8305 8306 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8307 mHandler.sendMessage(msg); 8308 } 8309 8310 /** 8311 * Get the verification agent timeout. 8312 * 8313 * @return verification timeout in milliseconds 8314 */ 8315 private long getVerificationTimeout() { 8316 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8317 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8318 DEFAULT_VERIFICATION_TIMEOUT); 8319 } 8320 8321 /** 8322 * Get the default verification agent response code. 8323 * 8324 * @return default verification response code 8325 */ 8326 private int getDefaultVerificationResponse() { 8327 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8328 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8329 DEFAULT_VERIFICATION_RESPONSE); 8330 } 8331 8332 /** 8333 * Check whether or not package verification has been enabled. 8334 * 8335 * @return true if verification should be performed 8336 */ 8337 private boolean isVerificationEnabled(int userId, int installFlags) { 8338 if (!DEFAULT_VERIFY_ENABLE) { 8339 return false; 8340 } 8341 8342 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8343 8344 // Check if installing from ADB 8345 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8346 // Do not run verification in a test harness environment 8347 if (ActivityManager.isRunningInTestHarness()) { 8348 return false; 8349 } 8350 if (ensureVerifyAppsEnabled) { 8351 return true; 8352 } 8353 // Check if the developer does not want package verification for ADB installs 8354 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8355 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8356 return false; 8357 } 8358 } 8359 8360 if (ensureVerifyAppsEnabled) { 8361 return true; 8362 } 8363 8364 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8365 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8366 } 8367 8368 /** 8369 * Get the "allow unknown sources" setting. 8370 * 8371 * @return the current "allow unknown sources" setting 8372 */ 8373 private int getUnknownSourcesSettings() { 8374 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8375 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8376 -1); 8377 } 8378 8379 @Override 8380 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8381 final int uid = Binder.getCallingUid(); 8382 // writer 8383 synchronized (mPackages) { 8384 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8385 if (targetPackageSetting == null) { 8386 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8387 } 8388 8389 PackageSetting installerPackageSetting; 8390 if (installerPackageName != null) { 8391 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8392 if (installerPackageSetting == null) { 8393 throw new IllegalArgumentException("Unknown installer package: " 8394 + installerPackageName); 8395 } 8396 } else { 8397 installerPackageSetting = null; 8398 } 8399 8400 Signature[] callerSignature; 8401 Object obj = mSettings.getUserIdLPr(uid); 8402 if (obj != null) { 8403 if (obj instanceof SharedUserSetting) { 8404 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8405 } else if (obj instanceof PackageSetting) { 8406 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8407 } else { 8408 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8409 } 8410 } else { 8411 throw new SecurityException("Unknown calling uid " + uid); 8412 } 8413 8414 // Verify: can't set installerPackageName to a package that is 8415 // not signed with the same cert as the caller. 8416 if (installerPackageSetting != null) { 8417 if (compareSignatures(callerSignature, 8418 installerPackageSetting.signatures.mSignatures) 8419 != PackageManager.SIGNATURE_MATCH) { 8420 throw new SecurityException( 8421 "Caller does not have same cert as new installer package " 8422 + installerPackageName); 8423 } 8424 } 8425 8426 // Verify: if target already has an installer package, it must 8427 // be signed with the same cert as the caller. 8428 if (targetPackageSetting.installerPackageName != null) { 8429 PackageSetting setting = mSettings.mPackages.get( 8430 targetPackageSetting.installerPackageName); 8431 // If the currently set package isn't valid, then it's always 8432 // okay to change it. 8433 if (setting != null) { 8434 if (compareSignatures(callerSignature, 8435 setting.signatures.mSignatures) 8436 != PackageManager.SIGNATURE_MATCH) { 8437 throw new SecurityException( 8438 "Caller does not have same cert as old installer package " 8439 + targetPackageSetting.installerPackageName); 8440 } 8441 } 8442 } 8443 8444 // Okay! 8445 targetPackageSetting.installerPackageName = installerPackageName; 8446 scheduleWriteSettingsLocked(); 8447 } 8448 } 8449 8450 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8451 // Queue up an async operation since the package installation may take a little while. 8452 mHandler.post(new Runnable() { 8453 public void run() { 8454 mHandler.removeCallbacks(this); 8455 // Result object to be returned 8456 PackageInstalledInfo res = new PackageInstalledInfo(); 8457 res.returnCode = currentStatus; 8458 res.uid = -1; 8459 res.pkg = null; 8460 res.removedInfo = new PackageRemovedInfo(); 8461 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8462 args.doPreInstall(res.returnCode); 8463 synchronized (mInstallLock) { 8464 installPackageLI(args, res); 8465 } 8466 args.doPostInstall(res.returnCode, res.uid); 8467 } 8468 8469 // A restore should be performed at this point if (a) the install 8470 // succeeded, (b) the operation is not an update, and (c) the new 8471 // package has not opted out of backup participation. 8472 final boolean update = res.removedInfo.removedPackage != null; 8473 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8474 boolean doRestore = !update 8475 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8476 8477 // Set up the post-install work request bookkeeping. This will be used 8478 // and cleaned up by the post-install event handling regardless of whether 8479 // there's a restore pass performed. Token values are >= 1. 8480 int token; 8481 if (mNextInstallToken < 0) mNextInstallToken = 1; 8482 token = mNextInstallToken++; 8483 8484 PostInstallData data = new PostInstallData(args, res); 8485 mRunningInstalls.put(token, data); 8486 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8487 8488 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8489 // Pass responsibility to the Backup Manager. It will perform a 8490 // restore if appropriate, then pass responsibility back to the 8491 // Package Manager to run the post-install observer callbacks 8492 // and broadcasts. 8493 IBackupManager bm = IBackupManager.Stub.asInterface( 8494 ServiceManager.getService(Context.BACKUP_SERVICE)); 8495 if (bm != null) { 8496 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8497 + " to BM for possible restore"); 8498 try { 8499 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8500 } catch (RemoteException e) { 8501 // can't happen; the backup manager is local 8502 } catch (Exception e) { 8503 Slog.e(TAG, "Exception trying to enqueue restore", e); 8504 doRestore = false; 8505 } 8506 } else { 8507 Slog.e(TAG, "Backup Manager not found!"); 8508 doRestore = false; 8509 } 8510 } 8511 8512 if (!doRestore) { 8513 // No restore possible, or the Backup Manager was mysteriously not 8514 // available -- just fire the post-install work request directly. 8515 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8516 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8517 mHandler.sendMessage(msg); 8518 } 8519 } 8520 }); 8521 } 8522 8523 private abstract class HandlerParams { 8524 private static final int MAX_RETRIES = 4; 8525 8526 /** 8527 * Number of times startCopy() has been attempted and had a non-fatal 8528 * error. 8529 */ 8530 private int mRetries = 0; 8531 8532 /** User handle for the user requesting the information or installation. */ 8533 private final UserHandle mUser; 8534 8535 HandlerParams(UserHandle user) { 8536 mUser = user; 8537 } 8538 8539 UserHandle getUser() { 8540 return mUser; 8541 } 8542 8543 final boolean startCopy() { 8544 boolean res; 8545 try { 8546 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8547 8548 if (++mRetries > MAX_RETRIES) { 8549 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8550 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8551 handleServiceError(); 8552 return false; 8553 } else { 8554 handleStartCopy(); 8555 res = true; 8556 } 8557 } catch (RemoteException e) { 8558 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8559 mHandler.sendEmptyMessage(MCS_RECONNECT); 8560 res = false; 8561 } 8562 handleReturnCode(); 8563 return res; 8564 } 8565 8566 final void serviceError() { 8567 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8568 handleServiceError(); 8569 handleReturnCode(); 8570 } 8571 8572 abstract void handleStartCopy() throws RemoteException; 8573 abstract void handleServiceError(); 8574 abstract void handleReturnCode(); 8575 } 8576 8577 class MeasureParams extends HandlerParams { 8578 private final PackageStats mStats; 8579 private boolean mSuccess; 8580 8581 private final IPackageStatsObserver mObserver; 8582 8583 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8584 super(new UserHandle(stats.userHandle)); 8585 mObserver = observer; 8586 mStats = stats; 8587 } 8588 8589 @Override 8590 public String toString() { 8591 return "MeasureParams{" 8592 + Integer.toHexString(System.identityHashCode(this)) 8593 + " " + mStats.packageName + "}"; 8594 } 8595 8596 @Override 8597 void handleStartCopy() throws RemoteException { 8598 synchronized (mInstallLock) { 8599 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8600 } 8601 8602 if (mSuccess) { 8603 final boolean mounted; 8604 if (Environment.isExternalStorageEmulated()) { 8605 mounted = true; 8606 } else { 8607 final String status = Environment.getExternalStorageState(); 8608 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8609 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8610 } 8611 8612 if (mounted) { 8613 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8614 8615 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8616 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8617 8618 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8619 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8620 8621 // Always subtract cache size, since it's a subdirectory 8622 mStats.externalDataSize -= mStats.externalCacheSize; 8623 8624 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8625 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8626 8627 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8628 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8629 } 8630 } 8631 } 8632 8633 @Override 8634 void handleReturnCode() { 8635 if (mObserver != null) { 8636 try { 8637 mObserver.onGetStatsCompleted(mStats, mSuccess); 8638 } catch (RemoteException e) { 8639 Slog.i(TAG, "Observer no longer exists."); 8640 } 8641 } 8642 } 8643 8644 @Override 8645 void handleServiceError() { 8646 Slog.e(TAG, "Could not measure application " + mStats.packageName 8647 + " external storage"); 8648 } 8649 } 8650 8651 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8652 throws RemoteException { 8653 long result = 0; 8654 for (File path : paths) { 8655 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8656 } 8657 return result; 8658 } 8659 8660 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8661 for (File path : paths) { 8662 try { 8663 mcs.clearDirectory(path.getAbsolutePath()); 8664 } catch (RemoteException e) { 8665 } 8666 } 8667 } 8668 8669 static class OriginInfo { 8670 /** 8671 * Location where install is coming from, before it has been 8672 * copied/renamed into place. This could be a single monolithic APK 8673 * file, or a cluster directory. This location may be untrusted. 8674 */ 8675 final File file; 8676 final String cid; 8677 8678 /** 8679 * Flag indicating that {@link #file} or {@link #cid} has already been 8680 * staged, meaning downstream users don't need to defensively copy the 8681 * contents. 8682 */ 8683 final boolean staged; 8684 8685 /** 8686 * Flag indicating that {@link #file} or {@link #cid} is an already 8687 * installed app that is being moved. 8688 */ 8689 final boolean existing; 8690 8691 final String resolvedPath; 8692 final File resolvedFile; 8693 8694 static OriginInfo fromNothing() { 8695 return new OriginInfo(null, null, false, false); 8696 } 8697 8698 static OriginInfo fromUntrustedFile(File file) { 8699 return new OriginInfo(file, null, false, false); 8700 } 8701 8702 static OriginInfo fromExistingFile(File file) { 8703 return new OriginInfo(file, null, false, true); 8704 } 8705 8706 static OriginInfo fromStagedFile(File file) { 8707 return new OriginInfo(file, null, true, false); 8708 } 8709 8710 static OriginInfo fromStagedContainer(String cid) { 8711 return new OriginInfo(null, cid, true, false); 8712 } 8713 8714 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8715 this.file = file; 8716 this.cid = cid; 8717 this.staged = staged; 8718 this.existing = existing; 8719 8720 if (cid != null) { 8721 resolvedPath = PackageHelper.getSdDir(cid); 8722 resolvedFile = new File(resolvedPath); 8723 } else if (file != null) { 8724 resolvedPath = file.getAbsolutePath(); 8725 resolvedFile = file; 8726 } else { 8727 resolvedPath = null; 8728 resolvedFile = null; 8729 } 8730 } 8731 } 8732 8733 class InstallParams extends HandlerParams { 8734 final OriginInfo origin; 8735 final IPackageInstallObserver2 observer; 8736 int installFlags; 8737 final String installerPackageName; 8738 final VerificationParams verificationParams; 8739 private InstallArgs mArgs; 8740 private int mRet; 8741 final String packageAbiOverride; 8742 8743 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8744 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8745 String packageAbiOverride) { 8746 super(user); 8747 this.origin = origin; 8748 this.observer = observer; 8749 this.installFlags = installFlags; 8750 this.installerPackageName = installerPackageName; 8751 this.verificationParams = verificationParams; 8752 this.packageAbiOverride = packageAbiOverride; 8753 } 8754 8755 @Override 8756 public String toString() { 8757 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8758 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8759 } 8760 8761 public ManifestDigest getManifestDigest() { 8762 if (verificationParams == null) { 8763 return null; 8764 } 8765 return verificationParams.getManifestDigest(); 8766 } 8767 8768 private int installLocationPolicy(PackageInfoLite pkgLite) { 8769 String packageName = pkgLite.packageName; 8770 int installLocation = pkgLite.installLocation; 8771 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8772 // reader 8773 synchronized (mPackages) { 8774 PackageParser.Package pkg = mPackages.get(packageName); 8775 if (pkg != null) { 8776 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8777 // Check for downgrading. 8778 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8779 if (pkgLite.versionCode < pkg.mVersionCode) { 8780 Slog.w(TAG, "Can't install update of " + packageName 8781 + " update version " + pkgLite.versionCode 8782 + " is older than installed version " 8783 + pkg.mVersionCode); 8784 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8785 } 8786 } 8787 // Check for updated system application. 8788 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8789 if (onSd) { 8790 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8791 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8792 } 8793 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8794 } else { 8795 if (onSd) { 8796 // Install flag overrides everything. 8797 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8798 } 8799 // If current upgrade specifies particular preference 8800 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8801 // Application explicitly specified internal. 8802 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8803 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8804 // App explictly prefers external. Let policy decide 8805 } else { 8806 // Prefer previous location 8807 if (isExternal(pkg)) { 8808 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8809 } 8810 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8811 } 8812 } 8813 } else { 8814 // Invalid install. Return error code 8815 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8816 } 8817 } 8818 } 8819 // All the special cases have been taken care of. 8820 // Return result based on recommended install location. 8821 if (onSd) { 8822 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8823 } 8824 return pkgLite.recommendedInstallLocation; 8825 } 8826 8827 /* 8828 * Invoke remote method to get package information and install 8829 * location values. Override install location based on default 8830 * policy if needed and then create install arguments based 8831 * on the install location. 8832 */ 8833 public void handleStartCopy() throws RemoteException { 8834 int ret = PackageManager.INSTALL_SUCCEEDED; 8835 8836 // If we're already staged, we've firmly committed to an install location 8837 if (origin.staged) { 8838 if (origin.file != null) { 8839 installFlags |= PackageManager.INSTALL_INTERNAL; 8840 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8841 } else if (origin.cid != null) { 8842 installFlags |= PackageManager.INSTALL_EXTERNAL; 8843 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8844 } else { 8845 throw new IllegalStateException("Invalid stage location"); 8846 } 8847 } 8848 8849 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8850 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8851 8852 PackageInfoLite pkgLite = null; 8853 8854 if (onInt && onSd) { 8855 // Check if both bits are set. 8856 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8857 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8858 } else { 8859 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8860 packageAbiOverride); 8861 8862 /* 8863 * If we have too little free space, try to free cache 8864 * before giving up. 8865 */ 8866 if (!origin.staged && pkgLite.recommendedInstallLocation 8867 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8868 // TODO: focus freeing disk space on the target device 8869 final StorageManager storage = StorageManager.from(mContext); 8870 final long lowThreshold = storage.getStorageLowBytes( 8871 Environment.getDataDirectory()); 8872 8873 final long sizeBytes = mContainerService.calculateInstalledSize( 8874 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8875 8876 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8877 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8878 installFlags, packageAbiOverride); 8879 } 8880 8881 /* 8882 * The cache free must have deleted the file we 8883 * downloaded to install. 8884 * 8885 * TODO: fix the "freeCache" call to not delete 8886 * the file we care about. 8887 */ 8888 if (pkgLite.recommendedInstallLocation 8889 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8890 pkgLite.recommendedInstallLocation 8891 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8892 } 8893 } 8894 } 8895 8896 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8897 int loc = pkgLite.recommendedInstallLocation; 8898 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8899 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8900 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8901 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8902 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8903 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8904 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8905 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8906 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8907 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8908 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8909 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8910 } else { 8911 // Override with defaults if needed. 8912 loc = installLocationPolicy(pkgLite); 8913 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8914 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8915 } else if (!onSd && !onInt) { 8916 // Override install location with flags 8917 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8918 // Set the flag to install on external media. 8919 installFlags |= PackageManager.INSTALL_EXTERNAL; 8920 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8921 } else { 8922 // Make sure the flag for installing on external 8923 // media is unset 8924 installFlags |= PackageManager.INSTALL_INTERNAL; 8925 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8926 } 8927 } 8928 } 8929 } 8930 8931 final InstallArgs args = createInstallArgs(this); 8932 mArgs = args; 8933 8934 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8935 /* 8936 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8937 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8938 */ 8939 int userIdentifier = getUser().getIdentifier(); 8940 if (userIdentifier == UserHandle.USER_ALL 8941 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8942 userIdentifier = UserHandle.USER_OWNER; 8943 } 8944 8945 /* 8946 * Determine if we have any installed package verifiers. If we 8947 * do, then we'll defer to them to verify the packages. 8948 */ 8949 final int requiredUid = mRequiredVerifierPackage == null ? -1 8950 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8951 if (!origin.existing && requiredUid != -1 8952 && isVerificationEnabled(userIdentifier, installFlags)) { 8953 final Intent verification = new Intent( 8954 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8955 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 8956 PACKAGE_MIME_TYPE); 8957 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8958 8959 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8960 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8961 0 /* TODO: Which userId? */); 8962 8963 if (DEBUG_VERIFY) { 8964 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8965 + verification.toString() + " with " + pkgLite.verifiers.length 8966 + " optional verifiers"); 8967 } 8968 8969 final int verificationId = mPendingVerificationToken++; 8970 8971 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8972 8973 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8974 installerPackageName); 8975 8976 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 8977 installFlags); 8978 8979 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8980 pkgLite.packageName); 8981 8982 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8983 pkgLite.versionCode); 8984 8985 if (verificationParams != null) { 8986 if (verificationParams.getVerificationURI() != null) { 8987 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8988 verificationParams.getVerificationURI()); 8989 } 8990 if (verificationParams.getOriginatingURI() != null) { 8991 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8992 verificationParams.getOriginatingURI()); 8993 } 8994 if (verificationParams.getReferrer() != null) { 8995 verification.putExtra(Intent.EXTRA_REFERRER, 8996 verificationParams.getReferrer()); 8997 } 8998 if (verificationParams.getOriginatingUid() >= 0) { 8999 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9000 verificationParams.getOriginatingUid()); 9001 } 9002 if (verificationParams.getInstallerUid() >= 0) { 9003 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9004 verificationParams.getInstallerUid()); 9005 } 9006 } 9007 9008 final PackageVerificationState verificationState = new PackageVerificationState( 9009 requiredUid, args); 9010 9011 mPendingVerification.append(verificationId, verificationState); 9012 9013 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9014 receivers, verificationState); 9015 9016 /* 9017 * If any sufficient verifiers were listed in the package 9018 * manifest, attempt to ask them. 9019 */ 9020 if (sufficientVerifiers != null) { 9021 final int N = sufficientVerifiers.size(); 9022 if (N == 0) { 9023 Slog.i(TAG, "Additional verifiers required, but none installed."); 9024 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9025 } else { 9026 for (int i = 0; i < N; i++) { 9027 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9028 9029 final Intent sufficientIntent = new Intent(verification); 9030 sufficientIntent.setComponent(verifierComponent); 9031 9032 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9033 } 9034 } 9035 } 9036 9037 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9038 mRequiredVerifierPackage, receivers); 9039 if (ret == PackageManager.INSTALL_SUCCEEDED 9040 && mRequiredVerifierPackage != null) { 9041 /* 9042 * Send the intent to the required verification agent, 9043 * but only start the verification timeout after the 9044 * target BroadcastReceivers have run. 9045 */ 9046 verification.setComponent(requiredVerifierComponent); 9047 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9048 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9049 new BroadcastReceiver() { 9050 @Override 9051 public void onReceive(Context context, Intent intent) { 9052 final Message msg = mHandler 9053 .obtainMessage(CHECK_PENDING_VERIFICATION); 9054 msg.arg1 = verificationId; 9055 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9056 } 9057 }, null, 0, null, null); 9058 9059 /* 9060 * We don't want the copy to proceed until verification 9061 * succeeds, so null out this field. 9062 */ 9063 mArgs = null; 9064 } 9065 } else { 9066 /* 9067 * No package verification is enabled, so immediately start 9068 * the remote call to initiate copy using temporary file. 9069 */ 9070 ret = args.copyApk(mContainerService, true); 9071 } 9072 } 9073 9074 mRet = ret; 9075 } 9076 9077 @Override 9078 void handleReturnCode() { 9079 // If mArgs is null, then MCS couldn't be reached. When it 9080 // reconnects, it will try again to install. At that point, this 9081 // will succeed. 9082 if (mArgs != null) { 9083 processPendingInstall(mArgs, mRet); 9084 } 9085 } 9086 9087 @Override 9088 void handleServiceError() { 9089 mArgs = createInstallArgs(this); 9090 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9091 } 9092 9093 public boolean isForwardLocked() { 9094 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9095 } 9096 } 9097 9098 /** 9099 * Used during creation of InstallArgs 9100 * 9101 * @param installFlags package installation flags 9102 * @return true if should be installed on external storage 9103 */ 9104 private static boolean installOnSd(int installFlags) { 9105 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9106 return false; 9107 } 9108 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9109 return true; 9110 } 9111 return false; 9112 } 9113 9114 /** 9115 * Used during creation of InstallArgs 9116 * 9117 * @param installFlags package installation flags 9118 * @return true if should be installed as forward locked 9119 */ 9120 private static boolean installForwardLocked(int installFlags) { 9121 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9122 } 9123 9124 private InstallArgs createInstallArgs(InstallParams params) { 9125 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 9126 return new AsecInstallArgs(params); 9127 } else { 9128 return new FileInstallArgs(params); 9129 } 9130 } 9131 9132 /** 9133 * Create args that describe an existing installed package. Typically used 9134 * when cleaning up old installs, or used as a move source. 9135 */ 9136 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9137 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9138 final boolean isInAsec; 9139 if (installOnSd(installFlags)) { 9140 /* Apps on SD card are always in ASEC containers. */ 9141 isInAsec = true; 9142 } else if (installForwardLocked(installFlags) 9143 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9144 /* 9145 * Forward-locked apps are only in ASEC containers if they're the 9146 * new style 9147 */ 9148 isInAsec = true; 9149 } else { 9150 isInAsec = false; 9151 } 9152 9153 if (isInAsec) { 9154 return new AsecInstallArgs(codePath, instructionSets, 9155 installOnSd(installFlags), installForwardLocked(installFlags)); 9156 } else { 9157 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9158 instructionSets); 9159 } 9160 } 9161 9162 static abstract class InstallArgs { 9163 /** @see InstallParams#origin */ 9164 final OriginInfo origin; 9165 9166 final IPackageInstallObserver2 observer; 9167 // Always refers to PackageManager flags only 9168 final int installFlags; 9169 final String installerPackageName; 9170 final ManifestDigest manifestDigest; 9171 final UserHandle user; 9172 final String abiOverride; 9173 9174 // The list of instruction sets supported by this app. This is currently 9175 // only used during the rmdex() phase to clean up resources. We can get rid of this 9176 // if we move dex files under the common app path. 9177 /* nullable */ String[] instructionSets; 9178 9179 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9180 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 9181 String[] instructionSets, String abiOverride) { 9182 this.origin = origin; 9183 this.installFlags = installFlags; 9184 this.observer = observer; 9185 this.installerPackageName = installerPackageName; 9186 this.manifestDigest = manifestDigest; 9187 this.user = user; 9188 this.instructionSets = instructionSets; 9189 this.abiOverride = abiOverride; 9190 } 9191 9192 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9193 abstract int doPreInstall(int status); 9194 9195 /** 9196 * Rename package into final resting place. All paths on the given 9197 * scanned package should be updated to reflect the rename. 9198 */ 9199 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9200 abstract int doPostInstall(int status, int uid); 9201 9202 /** @see PackageSettingBase#codePathString */ 9203 abstract String getCodePath(); 9204 /** @see PackageSettingBase#resourcePathString */ 9205 abstract String getResourcePath(); 9206 abstract String getLegacyNativeLibraryPath(); 9207 9208 // Need installer lock especially for dex file removal. 9209 abstract void cleanUpResourcesLI(); 9210 abstract boolean doPostDeleteLI(boolean delete); 9211 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9212 9213 /** 9214 * Called before the source arguments are copied. This is used mostly 9215 * for MoveParams when it needs to read the source file to put it in the 9216 * destination. 9217 */ 9218 int doPreCopy() { 9219 return PackageManager.INSTALL_SUCCEEDED; 9220 } 9221 9222 /** 9223 * Called after the source arguments are copied. This is used mostly for 9224 * MoveParams when it needs to read the source file to put it in the 9225 * destination. 9226 * 9227 * @return 9228 */ 9229 int doPostCopy(int uid) { 9230 return PackageManager.INSTALL_SUCCEEDED; 9231 } 9232 9233 protected boolean isFwdLocked() { 9234 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9235 } 9236 9237 protected boolean isExternal() { 9238 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9239 } 9240 9241 UserHandle getUser() { 9242 return user; 9243 } 9244 } 9245 9246 /** 9247 * Logic to handle installation of non-ASEC applications, including copying 9248 * and renaming logic. 9249 */ 9250 class FileInstallArgs extends InstallArgs { 9251 private File codeFile; 9252 private File resourceFile; 9253 private File legacyNativeLibraryPath; 9254 9255 // Example topology: 9256 // /data/app/com.example/base.apk 9257 // /data/app/com.example/split_foo.apk 9258 // /data/app/com.example/lib/arm/libfoo.so 9259 // /data/app/com.example/lib/arm64/libfoo.so 9260 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9261 9262 /** New install */ 9263 FileInstallArgs(InstallParams params) { 9264 super(params.origin, params.observer, params.installFlags, 9265 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9266 null /* instruction sets */, params.packageAbiOverride); 9267 if (isFwdLocked()) { 9268 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9269 } 9270 } 9271 9272 /** Existing install */ 9273 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9274 String[] instructionSets) { 9275 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9276 this.codeFile = (codePath != null) ? new File(codePath) : null; 9277 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9278 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9279 new File(legacyNativeLibraryPath) : null; 9280 } 9281 9282 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9283 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9284 isFwdLocked(), abiOverride); 9285 9286 final StorageManager storage = StorageManager.from(mContext); 9287 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9288 } 9289 9290 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9291 if (origin.staged) { 9292 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9293 codeFile = origin.file; 9294 resourceFile = origin.file; 9295 return PackageManager.INSTALL_SUCCEEDED; 9296 } 9297 9298 try { 9299 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9300 codeFile = tempDir; 9301 resourceFile = tempDir; 9302 } catch (IOException e) { 9303 Slog.w(TAG, "Failed to create copy file: " + e); 9304 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9305 } 9306 9307 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9308 @Override 9309 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9310 if (!FileUtils.isValidExtFilename(name)) { 9311 throw new IllegalArgumentException("Invalid filename: " + name); 9312 } 9313 try { 9314 final File file = new File(codeFile, name); 9315 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9316 O_RDWR | O_CREAT, 0644); 9317 Os.chmod(file.getAbsolutePath(), 0644); 9318 return new ParcelFileDescriptor(fd); 9319 } catch (ErrnoException e) { 9320 throw new RemoteException("Failed to open: " + e.getMessage()); 9321 } 9322 } 9323 }; 9324 9325 int ret = PackageManager.INSTALL_SUCCEEDED; 9326 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9327 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9328 Slog.e(TAG, "Failed to copy package"); 9329 return ret; 9330 } 9331 9332 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9333 NativeLibraryHelper.Handle handle = null; 9334 try { 9335 handle = NativeLibraryHelper.Handle.create(codeFile); 9336 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9337 abiOverride); 9338 } catch (IOException e) { 9339 Slog.e(TAG, "Copying native libraries failed", e); 9340 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9341 } finally { 9342 IoUtils.closeQuietly(handle); 9343 } 9344 9345 return ret; 9346 } 9347 9348 int doPreInstall(int status) { 9349 if (status != PackageManager.INSTALL_SUCCEEDED) { 9350 cleanUp(); 9351 } 9352 return status; 9353 } 9354 9355 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9356 if (status != PackageManager.INSTALL_SUCCEEDED) { 9357 cleanUp(); 9358 return false; 9359 } else { 9360 final File beforeCodeFile = codeFile; 9361 final File afterCodeFile = getNextCodePath(pkg.packageName); 9362 9363 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9364 try { 9365 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9366 } catch (ErrnoException e) { 9367 Slog.d(TAG, "Failed to rename", e); 9368 return false; 9369 } 9370 9371 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9372 Slog.d(TAG, "Failed to restorecon"); 9373 return false; 9374 } 9375 9376 // Reflect the rename internally 9377 codeFile = afterCodeFile; 9378 resourceFile = afterCodeFile; 9379 9380 // Reflect the rename in scanned details 9381 pkg.codePath = afterCodeFile.getAbsolutePath(); 9382 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9383 pkg.baseCodePath); 9384 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9385 pkg.splitCodePaths); 9386 9387 // Reflect the rename in app info 9388 pkg.applicationInfo.setCodePath(pkg.codePath); 9389 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9390 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9391 pkg.applicationInfo.setResourcePath(pkg.codePath); 9392 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9393 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9394 9395 return true; 9396 } 9397 } 9398 9399 int doPostInstall(int status, int uid) { 9400 if (status != PackageManager.INSTALL_SUCCEEDED) { 9401 cleanUp(); 9402 } 9403 return status; 9404 } 9405 9406 @Override 9407 String getCodePath() { 9408 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9409 } 9410 9411 @Override 9412 String getResourcePath() { 9413 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9414 } 9415 9416 @Override 9417 String getLegacyNativeLibraryPath() { 9418 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9419 } 9420 9421 private boolean cleanUp() { 9422 if (codeFile == null || !codeFile.exists()) { 9423 return false; 9424 } 9425 9426 if (codeFile.isDirectory()) { 9427 FileUtils.deleteContents(codeFile); 9428 } 9429 codeFile.delete(); 9430 9431 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9432 resourceFile.delete(); 9433 } 9434 9435 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9436 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9437 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9438 } 9439 legacyNativeLibraryPath.delete(); 9440 } 9441 9442 return true; 9443 } 9444 9445 void cleanUpResourcesLI() { 9446 // Try enumerating all code paths before deleting 9447 List<String> allCodePaths = Collections.EMPTY_LIST; 9448 if (codeFile != null && codeFile.exists()) { 9449 try { 9450 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9451 allCodePaths = pkg.getAllCodePaths(); 9452 } catch (PackageParserException e) { 9453 // Ignored; we tried our best 9454 } 9455 } 9456 9457 cleanUp(); 9458 9459 if (!allCodePaths.isEmpty()) { 9460 if (instructionSets == null) { 9461 throw new IllegalStateException("instructionSet == null"); 9462 } 9463 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9464 for (String codePath : allCodePaths) { 9465 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9466 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9467 if (retCode < 0) { 9468 Slog.w(TAG, "Couldn't remove dex file for package: " 9469 + " at location " + codePath + ", retcode=" + retCode); 9470 // we don't consider this to be a failure of the core package deletion 9471 } 9472 } 9473 } 9474 } 9475 } 9476 9477 boolean doPostDeleteLI(boolean delete) { 9478 // XXX err, shouldn't we respect the delete flag? 9479 cleanUpResourcesLI(); 9480 return true; 9481 } 9482 } 9483 9484 private boolean isAsecExternal(String cid) { 9485 final String asecPath = PackageHelper.getSdFilesystem(cid); 9486 return !asecPath.startsWith(mAsecInternalPath); 9487 } 9488 9489 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9490 PackageManagerException { 9491 if (copyRet < 0) { 9492 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9493 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9494 throw new PackageManagerException(copyRet, message); 9495 } 9496 } 9497 } 9498 9499 /** 9500 * Extract the MountService "container ID" from the full code path of an 9501 * .apk. 9502 */ 9503 static String cidFromCodePath(String fullCodePath) { 9504 int eidx = fullCodePath.lastIndexOf("/"); 9505 String subStr1 = fullCodePath.substring(0, eidx); 9506 int sidx = subStr1.lastIndexOf("/"); 9507 return subStr1.substring(sidx+1, eidx); 9508 } 9509 9510 /** 9511 * Logic to handle installation of ASEC applications, including copying and 9512 * renaming logic. 9513 */ 9514 class AsecInstallArgs extends InstallArgs { 9515 static final String RES_FILE_NAME = "pkg.apk"; 9516 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9517 9518 String cid; 9519 String packagePath; 9520 String resourcePath; 9521 String legacyNativeLibraryDir; 9522 9523 /** New install */ 9524 AsecInstallArgs(InstallParams params) { 9525 super(params.origin, params.observer, params.installFlags, 9526 params.installerPackageName, params.getManifestDigest(), 9527 params.getUser(), null /* instruction sets */, 9528 params.packageAbiOverride); 9529 } 9530 9531 /** Existing install */ 9532 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9533 boolean isExternal, boolean isForwardLocked) { 9534 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9535 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9536 instructionSets, null); 9537 // Hackily pretend we're still looking at a full code path 9538 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9539 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9540 } 9541 9542 // Extract cid from fullCodePath 9543 int eidx = fullCodePath.lastIndexOf("/"); 9544 String subStr1 = fullCodePath.substring(0, eidx); 9545 int sidx = subStr1.lastIndexOf("/"); 9546 cid = subStr1.substring(sidx+1, eidx); 9547 setMountPath(subStr1); 9548 } 9549 9550 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9551 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9552 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9553 instructionSets, null); 9554 this.cid = cid; 9555 setMountPath(PackageHelper.getSdDir(cid)); 9556 } 9557 9558 void createCopyFile() { 9559 cid = mInstallerService.allocateExternalStageCidLegacy(); 9560 } 9561 9562 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9563 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9564 abiOverride); 9565 9566 final File target; 9567 if (isExternal()) { 9568 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9569 } else { 9570 target = Environment.getDataDirectory(); 9571 } 9572 9573 final StorageManager storage = StorageManager.from(mContext); 9574 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9575 } 9576 9577 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9578 if (origin.staged) { 9579 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9580 cid = origin.cid; 9581 setMountPath(PackageHelper.getSdDir(cid)); 9582 return PackageManager.INSTALL_SUCCEEDED; 9583 } 9584 9585 if (temp) { 9586 createCopyFile(); 9587 } else { 9588 /* 9589 * Pre-emptively destroy the container since it's destroyed if 9590 * copying fails due to it existing anyway. 9591 */ 9592 PackageHelper.destroySdDir(cid); 9593 } 9594 9595 final String newMountPath = imcs.copyPackageToContainer( 9596 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9597 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9598 9599 if (newMountPath != null) { 9600 setMountPath(newMountPath); 9601 return PackageManager.INSTALL_SUCCEEDED; 9602 } else { 9603 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9604 } 9605 } 9606 9607 @Override 9608 String getCodePath() { 9609 return packagePath; 9610 } 9611 9612 @Override 9613 String getResourcePath() { 9614 return resourcePath; 9615 } 9616 9617 @Override 9618 String getLegacyNativeLibraryPath() { 9619 return legacyNativeLibraryDir; 9620 } 9621 9622 int doPreInstall(int status) { 9623 if (status != PackageManager.INSTALL_SUCCEEDED) { 9624 // Destroy container 9625 PackageHelper.destroySdDir(cid); 9626 } else { 9627 boolean mounted = PackageHelper.isContainerMounted(cid); 9628 if (!mounted) { 9629 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9630 Process.SYSTEM_UID); 9631 if (newMountPath != null) { 9632 setMountPath(newMountPath); 9633 } else { 9634 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9635 } 9636 } 9637 } 9638 return status; 9639 } 9640 9641 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9642 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9643 String newMountPath = null; 9644 if (PackageHelper.isContainerMounted(cid)) { 9645 // Unmount the container 9646 if (!PackageHelper.unMountSdDir(cid)) { 9647 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9648 return false; 9649 } 9650 } 9651 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9652 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9653 " which might be stale. Will try to clean up."); 9654 // Clean up the stale container and proceed to recreate. 9655 if (!PackageHelper.destroySdDir(newCacheId)) { 9656 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9657 return false; 9658 } 9659 // Successfully cleaned up stale container. Try to rename again. 9660 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9661 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9662 + " inspite of cleaning it up."); 9663 return false; 9664 } 9665 } 9666 if (!PackageHelper.isContainerMounted(newCacheId)) { 9667 Slog.w(TAG, "Mounting container " + newCacheId); 9668 newMountPath = PackageHelper.mountSdDir(newCacheId, 9669 getEncryptKey(), Process.SYSTEM_UID); 9670 } else { 9671 newMountPath = PackageHelper.getSdDir(newCacheId); 9672 } 9673 if (newMountPath == null) { 9674 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9675 return false; 9676 } 9677 Log.i(TAG, "Succesfully renamed " + cid + 9678 " to " + newCacheId + 9679 " at new path: " + newMountPath); 9680 cid = newCacheId; 9681 9682 final File beforeCodeFile = new File(packagePath); 9683 setMountPath(newMountPath); 9684 final File afterCodeFile = new File(packagePath); 9685 9686 // Reflect the rename in scanned details 9687 pkg.codePath = afterCodeFile.getAbsolutePath(); 9688 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9689 pkg.baseCodePath); 9690 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9691 pkg.splitCodePaths); 9692 9693 // Reflect the rename in app info 9694 pkg.applicationInfo.setCodePath(pkg.codePath); 9695 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9696 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9697 pkg.applicationInfo.setResourcePath(pkg.codePath); 9698 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9699 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9700 9701 return true; 9702 } 9703 9704 private void setMountPath(String mountPath) { 9705 final File mountFile = new File(mountPath); 9706 9707 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9708 if (monolithicFile.exists()) { 9709 packagePath = monolithicFile.getAbsolutePath(); 9710 if (isFwdLocked()) { 9711 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9712 } else { 9713 resourcePath = packagePath; 9714 } 9715 } else { 9716 packagePath = mountFile.getAbsolutePath(); 9717 resourcePath = packagePath; 9718 } 9719 9720 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9721 } 9722 9723 int doPostInstall(int status, int uid) { 9724 if (status != PackageManager.INSTALL_SUCCEEDED) { 9725 cleanUp(); 9726 } else { 9727 final int groupOwner; 9728 final String protectedFile; 9729 if (isFwdLocked()) { 9730 groupOwner = UserHandle.getSharedAppGid(uid); 9731 protectedFile = RES_FILE_NAME; 9732 } else { 9733 groupOwner = -1; 9734 protectedFile = null; 9735 } 9736 9737 if (uid < Process.FIRST_APPLICATION_UID 9738 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9739 Slog.e(TAG, "Failed to finalize " + cid); 9740 PackageHelper.destroySdDir(cid); 9741 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9742 } 9743 9744 boolean mounted = PackageHelper.isContainerMounted(cid); 9745 if (!mounted) { 9746 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9747 } 9748 } 9749 return status; 9750 } 9751 9752 private void cleanUp() { 9753 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9754 9755 // Destroy secure container 9756 PackageHelper.destroySdDir(cid); 9757 } 9758 9759 private List<String> getAllCodePaths() { 9760 final File codeFile = new File(getCodePath()); 9761 if (codeFile != null && codeFile.exists()) { 9762 try { 9763 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9764 return pkg.getAllCodePaths(); 9765 } catch (PackageParserException e) { 9766 // Ignored; we tried our best 9767 } 9768 } 9769 return Collections.EMPTY_LIST; 9770 } 9771 9772 void cleanUpResourcesLI() { 9773 // Enumerate all code paths before deleting 9774 cleanUpResourcesLI(getAllCodePaths()); 9775 } 9776 9777 private void cleanUpResourcesLI(List<String> allCodePaths) { 9778 cleanUp(); 9779 9780 if (!allCodePaths.isEmpty()) { 9781 if (instructionSets == null) { 9782 throw new IllegalStateException("instructionSet == null"); 9783 } 9784 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9785 for (String codePath : allCodePaths) { 9786 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9787 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9788 if (retCode < 0) { 9789 Slog.w(TAG, "Couldn't remove dex file for package: " 9790 + " at location " + codePath + ", retcode=" + retCode); 9791 // we don't consider this to be a failure of the core package deletion 9792 } 9793 } 9794 } 9795 } 9796 } 9797 9798 boolean matchContainer(String app) { 9799 if (cid.startsWith(app)) { 9800 return true; 9801 } 9802 return false; 9803 } 9804 9805 String getPackageName() { 9806 return getAsecPackageName(cid); 9807 } 9808 9809 boolean doPostDeleteLI(boolean delete) { 9810 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9811 final List<String> allCodePaths = getAllCodePaths(); 9812 boolean mounted = PackageHelper.isContainerMounted(cid); 9813 if (mounted) { 9814 // Unmount first 9815 if (PackageHelper.unMountSdDir(cid)) { 9816 mounted = false; 9817 } 9818 } 9819 if (!mounted && delete) { 9820 cleanUpResourcesLI(allCodePaths); 9821 } 9822 return !mounted; 9823 } 9824 9825 @Override 9826 int doPreCopy() { 9827 if (isFwdLocked()) { 9828 if (!PackageHelper.fixSdPermissions(cid, 9829 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9830 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9831 } 9832 } 9833 9834 return PackageManager.INSTALL_SUCCEEDED; 9835 } 9836 9837 @Override 9838 int doPostCopy(int uid) { 9839 if (isFwdLocked()) { 9840 if (uid < Process.FIRST_APPLICATION_UID 9841 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9842 RES_FILE_NAME)) { 9843 Slog.e(TAG, "Failed to finalize " + cid); 9844 PackageHelper.destroySdDir(cid); 9845 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9846 } 9847 } 9848 9849 return PackageManager.INSTALL_SUCCEEDED; 9850 } 9851 } 9852 9853 static String getAsecPackageName(String packageCid) { 9854 int idx = packageCid.lastIndexOf("-"); 9855 if (idx == -1) { 9856 return packageCid; 9857 } 9858 return packageCid.substring(0, idx); 9859 } 9860 9861 // Utility method used to create code paths based on package name and available index. 9862 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9863 String idxStr = ""; 9864 int idx = 1; 9865 // Fall back to default value of idx=1 if prefix is not 9866 // part of oldCodePath 9867 if (oldCodePath != null) { 9868 String subStr = oldCodePath; 9869 // Drop the suffix right away 9870 if (suffix != null && subStr.endsWith(suffix)) { 9871 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9872 } 9873 // If oldCodePath already contains prefix find out the 9874 // ending index to either increment or decrement. 9875 int sidx = subStr.lastIndexOf(prefix); 9876 if (sidx != -1) { 9877 subStr = subStr.substring(sidx + prefix.length()); 9878 if (subStr != null) { 9879 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9880 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9881 } 9882 try { 9883 idx = Integer.parseInt(subStr); 9884 if (idx <= 1) { 9885 idx++; 9886 } else { 9887 idx--; 9888 } 9889 } catch(NumberFormatException e) { 9890 } 9891 } 9892 } 9893 } 9894 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9895 return prefix + idxStr; 9896 } 9897 9898 private File getNextCodePath(String packageName) { 9899 int suffix = 1; 9900 File result; 9901 do { 9902 result = new File(mAppInstallDir, packageName + "-" + suffix); 9903 suffix++; 9904 } while (result.exists()); 9905 return result; 9906 } 9907 9908 // Utility method used to ignore ADD/REMOVE events 9909 // by directory observer. 9910 private static boolean ignoreCodePath(String fullPathStr) { 9911 String apkName = deriveCodePathName(fullPathStr); 9912 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9913 if (idx != -1 && ((idx+1) < apkName.length())) { 9914 // Make sure the package ends with a numeral 9915 String version = apkName.substring(idx+1); 9916 try { 9917 Integer.parseInt(version); 9918 return true; 9919 } catch (NumberFormatException e) {} 9920 } 9921 return false; 9922 } 9923 9924 // Utility method that returns the relative package path with respect 9925 // to the installation directory. Like say for /data/data/com.test-1.apk 9926 // string com.test-1 is returned. 9927 static String deriveCodePathName(String codePath) { 9928 if (codePath == null) { 9929 return null; 9930 } 9931 final File codeFile = new File(codePath); 9932 final String name = codeFile.getName(); 9933 if (codeFile.isDirectory()) { 9934 return name; 9935 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9936 final int lastDot = name.lastIndexOf('.'); 9937 return name.substring(0, lastDot); 9938 } else { 9939 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9940 return null; 9941 } 9942 } 9943 9944 class PackageInstalledInfo { 9945 String name; 9946 int uid; 9947 // The set of users that originally had this package installed. 9948 int[] origUsers; 9949 // The set of users that now have this package installed. 9950 int[] newUsers; 9951 PackageParser.Package pkg; 9952 int returnCode; 9953 String returnMsg; 9954 PackageRemovedInfo removedInfo; 9955 9956 public void setError(int code, String msg) { 9957 returnCode = code; 9958 returnMsg = msg; 9959 Slog.w(TAG, msg); 9960 } 9961 9962 public void setError(String msg, PackageParserException e) { 9963 returnCode = e.error; 9964 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9965 Slog.w(TAG, msg, e); 9966 } 9967 9968 public void setError(String msg, PackageManagerException e) { 9969 returnCode = e.error; 9970 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9971 Slog.w(TAG, msg, e); 9972 } 9973 9974 // In some error cases we want to convey more info back to the observer 9975 String origPackage; 9976 String origPermission; 9977 } 9978 9979 /* 9980 * Install a non-existing package. 9981 */ 9982 private void installNewPackageLI(PackageParser.Package pkg, 9983 int parseFlags, int scanFlags, UserHandle user, 9984 String installerPackageName, PackageInstalledInfo res) { 9985 // Remember this for later, in case we need to rollback this install 9986 String pkgName = pkg.packageName; 9987 9988 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9989 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9990 synchronized(mPackages) { 9991 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9992 // A package with the same name is already installed, though 9993 // it has been renamed to an older name. The package we 9994 // are trying to install should be installed as an update to 9995 // the existing one, but that has not been requested, so bail. 9996 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9997 + " without first uninstalling package running as " 9998 + mSettings.mRenamedPackages.get(pkgName)); 9999 return; 10000 } 10001 if (mPackages.containsKey(pkgName)) { 10002 // Don't allow installation over an existing package with the same name. 10003 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10004 + " without first uninstalling."); 10005 return; 10006 } 10007 } 10008 10009 try { 10010 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10011 System.currentTimeMillis(), user); 10012 10013 updateSettingsLI(newPackage, installerPackageName, null, null, res); 10014 // delete the partially installed application. the data directory will have to be 10015 // restored if it was already existing 10016 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10017 // remove package from internal structures. Note that we want deletePackageX to 10018 // delete the package data and cache directories that it created in 10019 // scanPackageLocked, unless those directories existed before we even tried to 10020 // install. 10021 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10022 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10023 res.removedInfo, true); 10024 } 10025 10026 } catch (PackageManagerException e) { 10027 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10028 } 10029 } 10030 10031 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10032 // Upgrade keysets are being used. Determine if new package has a superset of the 10033 // required keys. 10034 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10035 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10036 for (int i = 0; i < upgradeKeySets.length; i++) { 10037 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10038 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10039 return true; 10040 } 10041 } 10042 return false; 10043 } 10044 10045 private void replacePackageLI(PackageParser.Package pkg, 10046 int parseFlags, int scanFlags, UserHandle user, 10047 String installerPackageName, PackageInstalledInfo res) { 10048 PackageParser.Package oldPackage; 10049 String pkgName = pkg.packageName; 10050 int[] allUsers; 10051 boolean[] perUserInstalled; 10052 10053 // First find the old package info and check signatures 10054 synchronized(mPackages) { 10055 oldPackage = mPackages.get(pkgName); 10056 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10057 PackageSetting ps = mSettings.mPackages.get(pkgName); 10058 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10059 // default to original signature matching 10060 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10061 != PackageManager.SIGNATURE_MATCH) { 10062 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10063 "New package has a different signature: " + pkgName); 10064 return; 10065 } 10066 } else { 10067 if(!checkUpgradeKeySetLP(ps, pkg)) { 10068 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10069 "New package not signed by keys specified by upgrade-keysets: " 10070 + pkgName); 10071 return; 10072 } 10073 } 10074 10075 // In case of rollback, remember per-user/profile install state 10076 allUsers = sUserManager.getUserIds(); 10077 perUserInstalled = new boolean[allUsers.length]; 10078 for (int i = 0; i < allUsers.length; i++) { 10079 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10080 } 10081 } 10082 10083 boolean sysPkg = (isSystemApp(oldPackage)); 10084 if (sysPkg) { 10085 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10086 user, allUsers, perUserInstalled, installerPackageName, res); 10087 } else { 10088 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10089 user, allUsers, perUserInstalled, installerPackageName, res); 10090 } 10091 } 10092 10093 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10094 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10095 int[] allUsers, boolean[] perUserInstalled, 10096 String installerPackageName, PackageInstalledInfo res) { 10097 String pkgName = deletedPackage.packageName; 10098 boolean deletedPkg = true; 10099 boolean updatedSettings = false; 10100 10101 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10102 + deletedPackage); 10103 long origUpdateTime; 10104 if (pkg.mExtras != null) { 10105 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10106 } else { 10107 origUpdateTime = 0; 10108 } 10109 10110 // First delete the existing package while retaining the data directory 10111 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10112 res.removedInfo, true)) { 10113 // If the existing package wasn't successfully deleted 10114 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10115 deletedPkg = false; 10116 } else { 10117 // Successfully deleted the old package; proceed with replace. 10118 10119 // If deleted package lived in a container, give users a chance to 10120 // relinquish resources before killing. 10121 if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) { 10122 if (DEBUG_INSTALL) { 10123 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10124 } 10125 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10126 final ArrayList<String> pkgList = new ArrayList<String>(1); 10127 pkgList.add(deletedPackage.applicationInfo.packageName); 10128 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10129 } 10130 10131 deleteCodeCacheDirsLI(pkgName); 10132 try { 10133 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10134 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10135 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10136 updatedSettings = true; 10137 } catch (PackageManagerException e) { 10138 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10139 } 10140 } 10141 10142 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10143 // remove package from internal structures. Note that we want deletePackageX to 10144 // delete the package data and cache directories that it created in 10145 // scanPackageLocked, unless those directories existed before we even tried to 10146 // install. 10147 if(updatedSettings) { 10148 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10149 deletePackageLI( 10150 pkgName, null, true, allUsers, perUserInstalled, 10151 PackageManager.DELETE_KEEP_DATA, 10152 res.removedInfo, true); 10153 } 10154 // Since we failed to install the new package we need to restore the old 10155 // package that we deleted. 10156 if (deletedPkg) { 10157 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10158 File restoreFile = new File(deletedPackage.codePath); 10159 // Parse old package 10160 boolean oldOnSd = isExternal(deletedPackage); 10161 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10162 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10163 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10164 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10165 try { 10166 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10167 } catch (PackageManagerException e) { 10168 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10169 + e.getMessage()); 10170 return; 10171 } 10172 // Restore of old package succeeded. Update permissions. 10173 // writer 10174 synchronized (mPackages) { 10175 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10176 UPDATE_PERMISSIONS_ALL); 10177 // can downgrade to reader 10178 mSettings.writeLPr(); 10179 } 10180 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10181 } 10182 } 10183 } 10184 10185 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10186 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10187 int[] allUsers, boolean[] perUserInstalled, 10188 String installerPackageName, PackageInstalledInfo res) { 10189 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10190 + ", old=" + deletedPackage); 10191 boolean disabledSystem = false; 10192 boolean updatedSettings = false; 10193 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10194 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10195 != 0) { 10196 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10197 } 10198 String packageName = deletedPackage.packageName; 10199 if (packageName == null) { 10200 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10201 "Attempt to delete null packageName."); 10202 return; 10203 } 10204 PackageParser.Package oldPkg; 10205 PackageSetting oldPkgSetting; 10206 // reader 10207 synchronized (mPackages) { 10208 oldPkg = mPackages.get(packageName); 10209 oldPkgSetting = mSettings.mPackages.get(packageName); 10210 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10211 (oldPkgSetting == null)) { 10212 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10213 "Couldn't find package:" + packageName + " information"); 10214 return; 10215 } 10216 } 10217 10218 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10219 10220 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10221 res.removedInfo.removedPackage = packageName; 10222 // Remove existing system package 10223 removePackageLI(oldPkgSetting, true); 10224 // writer 10225 synchronized (mPackages) { 10226 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10227 if (!disabledSystem && deletedPackage != null) { 10228 // We didn't need to disable the .apk as a current system package, 10229 // which means we are replacing another update that is already 10230 // installed. We need to make sure to delete the older one's .apk. 10231 res.removedInfo.args = createInstallArgsForExisting(0, 10232 deletedPackage.applicationInfo.getCodePath(), 10233 deletedPackage.applicationInfo.getResourcePath(), 10234 deletedPackage.applicationInfo.nativeLibraryRootDir, 10235 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10236 } else { 10237 res.removedInfo.args = null; 10238 } 10239 } 10240 10241 // Successfully disabled the old package. Now proceed with re-installation 10242 deleteCodeCacheDirsLI(packageName); 10243 10244 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10245 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10246 10247 PackageParser.Package newPackage = null; 10248 try { 10249 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10250 if (newPackage.mExtras != null) { 10251 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10252 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10253 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10254 10255 // is the update attempting to change shared user? that isn't going to work... 10256 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10257 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10258 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10259 + " to " + newPkgSetting.sharedUser); 10260 updatedSettings = true; 10261 } 10262 } 10263 10264 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10265 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10266 updatedSettings = true; 10267 } 10268 10269 } catch (PackageManagerException e) { 10270 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10271 } 10272 10273 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10274 // Re installation failed. Restore old information 10275 // Remove new pkg information 10276 if (newPackage != null) { 10277 removeInstalledPackageLI(newPackage, true); 10278 } 10279 // Add back the old system package 10280 try { 10281 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10282 } catch (PackageManagerException e) { 10283 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10284 } 10285 // Restore the old system information in Settings 10286 synchronized (mPackages) { 10287 if (disabledSystem) { 10288 mSettings.enableSystemPackageLPw(packageName); 10289 } 10290 if (updatedSettings) { 10291 mSettings.setInstallerPackageName(packageName, 10292 oldPkgSetting.installerPackageName); 10293 } 10294 mSettings.writeLPr(); 10295 } 10296 } 10297 } 10298 10299 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10300 int[] allUsers, boolean[] perUserInstalled, 10301 PackageInstalledInfo res) { 10302 String pkgName = newPackage.packageName; 10303 synchronized (mPackages) { 10304 //write settings. the installStatus will be incomplete at this stage. 10305 //note that the new package setting would have already been 10306 //added to mPackages. It hasn't been persisted yet. 10307 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10308 mSettings.writeLPr(); 10309 } 10310 10311 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10312 10313 synchronized (mPackages) { 10314 updatePermissionsLPw(newPackage.packageName, newPackage, 10315 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10316 ? UPDATE_PERMISSIONS_ALL : 0)); 10317 // For system-bundled packages, we assume that installing an upgraded version 10318 // of the package implies that the user actually wants to run that new code, 10319 // so we enable the package. 10320 if (isSystemApp(newPackage)) { 10321 // NB: implicit assumption that system package upgrades apply to all users 10322 if (DEBUG_INSTALL) { 10323 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10324 } 10325 PackageSetting ps = mSettings.mPackages.get(pkgName); 10326 if (ps != null) { 10327 if (res.origUsers != null) { 10328 for (int userHandle : res.origUsers) { 10329 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10330 userHandle, installerPackageName); 10331 } 10332 } 10333 // Also convey the prior install/uninstall state 10334 if (allUsers != null && perUserInstalled != null) { 10335 for (int i = 0; i < allUsers.length; i++) { 10336 if (DEBUG_INSTALL) { 10337 Slog.d(TAG, " user " + allUsers[i] 10338 + " => " + perUserInstalled[i]); 10339 } 10340 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10341 } 10342 // these install state changes will be persisted in the 10343 // upcoming call to mSettings.writeLPr(). 10344 } 10345 } 10346 } 10347 res.name = pkgName; 10348 res.uid = newPackage.applicationInfo.uid; 10349 res.pkg = newPackage; 10350 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10351 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10352 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10353 //to update install status 10354 mSettings.writeLPr(); 10355 } 10356 } 10357 10358 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10359 final int installFlags = args.installFlags; 10360 String installerPackageName = args.installerPackageName; 10361 File tmpPackageFile = new File(args.getCodePath()); 10362 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10363 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10364 boolean replace = false; 10365 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10366 // Result object to be returned 10367 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10368 10369 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10370 // Retrieve PackageSettings and parse package 10371 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10372 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10373 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10374 PackageParser pp = new PackageParser(); 10375 pp.setSeparateProcesses(mSeparateProcesses); 10376 pp.setDisplayMetrics(mMetrics); 10377 10378 final PackageParser.Package pkg; 10379 try { 10380 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10381 } catch (PackageParserException e) { 10382 res.setError("Failed parse during installPackageLI", e); 10383 return; 10384 } 10385 10386 // Mark that we have an install time CPU ABI override. 10387 pkg.cpuAbiOverride = args.abiOverride; 10388 10389 String pkgName = res.name = pkg.packageName; 10390 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10391 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10392 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10393 return; 10394 } 10395 } 10396 10397 try { 10398 pp.collectCertificates(pkg, parseFlags); 10399 pp.collectManifestDigest(pkg); 10400 } catch (PackageParserException e) { 10401 res.setError("Failed collect during installPackageLI", e); 10402 return; 10403 } 10404 10405 /* If the installer passed in a manifest digest, compare it now. */ 10406 if (args.manifestDigest != null) { 10407 if (DEBUG_INSTALL) { 10408 final String parsedManifest = pkg.manifestDigest == null ? "null" 10409 : pkg.manifestDigest.toString(); 10410 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10411 + parsedManifest); 10412 } 10413 10414 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10415 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10416 return; 10417 } 10418 } else if (DEBUG_INSTALL) { 10419 final String parsedManifest = pkg.manifestDigest == null 10420 ? "null" : pkg.manifestDigest.toString(); 10421 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10422 } 10423 10424 // Get rid of all references to package scan path via parser. 10425 pp = null; 10426 String oldCodePath = null; 10427 boolean systemApp = false; 10428 synchronized (mPackages) { 10429 // Check whether the newly-scanned package wants to define an already-defined perm 10430 int N = pkg.permissions.size(); 10431 for (int i = N-1; i >= 0; i--) { 10432 PackageParser.Permission perm = pkg.permissions.get(i); 10433 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10434 if (bp != null) { 10435 // If the defining package is signed with our cert, it's okay. This 10436 // also includes the "updating the same package" case, of course. 10437 // "updating same package" could also involve key-rotation. 10438 final boolean sigsOk; 10439 if (!bp.sourcePackage.equals(pkg.packageName) 10440 || !(bp.packageSetting instanceof PackageSetting) 10441 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10442 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10443 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10444 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 10445 } else { 10446 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10447 } 10448 if (!sigsOk) { 10449 // If the owning package is the system itself, we log but allow 10450 // install to proceed; we fail the install on all other permission 10451 // redefinitions. 10452 if (!bp.sourcePackage.equals("android")) { 10453 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10454 + pkg.packageName + " attempting to redeclare permission " 10455 + perm.info.name + " already owned by " + bp.sourcePackage); 10456 res.origPermission = perm.info.name; 10457 res.origPackage = bp.sourcePackage; 10458 return; 10459 } else { 10460 Slog.w(TAG, "Package " + pkg.packageName 10461 + " attempting to redeclare system permission " 10462 + perm.info.name + "; ignoring new declaration"); 10463 pkg.permissions.remove(i); 10464 } 10465 } 10466 } 10467 } 10468 10469 // Check if installing already existing package 10470 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10471 String oldName = mSettings.mRenamedPackages.get(pkgName); 10472 if (pkg.mOriginalPackages != null 10473 && pkg.mOriginalPackages.contains(oldName) 10474 && mPackages.containsKey(oldName)) { 10475 // This package is derived from an original package, 10476 // and this device has been updating from that original 10477 // name. We must continue using the original name, so 10478 // rename the new package here. 10479 pkg.setPackageName(oldName); 10480 pkgName = pkg.packageName; 10481 replace = true; 10482 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10483 + oldName + " pkgName=" + pkgName); 10484 } else if (mPackages.containsKey(pkgName)) { 10485 // This package, under its official name, already exists 10486 // on the device; we should replace it. 10487 replace = true; 10488 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10489 } 10490 } 10491 PackageSetting ps = mSettings.mPackages.get(pkgName); 10492 if (ps != null) { 10493 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10494 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10495 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10496 systemApp = (ps.pkg.applicationInfo.flags & 10497 ApplicationInfo.FLAG_SYSTEM) != 0; 10498 } 10499 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10500 } 10501 } 10502 10503 if (systemApp && onSd) { 10504 // Disable updates to system apps on sdcard 10505 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10506 "Cannot install updates to system apps on sdcard"); 10507 return; 10508 } 10509 10510 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10511 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10512 return; 10513 } 10514 10515 if (replace) { 10516 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10517 installerPackageName, res); 10518 } else { 10519 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10520 args.user, installerPackageName, res); 10521 } 10522 synchronized (mPackages) { 10523 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10524 if (ps != null) { 10525 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10526 } 10527 } 10528 } 10529 10530 private static boolean isForwardLocked(PackageParser.Package pkg) { 10531 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_FORWARD_LOCK) != 0; 10532 } 10533 10534 private static boolean isForwardLocked(ApplicationInfo info) { 10535 return (info.privateFlags & ApplicationInfo.PRIVATE_FLAG_FORWARD_LOCK) != 0; 10536 } 10537 10538 private boolean isForwardLocked(PackageSetting ps) { 10539 return (ps.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_FORWARD_LOCK) != 0; 10540 } 10541 10542 private static boolean isMultiArch(PackageSetting ps) { 10543 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10544 } 10545 10546 private static boolean isMultiArch(ApplicationInfo info) { 10547 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10548 } 10549 10550 private static boolean isExternal(PackageParser.Package pkg) { 10551 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10552 } 10553 10554 private static boolean isExternal(PackageSetting ps) { 10555 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10556 } 10557 10558 private static boolean isExternal(ApplicationInfo info) { 10559 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10560 } 10561 10562 private static boolean isSystemApp(PackageParser.Package pkg) { 10563 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10564 } 10565 10566 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10567 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 10568 } 10569 10570 private static boolean isSystemApp(ApplicationInfo info) { 10571 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10572 } 10573 10574 private static boolean isSystemApp(PackageSetting ps) { 10575 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10576 } 10577 10578 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10579 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10580 } 10581 10582 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10583 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10584 } 10585 10586 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10587 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10588 } 10589 10590 private int packageFlagsToInstallFlags(PackageSetting ps) { 10591 int installFlags = 0; 10592 if (isExternal(ps)) { 10593 installFlags |= PackageManager.INSTALL_EXTERNAL; 10594 } 10595 if (isForwardLocked(ps)) { 10596 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10597 } 10598 return installFlags; 10599 } 10600 10601 private void deleteTempPackageFiles() { 10602 final FilenameFilter filter = new FilenameFilter() { 10603 public boolean accept(File dir, String name) { 10604 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10605 } 10606 }; 10607 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10608 file.delete(); 10609 } 10610 } 10611 10612 @Override 10613 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10614 int flags) { 10615 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10616 flags); 10617 } 10618 10619 @Override 10620 public void deletePackage(final String packageName, 10621 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10622 mContext.enforceCallingOrSelfPermission( 10623 android.Manifest.permission.DELETE_PACKAGES, null); 10624 final int uid = Binder.getCallingUid(); 10625 if (UserHandle.getUserId(uid) != userId) { 10626 mContext.enforceCallingPermission( 10627 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10628 "deletePackage for user " + userId); 10629 } 10630 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10631 try { 10632 observer.onPackageDeleted(packageName, 10633 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10634 } catch (RemoteException re) { 10635 } 10636 return; 10637 } 10638 10639 boolean uninstallBlocked = false; 10640 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10641 int[] users = sUserManager.getUserIds(); 10642 for (int i = 0; i < users.length; ++i) { 10643 if (getBlockUninstallForUser(packageName, users[i])) { 10644 uninstallBlocked = true; 10645 break; 10646 } 10647 } 10648 } else { 10649 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10650 } 10651 if (uninstallBlocked) { 10652 try { 10653 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10654 null); 10655 } catch (RemoteException re) { 10656 } 10657 return; 10658 } 10659 10660 if (DEBUG_REMOVE) { 10661 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10662 } 10663 // Queue up an async operation since the package deletion may take a little while. 10664 mHandler.post(new Runnable() { 10665 public void run() { 10666 mHandler.removeCallbacks(this); 10667 final int returnCode = deletePackageX(packageName, userId, flags); 10668 if (observer != null) { 10669 try { 10670 observer.onPackageDeleted(packageName, returnCode, null); 10671 } catch (RemoteException e) { 10672 Log.i(TAG, "Observer no longer exists."); 10673 } //end catch 10674 } //end if 10675 } //end run 10676 }); 10677 } 10678 10679 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10680 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10681 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10682 try { 10683 if (dpm != null) { 10684 if (dpm.isDeviceOwner(packageName)) { 10685 return true; 10686 } 10687 int[] users; 10688 if (userId == UserHandle.USER_ALL) { 10689 users = sUserManager.getUserIds(); 10690 } else { 10691 users = new int[]{userId}; 10692 } 10693 for (int i = 0; i < users.length; ++i) { 10694 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 10695 return true; 10696 } 10697 } 10698 } 10699 } catch (RemoteException e) { 10700 } 10701 return false; 10702 } 10703 10704 /** 10705 * This method is an internal method that could be get invoked either 10706 * to delete an installed package or to clean up a failed installation. 10707 * After deleting an installed package, a broadcast is sent to notify any 10708 * listeners that the package has been installed. For cleaning up a failed 10709 * installation, the broadcast is not necessary since the package's 10710 * installation wouldn't have sent the initial broadcast either 10711 * The key steps in deleting a package are 10712 * deleting the package information in internal structures like mPackages, 10713 * deleting the packages base directories through installd 10714 * updating mSettings to reflect current status 10715 * persisting settings for later use 10716 * sending a broadcast if necessary 10717 */ 10718 private int deletePackageX(String packageName, int userId, int flags) { 10719 final PackageRemovedInfo info = new PackageRemovedInfo(); 10720 final boolean res; 10721 10722 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 10723 ? UserHandle.ALL : new UserHandle(userId); 10724 10725 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 10726 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10727 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10728 } 10729 10730 boolean removedForAllUsers = false; 10731 boolean systemUpdate = false; 10732 10733 // for the uninstall-updates case and restricted profiles, remember the per- 10734 // userhandle installed state 10735 int[] allUsers; 10736 boolean[] perUserInstalled; 10737 synchronized (mPackages) { 10738 PackageSetting ps = mSettings.mPackages.get(packageName); 10739 allUsers = sUserManager.getUserIds(); 10740 perUserInstalled = new boolean[allUsers.length]; 10741 for (int i = 0; i < allUsers.length; i++) { 10742 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10743 } 10744 } 10745 10746 synchronized (mInstallLock) { 10747 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10748 res = deletePackageLI(packageName, removeForUser, 10749 true, allUsers, perUserInstalled, 10750 flags | REMOVE_CHATTY, info, true); 10751 systemUpdate = info.isRemovedPackageSystemUpdate; 10752 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10753 removedForAllUsers = true; 10754 } 10755 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10756 + " removedForAllUsers=" + removedForAllUsers); 10757 } 10758 10759 if (res) { 10760 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10761 10762 // If the removed package was a system update, the old system package 10763 // was re-enabled; we need to broadcast this information 10764 if (systemUpdate) { 10765 Bundle extras = new Bundle(1); 10766 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10767 ? info.removedAppId : info.uid); 10768 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10769 10770 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10771 extras, null, null, null); 10772 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10773 extras, null, null, null); 10774 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10775 null, packageName, null, null); 10776 } 10777 } 10778 // Force a gc here. 10779 Runtime.getRuntime().gc(); 10780 // Delete the resources here after sending the broadcast to let 10781 // other processes clean up before deleting resources. 10782 if (info.args != null) { 10783 synchronized (mInstallLock) { 10784 info.args.doPostDeleteLI(true); 10785 } 10786 } 10787 10788 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10789 } 10790 10791 static class PackageRemovedInfo { 10792 String removedPackage; 10793 int uid = -1; 10794 int removedAppId = -1; 10795 int[] removedUsers = null; 10796 boolean isRemovedPackageSystemUpdate = false; 10797 // Clean up resources deleted packages. 10798 InstallArgs args = null; 10799 10800 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10801 Bundle extras = new Bundle(1); 10802 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10803 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10804 if (replacing) { 10805 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10806 } 10807 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10808 if (removedPackage != null) { 10809 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10810 extras, null, null, removedUsers); 10811 if (fullRemove && !replacing) { 10812 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10813 extras, null, null, removedUsers); 10814 } 10815 } 10816 if (removedAppId >= 0) { 10817 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10818 removedUsers); 10819 } 10820 } 10821 } 10822 10823 /* 10824 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10825 * flag is not set, the data directory is removed as well. 10826 * make sure this flag is set for partially installed apps. If not its meaningless to 10827 * delete a partially installed application. 10828 */ 10829 private void removePackageDataLI(PackageSetting ps, 10830 int[] allUserHandles, boolean[] perUserInstalled, 10831 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10832 String packageName = ps.name; 10833 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10834 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10835 // Retrieve object to delete permissions for shared user later on 10836 final PackageSetting deletedPs; 10837 // reader 10838 synchronized (mPackages) { 10839 deletedPs = mSettings.mPackages.get(packageName); 10840 if (outInfo != null) { 10841 outInfo.removedPackage = packageName; 10842 outInfo.removedUsers = deletedPs != null 10843 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10844 : null; 10845 } 10846 } 10847 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10848 removeDataDirsLI(packageName); 10849 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10850 } 10851 // writer 10852 synchronized (mPackages) { 10853 if (deletedPs != null) { 10854 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10855 if (outInfo != null) { 10856 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10857 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10858 } 10859 if (deletedPs != null) { 10860 updatePermissionsLPw(deletedPs.name, null, 0); 10861 if (deletedPs.sharedUser != null) { 10862 // remove permissions associated with package 10863 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10864 } 10865 } 10866 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10867 } 10868 // make sure to preserve per-user disabled state if this removal was just 10869 // a downgrade of a system app to the factory package 10870 if (allUserHandles != null && perUserInstalled != null) { 10871 if (DEBUG_REMOVE) { 10872 Slog.d(TAG, "Propagating install state across downgrade"); 10873 } 10874 for (int i = 0; i < allUserHandles.length; i++) { 10875 if (DEBUG_REMOVE) { 10876 Slog.d(TAG, " user " + allUserHandles[i] 10877 + " => " + perUserInstalled[i]); 10878 } 10879 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10880 } 10881 } 10882 } 10883 // can downgrade to reader 10884 if (writeSettings) { 10885 // Save settings now 10886 mSettings.writeLPr(); 10887 } 10888 } 10889 if (outInfo != null) { 10890 // A user ID was deleted here. Go through all users and remove it 10891 // from KeyStore. 10892 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10893 } 10894 } 10895 10896 static boolean locationIsPrivileged(File path) { 10897 try { 10898 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10899 .getCanonicalPath(); 10900 return path.getCanonicalPath().startsWith(privilegedAppDir); 10901 } catch (IOException e) { 10902 Slog.e(TAG, "Unable to access code path " + path); 10903 } 10904 return false; 10905 } 10906 10907 /* 10908 * Tries to delete system package. 10909 */ 10910 private boolean deleteSystemPackageLI(PackageSetting newPs, 10911 int[] allUserHandles, boolean[] perUserInstalled, 10912 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10913 final boolean applyUserRestrictions 10914 = (allUserHandles != null) && (perUserInstalled != null); 10915 PackageSetting disabledPs = null; 10916 // Confirm if the system package has been updated 10917 // An updated system app can be deleted. This will also have to restore 10918 // the system pkg from system partition 10919 // reader 10920 synchronized (mPackages) { 10921 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10922 } 10923 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10924 + " disabledPs=" + disabledPs); 10925 if (disabledPs == null) { 10926 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10927 return false; 10928 } else if (DEBUG_REMOVE) { 10929 Slog.d(TAG, "Deleting system pkg from data partition"); 10930 } 10931 if (DEBUG_REMOVE) { 10932 if (applyUserRestrictions) { 10933 Slog.d(TAG, "Remembering install states:"); 10934 for (int i = 0; i < allUserHandles.length; i++) { 10935 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10936 } 10937 } 10938 } 10939 // Delete the updated package 10940 outInfo.isRemovedPackageSystemUpdate = true; 10941 if (disabledPs.versionCode < newPs.versionCode) { 10942 // Delete data for downgrades 10943 flags &= ~PackageManager.DELETE_KEEP_DATA; 10944 } else { 10945 // Preserve data by setting flag 10946 flags |= PackageManager.DELETE_KEEP_DATA; 10947 } 10948 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10949 allUserHandles, perUserInstalled, outInfo, writeSettings); 10950 if (!ret) { 10951 return false; 10952 } 10953 // writer 10954 synchronized (mPackages) { 10955 // Reinstate the old system package 10956 mSettings.enableSystemPackageLPw(newPs.name); 10957 // Remove any native libraries from the upgraded package. 10958 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10959 } 10960 // Install the system package 10961 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10962 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10963 if (locationIsPrivileged(disabledPs.codePath)) { 10964 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10965 } 10966 10967 final PackageParser.Package newPkg; 10968 try { 10969 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 10970 } catch (PackageManagerException e) { 10971 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10972 return false; 10973 } 10974 10975 // writer 10976 synchronized (mPackages) { 10977 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10978 updatePermissionsLPw(newPkg.packageName, newPkg, 10979 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10980 if (applyUserRestrictions) { 10981 if (DEBUG_REMOVE) { 10982 Slog.d(TAG, "Propagating install state across reinstall"); 10983 } 10984 for (int i = 0; i < allUserHandles.length; i++) { 10985 if (DEBUG_REMOVE) { 10986 Slog.d(TAG, " user " + allUserHandles[i] 10987 + " => " + perUserInstalled[i]); 10988 } 10989 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10990 } 10991 // Regardless of writeSettings we need to ensure that this restriction 10992 // state propagation is persisted 10993 mSettings.writeAllUsersPackageRestrictionsLPr(); 10994 } 10995 // can downgrade to reader here 10996 if (writeSettings) { 10997 mSettings.writeLPr(); 10998 } 10999 } 11000 return true; 11001 } 11002 11003 private boolean deleteInstalledPackageLI(PackageSetting ps, 11004 boolean deleteCodeAndResources, int flags, 11005 int[] allUserHandles, boolean[] perUserInstalled, 11006 PackageRemovedInfo outInfo, boolean writeSettings) { 11007 if (outInfo != null) { 11008 outInfo.uid = ps.appId; 11009 } 11010 11011 // Delete package data from internal structures and also remove data if flag is set 11012 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11013 11014 // Delete application code and resources 11015 if (deleteCodeAndResources && (outInfo != null)) { 11016 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11017 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11018 getAppDexInstructionSets(ps)); 11019 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11020 } 11021 return true; 11022 } 11023 11024 @Override 11025 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11026 int userId) { 11027 mContext.enforceCallingOrSelfPermission( 11028 android.Manifest.permission.DELETE_PACKAGES, null); 11029 synchronized (mPackages) { 11030 PackageSetting ps = mSettings.mPackages.get(packageName); 11031 if (ps == null) { 11032 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11033 return false; 11034 } 11035 if (!ps.getInstalled(userId)) { 11036 // Can't block uninstall for an app that is not installed or enabled. 11037 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11038 return false; 11039 } 11040 ps.setBlockUninstall(blockUninstall, userId); 11041 mSettings.writePackageRestrictionsLPr(userId); 11042 } 11043 return true; 11044 } 11045 11046 @Override 11047 public boolean getBlockUninstallForUser(String packageName, int userId) { 11048 synchronized (mPackages) { 11049 PackageSetting ps = mSettings.mPackages.get(packageName); 11050 if (ps == null) { 11051 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11052 return false; 11053 } 11054 return ps.getBlockUninstall(userId); 11055 } 11056 } 11057 11058 /* 11059 * This method handles package deletion in general 11060 */ 11061 private boolean deletePackageLI(String packageName, UserHandle user, 11062 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11063 int flags, PackageRemovedInfo outInfo, 11064 boolean writeSettings) { 11065 if (packageName == null) { 11066 Slog.w(TAG, "Attempt to delete null packageName."); 11067 return false; 11068 } 11069 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11070 PackageSetting ps; 11071 boolean dataOnly = false; 11072 int removeUser = -1; 11073 int appId = -1; 11074 synchronized (mPackages) { 11075 ps = mSettings.mPackages.get(packageName); 11076 if (ps == null) { 11077 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11078 return false; 11079 } 11080 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11081 && user.getIdentifier() != UserHandle.USER_ALL) { 11082 // The caller is asking that the package only be deleted for a single 11083 // user. To do this, we just mark its uninstalled state and delete 11084 // its data. If this is a system app, we only allow this to happen if 11085 // they have set the special DELETE_SYSTEM_APP which requests different 11086 // semantics than normal for uninstalling system apps. 11087 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11088 ps.setUserState(user.getIdentifier(), 11089 COMPONENT_ENABLED_STATE_DEFAULT, 11090 false, //installed 11091 true, //stopped 11092 true, //notLaunched 11093 false, //hidden 11094 null, null, null, 11095 false // blockUninstall 11096 ); 11097 if (!isSystemApp(ps)) { 11098 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11099 // Other user still have this package installed, so all 11100 // we need to do is clear this user's data and save that 11101 // it is uninstalled. 11102 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11103 removeUser = user.getIdentifier(); 11104 appId = ps.appId; 11105 mSettings.writePackageRestrictionsLPr(removeUser); 11106 } else { 11107 // We need to set it back to 'installed' so the uninstall 11108 // broadcasts will be sent correctly. 11109 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11110 ps.setInstalled(true, user.getIdentifier()); 11111 } 11112 } else { 11113 // This is a system app, so we assume that the 11114 // other users still have this package installed, so all 11115 // we need to do is clear this user's data and save that 11116 // it is uninstalled. 11117 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11118 removeUser = user.getIdentifier(); 11119 appId = ps.appId; 11120 mSettings.writePackageRestrictionsLPr(removeUser); 11121 } 11122 } 11123 } 11124 11125 if (removeUser >= 0) { 11126 // From above, we determined that we are deleting this only 11127 // for a single user. Continue the work here. 11128 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11129 if (outInfo != null) { 11130 outInfo.removedPackage = packageName; 11131 outInfo.removedAppId = appId; 11132 outInfo.removedUsers = new int[] {removeUser}; 11133 } 11134 mInstaller.clearUserData(packageName, removeUser); 11135 removeKeystoreDataIfNeeded(removeUser, appId); 11136 schedulePackageCleaning(packageName, removeUser, false); 11137 return true; 11138 } 11139 11140 if (dataOnly) { 11141 // Delete application data first 11142 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11143 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11144 return true; 11145 } 11146 11147 boolean ret = false; 11148 if (isSystemApp(ps)) { 11149 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11150 // When an updated system application is deleted we delete the existing resources as well and 11151 // fall back to existing code in system partition 11152 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11153 flags, outInfo, writeSettings); 11154 } else { 11155 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11156 // Kill application pre-emptively especially for apps on sd. 11157 killApplication(packageName, ps.appId, "uninstall pkg"); 11158 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11159 allUserHandles, perUserInstalled, 11160 outInfo, writeSettings); 11161 } 11162 11163 return ret; 11164 } 11165 11166 private final class ClearStorageConnection implements ServiceConnection { 11167 IMediaContainerService mContainerService; 11168 11169 @Override 11170 public void onServiceConnected(ComponentName name, IBinder service) { 11171 synchronized (this) { 11172 mContainerService = IMediaContainerService.Stub.asInterface(service); 11173 notifyAll(); 11174 } 11175 } 11176 11177 @Override 11178 public void onServiceDisconnected(ComponentName name) { 11179 } 11180 } 11181 11182 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11183 final boolean mounted; 11184 if (Environment.isExternalStorageEmulated()) { 11185 mounted = true; 11186 } else { 11187 final String status = Environment.getExternalStorageState(); 11188 11189 mounted = status.equals(Environment.MEDIA_MOUNTED) 11190 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11191 } 11192 11193 if (!mounted) { 11194 return; 11195 } 11196 11197 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11198 int[] users; 11199 if (userId == UserHandle.USER_ALL) { 11200 users = sUserManager.getUserIds(); 11201 } else { 11202 users = new int[] { userId }; 11203 } 11204 final ClearStorageConnection conn = new ClearStorageConnection(); 11205 if (mContext.bindServiceAsUser( 11206 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11207 try { 11208 for (int curUser : users) { 11209 long timeout = SystemClock.uptimeMillis() + 5000; 11210 synchronized (conn) { 11211 long now = SystemClock.uptimeMillis(); 11212 while (conn.mContainerService == null && now < timeout) { 11213 try { 11214 conn.wait(timeout - now); 11215 } catch (InterruptedException e) { 11216 } 11217 } 11218 } 11219 if (conn.mContainerService == null) { 11220 return; 11221 } 11222 11223 final UserEnvironment userEnv = new UserEnvironment(curUser); 11224 clearDirectory(conn.mContainerService, 11225 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11226 if (allData) { 11227 clearDirectory(conn.mContainerService, 11228 userEnv.buildExternalStorageAppDataDirs(packageName)); 11229 clearDirectory(conn.mContainerService, 11230 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11231 } 11232 } 11233 } finally { 11234 mContext.unbindService(conn); 11235 } 11236 } 11237 } 11238 11239 @Override 11240 public void clearApplicationUserData(final String packageName, 11241 final IPackageDataObserver observer, final int userId) { 11242 mContext.enforceCallingOrSelfPermission( 11243 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11244 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11245 // Queue up an async operation since the package deletion may take a little while. 11246 mHandler.post(new Runnable() { 11247 public void run() { 11248 mHandler.removeCallbacks(this); 11249 final boolean succeeded; 11250 synchronized (mInstallLock) { 11251 succeeded = clearApplicationUserDataLI(packageName, userId); 11252 } 11253 clearExternalStorageDataSync(packageName, userId, true); 11254 if (succeeded) { 11255 // invoke DeviceStorageMonitor's update method to clear any notifications 11256 DeviceStorageMonitorInternal 11257 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11258 if (dsm != null) { 11259 dsm.checkMemory(); 11260 } 11261 } 11262 if(observer != null) { 11263 try { 11264 observer.onRemoveCompleted(packageName, succeeded); 11265 } catch (RemoteException e) { 11266 Log.i(TAG, "Observer no longer exists."); 11267 } 11268 } //end if observer 11269 } //end run 11270 }); 11271 } 11272 11273 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11274 if (packageName == null) { 11275 Slog.w(TAG, "Attempt to delete null packageName."); 11276 return false; 11277 } 11278 11279 // Try finding details about the requested package 11280 PackageParser.Package pkg; 11281 synchronized (mPackages) { 11282 pkg = mPackages.get(packageName); 11283 if (pkg == null) { 11284 final PackageSetting ps = mSettings.mPackages.get(packageName); 11285 if (ps != null) { 11286 pkg = ps.pkg; 11287 } 11288 } 11289 } 11290 11291 if (pkg == null) { 11292 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11293 } 11294 11295 // Always delete data directories for package, even if we found no other 11296 // record of app. This helps users recover from UID mismatches without 11297 // resorting to a full data wipe. 11298 int retCode = mInstaller.clearUserData(packageName, userId); 11299 if (retCode < 0) { 11300 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 11301 return false; 11302 } 11303 11304 if (pkg == null) { 11305 return false; 11306 } 11307 11308 if (pkg != null && pkg.applicationInfo != null) { 11309 final int appId = pkg.applicationInfo.uid; 11310 removeKeystoreDataIfNeeded(userId, appId); 11311 } 11312 11313 // Create a native library symlink only if we have native libraries 11314 // and if the native libraries are 32 bit libraries. We do not provide 11315 // this symlink for 64 bit libraries. 11316 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11317 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11318 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11319 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11320 Slog.w(TAG, "Failed linking native library dir"); 11321 return false; 11322 } 11323 } 11324 11325 return true; 11326 } 11327 11328 /** 11329 * Remove entries from the keystore daemon. Will only remove it if the 11330 * {@code appId} is valid. 11331 */ 11332 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11333 if (appId < 0) { 11334 return; 11335 } 11336 11337 final KeyStore keyStore = KeyStore.getInstance(); 11338 if (keyStore != null) { 11339 if (userId == UserHandle.USER_ALL) { 11340 for (final int individual : sUserManager.getUserIds()) { 11341 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11342 } 11343 } else { 11344 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11345 } 11346 } else { 11347 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11348 } 11349 } 11350 11351 @Override 11352 public void deleteApplicationCacheFiles(final String packageName, 11353 final IPackageDataObserver observer) { 11354 mContext.enforceCallingOrSelfPermission( 11355 android.Manifest.permission.DELETE_CACHE_FILES, null); 11356 // Queue up an async operation since the package deletion may take a little while. 11357 final int userId = UserHandle.getCallingUserId(); 11358 mHandler.post(new Runnable() { 11359 public void run() { 11360 mHandler.removeCallbacks(this); 11361 final boolean succeded; 11362 synchronized (mInstallLock) { 11363 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11364 } 11365 clearExternalStorageDataSync(packageName, userId, false); 11366 if(observer != null) { 11367 try { 11368 observer.onRemoveCompleted(packageName, succeded); 11369 } catch (RemoteException e) { 11370 Log.i(TAG, "Observer no longer exists."); 11371 } 11372 } //end if observer 11373 } //end run 11374 }); 11375 } 11376 11377 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11378 if (packageName == null) { 11379 Slog.w(TAG, "Attempt to delete null packageName."); 11380 return false; 11381 } 11382 PackageParser.Package p; 11383 synchronized (mPackages) { 11384 p = mPackages.get(packageName); 11385 } 11386 if (p == null) { 11387 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11388 return false; 11389 } 11390 final ApplicationInfo applicationInfo = p.applicationInfo; 11391 if (applicationInfo == null) { 11392 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11393 return false; 11394 } 11395 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11396 if (retCode < 0) { 11397 Slog.w(TAG, "Couldn't remove cache files for package: " 11398 + packageName + " u" + userId); 11399 return false; 11400 } 11401 return true; 11402 } 11403 11404 @Override 11405 public void getPackageSizeInfo(final String packageName, int userHandle, 11406 final IPackageStatsObserver observer) { 11407 mContext.enforceCallingOrSelfPermission( 11408 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11409 if (packageName == null) { 11410 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11411 } 11412 11413 PackageStats stats = new PackageStats(packageName, userHandle); 11414 11415 /* 11416 * Queue up an async operation since the package measurement may take a 11417 * little while. 11418 */ 11419 Message msg = mHandler.obtainMessage(INIT_COPY); 11420 msg.obj = new MeasureParams(stats, observer); 11421 mHandler.sendMessage(msg); 11422 } 11423 11424 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11425 PackageStats pStats) { 11426 if (packageName == null) { 11427 Slog.w(TAG, "Attempt to get size of null packageName."); 11428 return false; 11429 } 11430 PackageParser.Package p; 11431 boolean dataOnly = false; 11432 String libDirRoot = null; 11433 String asecPath = null; 11434 PackageSetting ps = null; 11435 synchronized (mPackages) { 11436 p = mPackages.get(packageName); 11437 ps = mSettings.mPackages.get(packageName); 11438 if(p == null) { 11439 dataOnly = true; 11440 if((ps == null) || (ps.pkg == null)) { 11441 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11442 return false; 11443 } 11444 p = ps.pkg; 11445 } 11446 if (ps != null) { 11447 libDirRoot = ps.legacyNativeLibraryPathString; 11448 } 11449 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11450 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11451 if (secureContainerId != null) { 11452 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11453 } 11454 } 11455 } 11456 String publicSrcDir = null; 11457 if(!dataOnly) { 11458 final ApplicationInfo applicationInfo = p.applicationInfo; 11459 if (applicationInfo == null) { 11460 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11461 return false; 11462 } 11463 if (isForwardLocked(p)) { 11464 publicSrcDir = applicationInfo.getBaseResourcePath(); 11465 } 11466 } 11467 // TODO: extend to measure size of split APKs 11468 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11469 // not just the first level. 11470 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11471 // just the primary. 11472 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11473 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11474 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11475 if (res < 0) { 11476 return false; 11477 } 11478 11479 // Fix-up for forward-locked applications in ASEC containers. 11480 if (!isExternal(p)) { 11481 pStats.codeSize += pStats.externalCodeSize; 11482 pStats.externalCodeSize = 0L; 11483 } 11484 11485 return true; 11486 } 11487 11488 11489 @Override 11490 public void addPackageToPreferred(String packageName) { 11491 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11492 } 11493 11494 @Override 11495 public void removePackageFromPreferred(String packageName) { 11496 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11497 } 11498 11499 @Override 11500 public List<PackageInfo> getPreferredPackages(int flags) { 11501 return new ArrayList<PackageInfo>(); 11502 } 11503 11504 private int getUidTargetSdkVersionLockedLPr(int uid) { 11505 Object obj = mSettings.getUserIdLPr(uid); 11506 if (obj instanceof SharedUserSetting) { 11507 final SharedUserSetting sus = (SharedUserSetting) obj; 11508 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11509 final Iterator<PackageSetting> it = sus.packages.iterator(); 11510 while (it.hasNext()) { 11511 final PackageSetting ps = it.next(); 11512 if (ps.pkg != null) { 11513 int v = ps.pkg.applicationInfo.targetSdkVersion; 11514 if (v < vers) vers = v; 11515 } 11516 } 11517 return vers; 11518 } else if (obj instanceof PackageSetting) { 11519 final PackageSetting ps = (PackageSetting) obj; 11520 if (ps.pkg != null) { 11521 return ps.pkg.applicationInfo.targetSdkVersion; 11522 } 11523 } 11524 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11525 } 11526 11527 @Override 11528 public void addPreferredActivity(IntentFilter filter, int match, 11529 ComponentName[] set, ComponentName activity, int userId) { 11530 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11531 "Adding preferred"); 11532 } 11533 11534 private void addPreferredActivityInternal(IntentFilter filter, int match, 11535 ComponentName[] set, ComponentName activity, boolean always, int userId, 11536 String opname) { 11537 // writer 11538 int callingUid = Binder.getCallingUid(); 11539 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 11540 if (filter.countActions() == 0) { 11541 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11542 return; 11543 } 11544 synchronized (mPackages) { 11545 if (mContext.checkCallingOrSelfPermission( 11546 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11547 != PackageManager.PERMISSION_GRANTED) { 11548 if (getUidTargetSdkVersionLockedLPr(callingUid) 11549 < Build.VERSION_CODES.FROYO) { 11550 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11551 + callingUid); 11552 return; 11553 } 11554 mContext.enforceCallingOrSelfPermission( 11555 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11556 } 11557 11558 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11559 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11560 + userId + ":"); 11561 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11562 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11563 mSettings.writePackageRestrictionsLPr(userId); 11564 } 11565 } 11566 11567 @Override 11568 public void replacePreferredActivity(IntentFilter filter, int match, 11569 ComponentName[] set, ComponentName activity, int userId) { 11570 if (filter.countActions() != 1) { 11571 throw new IllegalArgumentException( 11572 "replacePreferredActivity expects filter to have only 1 action."); 11573 } 11574 if (filter.countDataAuthorities() != 0 11575 || filter.countDataPaths() != 0 11576 || filter.countDataSchemes() > 1 11577 || filter.countDataTypes() != 0) { 11578 throw new IllegalArgumentException( 11579 "replacePreferredActivity expects filter to have no data authorities, " + 11580 "paths, or types; and at most one scheme."); 11581 } 11582 11583 final int callingUid = Binder.getCallingUid(); 11584 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 11585 synchronized (mPackages) { 11586 if (mContext.checkCallingOrSelfPermission( 11587 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11588 != PackageManager.PERMISSION_GRANTED) { 11589 if (getUidTargetSdkVersionLockedLPr(callingUid) 11590 < Build.VERSION_CODES.FROYO) { 11591 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11592 + Binder.getCallingUid()); 11593 return; 11594 } 11595 mContext.enforceCallingOrSelfPermission( 11596 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11597 } 11598 11599 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11600 if (pir != null) { 11601 // Get all of the existing entries that exactly match this filter. 11602 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11603 if (existing != null && existing.size() == 1) { 11604 PreferredActivity cur = existing.get(0); 11605 if (DEBUG_PREFERRED) { 11606 Slog.i(TAG, "Checking replace of preferred:"); 11607 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11608 if (!cur.mPref.mAlways) { 11609 Slog.i(TAG, " -- CUR; not mAlways!"); 11610 } else { 11611 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11612 Slog.i(TAG, " -- CUR: mSet=" 11613 + Arrays.toString(cur.mPref.mSetComponents)); 11614 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11615 Slog.i(TAG, " -- NEW: mMatch=" 11616 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11617 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11618 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11619 } 11620 } 11621 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11622 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11623 && cur.mPref.sameSet(set)) { 11624 // Setting the preferred activity to what it happens to be already 11625 if (DEBUG_PREFERRED) { 11626 Slog.i(TAG, "Replacing with same preferred activity " 11627 + cur.mPref.mShortComponent + " for user " 11628 + userId + ":"); 11629 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11630 } 11631 return; 11632 } 11633 } 11634 11635 if (existing != null) { 11636 if (DEBUG_PREFERRED) { 11637 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11638 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11639 } 11640 for (int i = 0; i < existing.size(); i++) { 11641 PreferredActivity pa = existing.get(i); 11642 if (DEBUG_PREFERRED) { 11643 Slog.i(TAG, "Removing existing preferred activity " 11644 + pa.mPref.mComponent + ":"); 11645 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11646 } 11647 pir.removeFilter(pa); 11648 } 11649 } 11650 } 11651 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11652 "Replacing preferred"); 11653 } 11654 } 11655 11656 @Override 11657 public void clearPackagePreferredActivities(String packageName) { 11658 final int uid = Binder.getCallingUid(); 11659 // writer 11660 synchronized (mPackages) { 11661 PackageParser.Package pkg = mPackages.get(packageName); 11662 if (pkg == null || pkg.applicationInfo.uid != uid) { 11663 if (mContext.checkCallingOrSelfPermission( 11664 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11665 != PackageManager.PERMISSION_GRANTED) { 11666 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11667 < Build.VERSION_CODES.FROYO) { 11668 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11669 + Binder.getCallingUid()); 11670 return; 11671 } 11672 mContext.enforceCallingOrSelfPermission( 11673 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11674 } 11675 } 11676 11677 int user = UserHandle.getCallingUserId(); 11678 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11679 mSettings.writePackageRestrictionsLPr(user); 11680 scheduleWriteSettingsLocked(); 11681 } 11682 } 11683 } 11684 11685 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11686 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11687 ArrayList<PreferredActivity> removed = null; 11688 boolean changed = false; 11689 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11690 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11691 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11692 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11693 continue; 11694 } 11695 Iterator<PreferredActivity> it = pir.filterIterator(); 11696 while (it.hasNext()) { 11697 PreferredActivity pa = it.next(); 11698 // Mark entry for removal only if it matches the package name 11699 // and the entry is of type "always". 11700 if (packageName == null || 11701 (pa.mPref.mComponent.getPackageName().equals(packageName) 11702 && pa.mPref.mAlways)) { 11703 if (removed == null) { 11704 removed = new ArrayList<PreferredActivity>(); 11705 } 11706 removed.add(pa); 11707 } 11708 } 11709 if (removed != null) { 11710 for (int j=0; j<removed.size(); j++) { 11711 PreferredActivity pa = removed.get(j); 11712 pir.removeFilter(pa); 11713 } 11714 changed = true; 11715 } 11716 } 11717 return changed; 11718 } 11719 11720 @Override 11721 public void resetPreferredActivities(int userId) { 11722 /* TODO: Actually use userId. Why is it being passed in? */ 11723 mContext.enforceCallingOrSelfPermission( 11724 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11725 // writer 11726 synchronized (mPackages) { 11727 int user = UserHandle.getCallingUserId(); 11728 clearPackagePreferredActivitiesLPw(null, user); 11729 mSettings.readDefaultPreferredAppsLPw(this, user); 11730 mSettings.writePackageRestrictionsLPr(user); 11731 scheduleWriteSettingsLocked(); 11732 } 11733 } 11734 11735 @Override 11736 public int getPreferredActivities(List<IntentFilter> outFilters, 11737 List<ComponentName> outActivities, String packageName) { 11738 11739 int num = 0; 11740 final int userId = UserHandle.getCallingUserId(); 11741 // reader 11742 synchronized (mPackages) { 11743 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11744 if (pir != null) { 11745 final Iterator<PreferredActivity> it = pir.filterIterator(); 11746 while (it.hasNext()) { 11747 final PreferredActivity pa = it.next(); 11748 if (packageName == null 11749 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11750 && pa.mPref.mAlways)) { 11751 if (outFilters != null) { 11752 outFilters.add(new IntentFilter(pa)); 11753 } 11754 if (outActivities != null) { 11755 outActivities.add(pa.mPref.mComponent); 11756 } 11757 } 11758 } 11759 } 11760 } 11761 11762 return num; 11763 } 11764 11765 @Override 11766 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11767 int userId) { 11768 int callingUid = Binder.getCallingUid(); 11769 if (callingUid != Process.SYSTEM_UID) { 11770 throw new SecurityException( 11771 "addPersistentPreferredActivity can only be run by the system"); 11772 } 11773 if (filter.countActions() == 0) { 11774 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11775 return; 11776 } 11777 synchronized (mPackages) { 11778 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11779 " :"); 11780 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11781 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11782 new PersistentPreferredActivity(filter, activity)); 11783 mSettings.writePackageRestrictionsLPr(userId); 11784 } 11785 } 11786 11787 @Override 11788 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11789 int callingUid = Binder.getCallingUid(); 11790 if (callingUid != Process.SYSTEM_UID) { 11791 throw new SecurityException( 11792 "clearPackagePersistentPreferredActivities can only be run by the system"); 11793 } 11794 ArrayList<PersistentPreferredActivity> removed = null; 11795 boolean changed = false; 11796 synchronized (mPackages) { 11797 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11798 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11799 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11800 .valueAt(i); 11801 if (userId != thisUserId) { 11802 continue; 11803 } 11804 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11805 while (it.hasNext()) { 11806 PersistentPreferredActivity ppa = it.next(); 11807 // Mark entry for removal only if it matches the package name. 11808 if (ppa.mComponent.getPackageName().equals(packageName)) { 11809 if (removed == null) { 11810 removed = new ArrayList<PersistentPreferredActivity>(); 11811 } 11812 removed.add(ppa); 11813 } 11814 } 11815 if (removed != null) { 11816 for (int j=0; j<removed.size(); j++) { 11817 PersistentPreferredActivity ppa = removed.get(j); 11818 ppir.removeFilter(ppa); 11819 } 11820 changed = true; 11821 } 11822 } 11823 11824 if (changed) { 11825 mSettings.writePackageRestrictionsLPr(userId); 11826 } 11827 } 11828 } 11829 11830 @Override 11831 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11832 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11833 mContext.enforceCallingOrSelfPermission( 11834 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11835 int callingUid = Binder.getCallingUid(); 11836 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11837 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11838 if (intentFilter.countActions() == 0) { 11839 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11840 return; 11841 } 11842 synchronized (mPackages) { 11843 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11844 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11845 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11846 mSettings.writePackageRestrictionsLPr(sourceUserId); 11847 } 11848 } 11849 11850 @Override 11851 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11852 int ownerUserId) { 11853 mContext.enforceCallingOrSelfPermission( 11854 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11855 int callingUid = Binder.getCallingUid(); 11856 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11857 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11858 int callingUserId = UserHandle.getUserId(callingUid); 11859 synchronized (mPackages) { 11860 CrossProfileIntentResolver resolver = 11861 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11862 HashSet<CrossProfileIntentFilter> set = 11863 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11864 for (CrossProfileIntentFilter filter : set) { 11865 if (filter.getOwnerPackage().equals(ownerPackage) 11866 && filter.getOwnerUserId() == callingUserId) { 11867 resolver.removeFilter(filter); 11868 } 11869 } 11870 mSettings.writePackageRestrictionsLPr(sourceUserId); 11871 } 11872 } 11873 11874 // Enforcing that callingUid is owning pkg on userId 11875 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11876 // The system owns everything. 11877 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11878 return; 11879 } 11880 int callingUserId = UserHandle.getUserId(callingUid); 11881 if (callingUserId != userId) { 11882 throw new SecurityException("calling uid " + callingUid 11883 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11884 + callingUserId); 11885 } 11886 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11887 if (pi == null) { 11888 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11889 + callingUserId); 11890 } 11891 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11892 throw new SecurityException("Calling uid " + callingUid 11893 + " does not own package " + pkg); 11894 } 11895 } 11896 11897 @Override 11898 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11899 Intent intent = new Intent(Intent.ACTION_MAIN); 11900 intent.addCategory(Intent.CATEGORY_HOME); 11901 11902 final int callingUserId = UserHandle.getCallingUserId(); 11903 List<ResolveInfo> list = queryIntentActivities(intent, null, 11904 PackageManager.GET_META_DATA, callingUserId); 11905 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11906 true, false, false, callingUserId); 11907 11908 allHomeCandidates.clear(); 11909 if (list != null) { 11910 for (ResolveInfo ri : list) { 11911 allHomeCandidates.add(ri); 11912 } 11913 } 11914 return (preferred == null || preferred.activityInfo == null) 11915 ? null 11916 : new ComponentName(preferred.activityInfo.packageName, 11917 preferred.activityInfo.name); 11918 } 11919 11920 @Override 11921 public void setApplicationEnabledSetting(String appPackageName, 11922 int newState, int flags, int userId, String callingPackage) { 11923 if (!sUserManager.exists(userId)) return; 11924 if (callingPackage == null) { 11925 callingPackage = Integer.toString(Binder.getCallingUid()); 11926 } 11927 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11928 } 11929 11930 @Override 11931 public void setComponentEnabledSetting(ComponentName componentName, 11932 int newState, int flags, int userId) { 11933 if (!sUserManager.exists(userId)) return; 11934 setEnabledSetting(componentName.getPackageName(), 11935 componentName.getClassName(), newState, flags, userId, null); 11936 } 11937 11938 private void setEnabledSetting(final String packageName, String className, int newState, 11939 final int flags, int userId, String callingPackage) { 11940 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11941 || newState == COMPONENT_ENABLED_STATE_ENABLED 11942 || newState == COMPONENT_ENABLED_STATE_DISABLED 11943 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11944 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11945 throw new IllegalArgumentException("Invalid new component state: " 11946 + newState); 11947 } 11948 PackageSetting pkgSetting; 11949 final int uid = Binder.getCallingUid(); 11950 final int permission = mContext.checkCallingOrSelfPermission( 11951 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11952 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 11953 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11954 boolean sendNow = false; 11955 boolean isApp = (className == null); 11956 String componentName = isApp ? packageName : className; 11957 int packageUid = -1; 11958 ArrayList<String> components; 11959 11960 // writer 11961 synchronized (mPackages) { 11962 pkgSetting = mSettings.mPackages.get(packageName); 11963 if (pkgSetting == null) { 11964 if (className == null) { 11965 throw new IllegalArgumentException( 11966 "Unknown package: " + packageName); 11967 } 11968 throw new IllegalArgumentException( 11969 "Unknown component: " + packageName 11970 + "/" + className); 11971 } 11972 // Allow root and verify that userId is not being specified by a different user 11973 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11974 throw new SecurityException( 11975 "Permission Denial: attempt to change component state from pid=" 11976 + Binder.getCallingPid() 11977 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11978 } 11979 if (className == null) { 11980 // We're dealing with an application/package level state change 11981 if (pkgSetting.getEnabled(userId) == newState) { 11982 // Nothing to do 11983 return; 11984 } 11985 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11986 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11987 // Don't care about who enables an app. 11988 callingPackage = null; 11989 } 11990 pkgSetting.setEnabled(newState, userId, callingPackage); 11991 // pkgSetting.pkg.mSetEnabled = newState; 11992 } else { 11993 // We're dealing with a component level state change 11994 // First, verify that this is a valid class name. 11995 PackageParser.Package pkg = pkgSetting.pkg; 11996 if (pkg == null || !pkg.hasComponentClassName(className)) { 11997 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11998 throw new IllegalArgumentException("Component class " + className 11999 + " does not exist in " + packageName); 12000 } else { 12001 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 12002 + className + " does not exist in " + packageName); 12003 } 12004 } 12005 switch (newState) { 12006 case COMPONENT_ENABLED_STATE_ENABLED: 12007 if (!pkgSetting.enableComponentLPw(className, userId)) { 12008 return; 12009 } 12010 break; 12011 case COMPONENT_ENABLED_STATE_DISABLED: 12012 if (!pkgSetting.disableComponentLPw(className, userId)) { 12013 return; 12014 } 12015 break; 12016 case COMPONENT_ENABLED_STATE_DEFAULT: 12017 if (!pkgSetting.restoreComponentLPw(className, userId)) { 12018 return; 12019 } 12020 break; 12021 default: 12022 Slog.e(TAG, "Invalid new component state: " + newState); 12023 return; 12024 } 12025 } 12026 mSettings.writePackageRestrictionsLPr(userId); 12027 components = mPendingBroadcasts.get(userId, packageName); 12028 final boolean newPackage = components == null; 12029 if (newPackage) { 12030 components = new ArrayList<String>(); 12031 } 12032 if (!components.contains(componentName)) { 12033 components.add(componentName); 12034 } 12035 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 12036 sendNow = true; 12037 // Purge entry from pending broadcast list if another one exists already 12038 // since we are sending one right away. 12039 mPendingBroadcasts.remove(userId, packageName); 12040 } else { 12041 if (newPackage) { 12042 mPendingBroadcasts.put(userId, packageName, components); 12043 } 12044 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12045 // Schedule a message 12046 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12047 } 12048 } 12049 } 12050 12051 long callingId = Binder.clearCallingIdentity(); 12052 try { 12053 if (sendNow) { 12054 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12055 sendPackageChangedBroadcast(packageName, 12056 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12057 } 12058 } finally { 12059 Binder.restoreCallingIdentity(callingId); 12060 } 12061 } 12062 12063 private void sendPackageChangedBroadcast(String packageName, 12064 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12065 if (DEBUG_INSTALL) 12066 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12067 + componentNames); 12068 Bundle extras = new Bundle(4); 12069 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12070 String nameList[] = new String[componentNames.size()]; 12071 componentNames.toArray(nameList); 12072 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12073 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12074 extras.putInt(Intent.EXTRA_UID, packageUid); 12075 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12076 new int[] {UserHandle.getUserId(packageUid)}); 12077 } 12078 12079 @Override 12080 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12081 if (!sUserManager.exists(userId)) return; 12082 final int uid = Binder.getCallingUid(); 12083 final int permission = mContext.checkCallingOrSelfPermission( 12084 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12085 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12086 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 12087 // writer 12088 synchronized (mPackages) { 12089 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12090 uid, userId)) { 12091 scheduleWritePackageRestrictionsLocked(userId); 12092 } 12093 } 12094 } 12095 12096 @Override 12097 public String getInstallerPackageName(String packageName) { 12098 // reader 12099 synchronized (mPackages) { 12100 return mSettings.getInstallerPackageNameLPr(packageName); 12101 } 12102 } 12103 12104 @Override 12105 public int getApplicationEnabledSetting(String packageName, int userId) { 12106 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12107 int uid = Binder.getCallingUid(); 12108 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 12109 // reader 12110 synchronized (mPackages) { 12111 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12112 } 12113 } 12114 12115 @Override 12116 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12117 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12118 int uid = Binder.getCallingUid(); 12119 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 12120 // reader 12121 synchronized (mPackages) { 12122 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12123 } 12124 } 12125 12126 @Override 12127 public void enterSafeMode() { 12128 enforceSystemOrRoot("Only the system can request entering safe mode"); 12129 12130 if (!mSystemReady) { 12131 mSafeMode = true; 12132 } 12133 } 12134 12135 @Override 12136 public void systemReady() { 12137 mSystemReady = true; 12138 12139 // Read the compatibilty setting when the system is ready. 12140 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12141 mContext.getContentResolver(), 12142 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12143 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12144 if (DEBUG_SETTINGS) { 12145 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12146 } 12147 12148 synchronized (mPackages) { 12149 // Verify that all of the preferred activity components actually 12150 // exist. It is possible for applications to be updated and at 12151 // that point remove a previously declared activity component that 12152 // had been set as a preferred activity. We try to clean this up 12153 // the next time we encounter that preferred activity, but it is 12154 // possible for the user flow to never be able to return to that 12155 // situation so here we do a sanity check to make sure we haven't 12156 // left any junk around. 12157 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12158 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12159 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12160 removed.clear(); 12161 for (PreferredActivity pa : pir.filterSet()) { 12162 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12163 removed.add(pa); 12164 } 12165 } 12166 if (removed.size() > 0) { 12167 for (int r=0; r<removed.size(); r++) { 12168 PreferredActivity pa = removed.get(r); 12169 Slog.w(TAG, "Removing dangling preferred activity: " 12170 + pa.mPref.mComponent); 12171 pir.removeFilter(pa); 12172 } 12173 mSettings.writePackageRestrictionsLPr( 12174 mSettings.mPreferredActivities.keyAt(i)); 12175 } 12176 } 12177 } 12178 sUserManager.systemReady(); 12179 12180 // Kick off any messages waiting for system ready 12181 if (mPostSystemReadyMessages != null) { 12182 for (Message msg : mPostSystemReadyMessages) { 12183 msg.sendToTarget(); 12184 } 12185 mPostSystemReadyMessages = null; 12186 } 12187 } 12188 12189 @Override 12190 public boolean isSafeMode() { 12191 return mSafeMode; 12192 } 12193 12194 @Override 12195 public boolean hasSystemUidErrors() { 12196 return mHasSystemUidErrors; 12197 } 12198 12199 static String arrayToString(int[] array) { 12200 StringBuffer buf = new StringBuffer(128); 12201 buf.append('['); 12202 if (array != null) { 12203 for (int i=0; i<array.length; i++) { 12204 if (i > 0) buf.append(", "); 12205 buf.append(array[i]); 12206 } 12207 } 12208 buf.append(']'); 12209 return buf.toString(); 12210 } 12211 12212 static class DumpState { 12213 public static final int DUMP_LIBS = 1 << 0; 12214 public static final int DUMP_FEATURES = 1 << 1; 12215 public static final int DUMP_RESOLVERS = 1 << 2; 12216 public static final int DUMP_PERMISSIONS = 1 << 3; 12217 public static final int DUMP_PACKAGES = 1 << 4; 12218 public static final int DUMP_SHARED_USERS = 1 << 5; 12219 public static final int DUMP_MESSAGES = 1 << 6; 12220 public static final int DUMP_PROVIDERS = 1 << 7; 12221 public static final int DUMP_VERIFIERS = 1 << 8; 12222 public static final int DUMP_PREFERRED = 1 << 9; 12223 public static final int DUMP_PREFERRED_XML = 1 << 10; 12224 public static final int DUMP_KEYSETS = 1 << 11; 12225 public static final int DUMP_VERSION = 1 << 12; 12226 public static final int DUMP_INSTALLS = 1 << 13; 12227 12228 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12229 12230 private int mTypes; 12231 12232 private int mOptions; 12233 12234 private boolean mTitlePrinted; 12235 12236 private SharedUserSetting mSharedUser; 12237 12238 public boolean isDumping(int type) { 12239 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12240 return true; 12241 } 12242 12243 return (mTypes & type) != 0; 12244 } 12245 12246 public void setDump(int type) { 12247 mTypes |= type; 12248 } 12249 12250 public boolean isOptionEnabled(int option) { 12251 return (mOptions & option) != 0; 12252 } 12253 12254 public void setOptionEnabled(int option) { 12255 mOptions |= option; 12256 } 12257 12258 public boolean onTitlePrinted() { 12259 final boolean printed = mTitlePrinted; 12260 mTitlePrinted = true; 12261 return printed; 12262 } 12263 12264 public boolean getTitlePrinted() { 12265 return mTitlePrinted; 12266 } 12267 12268 public void setTitlePrinted(boolean enabled) { 12269 mTitlePrinted = enabled; 12270 } 12271 12272 public SharedUserSetting getSharedUser() { 12273 return mSharedUser; 12274 } 12275 12276 public void setSharedUser(SharedUserSetting user) { 12277 mSharedUser = user; 12278 } 12279 } 12280 12281 @Override 12282 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12283 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12284 != PackageManager.PERMISSION_GRANTED) { 12285 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12286 + Binder.getCallingPid() 12287 + ", uid=" + Binder.getCallingUid() 12288 + " without permission " 12289 + android.Manifest.permission.DUMP); 12290 return; 12291 } 12292 12293 DumpState dumpState = new DumpState(); 12294 boolean fullPreferred = false; 12295 boolean checkin = false; 12296 12297 String packageName = null; 12298 12299 int opti = 0; 12300 while (opti < args.length) { 12301 String opt = args[opti]; 12302 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12303 break; 12304 } 12305 opti++; 12306 12307 if ("-a".equals(opt)) { 12308 // Right now we only know how to print all. 12309 } else if ("-h".equals(opt)) { 12310 pw.println("Package manager dump options:"); 12311 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12312 pw.println(" --checkin: dump for a checkin"); 12313 pw.println(" -f: print details of intent filters"); 12314 pw.println(" -h: print this help"); 12315 pw.println(" cmd may be one of:"); 12316 pw.println(" l[ibraries]: list known shared libraries"); 12317 pw.println(" f[ibraries]: list device features"); 12318 pw.println(" k[eysets]: print known keysets"); 12319 pw.println(" r[esolvers]: dump intent resolvers"); 12320 pw.println(" perm[issions]: dump permissions"); 12321 pw.println(" pref[erred]: print preferred package settings"); 12322 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12323 pw.println(" prov[iders]: dump content providers"); 12324 pw.println(" p[ackages]: dump installed packages"); 12325 pw.println(" s[hared-users]: dump shared user IDs"); 12326 pw.println(" m[essages]: print collected runtime messages"); 12327 pw.println(" v[erifiers]: print package verifier info"); 12328 pw.println(" version: print database version info"); 12329 pw.println(" write: write current settings now"); 12330 pw.println(" <package.name>: info about given package"); 12331 pw.println(" installs: details about install sessions"); 12332 return; 12333 } else if ("--checkin".equals(opt)) { 12334 checkin = true; 12335 } else if ("-f".equals(opt)) { 12336 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12337 } else { 12338 pw.println("Unknown argument: " + opt + "; use -h for help"); 12339 } 12340 } 12341 12342 // Is the caller requesting to dump a particular piece of data? 12343 if (opti < args.length) { 12344 String cmd = args[opti]; 12345 opti++; 12346 // Is this a package name? 12347 if ("android".equals(cmd) || cmd.contains(".")) { 12348 packageName = cmd; 12349 // When dumping a single package, we always dump all of its 12350 // filter information since the amount of data will be reasonable. 12351 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12352 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12353 dumpState.setDump(DumpState.DUMP_LIBS); 12354 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12355 dumpState.setDump(DumpState.DUMP_FEATURES); 12356 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12357 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12358 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12359 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12360 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12361 dumpState.setDump(DumpState.DUMP_PREFERRED); 12362 } else if ("preferred-xml".equals(cmd)) { 12363 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12364 if (opti < args.length && "--full".equals(args[opti])) { 12365 fullPreferred = true; 12366 opti++; 12367 } 12368 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12369 dumpState.setDump(DumpState.DUMP_PACKAGES); 12370 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12371 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12372 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12373 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12374 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12375 dumpState.setDump(DumpState.DUMP_MESSAGES); 12376 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12377 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12378 } else if ("version".equals(cmd)) { 12379 dumpState.setDump(DumpState.DUMP_VERSION); 12380 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12381 dumpState.setDump(DumpState.DUMP_KEYSETS); 12382 } else if ("installs".equals(cmd)) { 12383 dumpState.setDump(DumpState.DUMP_INSTALLS); 12384 } else if ("write".equals(cmd)) { 12385 synchronized (mPackages) { 12386 mSettings.writeLPr(); 12387 pw.println("Settings written."); 12388 return; 12389 } 12390 } 12391 } 12392 12393 if (checkin) { 12394 pw.println("vers,1"); 12395 } 12396 12397 // reader 12398 synchronized (mPackages) { 12399 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12400 if (!checkin) { 12401 if (dumpState.onTitlePrinted()) 12402 pw.println(); 12403 pw.println("Database versions:"); 12404 pw.print(" SDK Version:"); 12405 pw.print(" internal="); 12406 pw.print(mSettings.mInternalSdkPlatform); 12407 pw.print(" external="); 12408 pw.println(mSettings.mExternalSdkPlatform); 12409 pw.print(" DB Version:"); 12410 pw.print(" internal="); 12411 pw.print(mSettings.mInternalDatabaseVersion); 12412 pw.print(" external="); 12413 pw.println(mSettings.mExternalDatabaseVersion); 12414 } 12415 } 12416 12417 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12418 if (!checkin) { 12419 if (dumpState.onTitlePrinted()) 12420 pw.println(); 12421 pw.println("Verifiers:"); 12422 pw.print(" Required: "); 12423 pw.print(mRequiredVerifierPackage); 12424 pw.print(" (uid="); 12425 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12426 pw.println(")"); 12427 } else if (mRequiredVerifierPackage != null) { 12428 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12429 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12430 } 12431 } 12432 12433 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12434 boolean printedHeader = false; 12435 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12436 while (it.hasNext()) { 12437 String name = it.next(); 12438 SharedLibraryEntry ent = mSharedLibraries.get(name); 12439 if (!checkin) { 12440 if (!printedHeader) { 12441 if (dumpState.onTitlePrinted()) 12442 pw.println(); 12443 pw.println("Libraries:"); 12444 printedHeader = true; 12445 } 12446 pw.print(" "); 12447 } else { 12448 pw.print("lib,"); 12449 } 12450 pw.print(name); 12451 if (!checkin) { 12452 pw.print(" -> "); 12453 } 12454 if (ent.path != null) { 12455 if (!checkin) { 12456 pw.print("(jar) "); 12457 pw.print(ent.path); 12458 } else { 12459 pw.print(",jar,"); 12460 pw.print(ent.path); 12461 } 12462 } else { 12463 if (!checkin) { 12464 pw.print("(apk) "); 12465 pw.print(ent.apk); 12466 } else { 12467 pw.print(",apk,"); 12468 pw.print(ent.apk); 12469 } 12470 } 12471 pw.println(); 12472 } 12473 } 12474 12475 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12476 if (dumpState.onTitlePrinted()) 12477 pw.println(); 12478 if (!checkin) { 12479 pw.println("Features:"); 12480 } 12481 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12482 while (it.hasNext()) { 12483 String name = it.next(); 12484 if (!checkin) { 12485 pw.print(" "); 12486 } else { 12487 pw.print("feat,"); 12488 } 12489 pw.println(name); 12490 } 12491 } 12492 12493 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12494 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12495 : "Activity Resolver Table:", " ", packageName, 12496 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12497 dumpState.setTitlePrinted(true); 12498 } 12499 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12500 : "Receiver Resolver Table:", " ", packageName, 12501 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12502 dumpState.setTitlePrinted(true); 12503 } 12504 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12505 : "Service Resolver Table:", " ", packageName, 12506 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12507 dumpState.setTitlePrinted(true); 12508 } 12509 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12510 : "Provider Resolver Table:", " ", packageName, 12511 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12512 dumpState.setTitlePrinted(true); 12513 } 12514 } 12515 12516 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12517 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12518 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12519 int user = mSettings.mPreferredActivities.keyAt(i); 12520 if (pir.dump(pw, 12521 dumpState.getTitlePrinted() 12522 ? "\nPreferred Activities User " + user + ":" 12523 : "Preferred Activities User " + user + ":", " ", 12524 packageName, true)) { 12525 dumpState.setTitlePrinted(true); 12526 } 12527 } 12528 } 12529 12530 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12531 pw.flush(); 12532 FileOutputStream fout = new FileOutputStream(fd); 12533 BufferedOutputStream str = new BufferedOutputStream(fout); 12534 XmlSerializer serializer = new FastXmlSerializer(); 12535 try { 12536 serializer.setOutput(str, "utf-8"); 12537 serializer.startDocument(null, true); 12538 serializer.setFeature( 12539 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12540 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12541 serializer.endDocument(); 12542 serializer.flush(); 12543 } catch (IllegalArgumentException e) { 12544 pw.println("Failed writing: " + e); 12545 } catch (IllegalStateException e) { 12546 pw.println("Failed writing: " + e); 12547 } catch (IOException e) { 12548 pw.println("Failed writing: " + e); 12549 } 12550 } 12551 12552 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12553 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12554 if (packageName == null) { 12555 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12556 if (iperm == 0) { 12557 if (dumpState.onTitlePrinted()) 12558 pw.println(); 12559 pw.println("AppOp Permissions:"); 12560 } 12561 pw.print(" AppOp Permission "); 12562 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12563 pw.println(":"); 12564 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12565 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12566 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12567 } 12568 } 12569 } 12570 } 12571 12572 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12573 boolean printedSomething = false; 12574 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12575 if (packageName != null && !packageName.equals(p.info.packageName)) { 12576 continue; 12577 } 12578 if (!printedSomething) { 12579 if (dumpState.onTitlePrinted()) 12580 pw.println(); 12581 pw.println("Registered ContentProviders:"); 12582 printedSomething = true; 12583 } 12584 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12585 pw.print(" "); pw.println(p.toString()); 12586 } 12587 printedSomething = false; 12588 for (Map.Entry<String, PackageParser.Provider> entry : 12589 mProvidersByAuthority.entrySet()) { 12590 PackageParser.Provider p = entry.getValue(); 12591 if (packageName != null && !packageName.equals(p.info.packageName)) { 12592 continue; 12593 } 12594 if (!printedSomething) { 12595 if (dumpState.onTitlePrinted()) 12596 pw.println(); 12597 pw.println("ContentProvider Authorities:"); 12598 printedSomething = true; 12599 } 12600 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12601 pw.print(" "); pw.println(p.toString()); 12602 if (p.info != null && p.info.applicationInfo != null) { 12603 final String appInfo = p.info.applicationInfo.toString(); 12604 pw.print(" applicationInfo="); pw.println(appInfo); 12605 } 12606 } 12607 } 12608 12609 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12610 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12611 } 12612 12613 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12614 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12615 } 12616 12617 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12618 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12619 } 12620 12621 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 12622 // XXX should handle packageName != null by dumping only install data that 12623 // the given package is involved with. 12624 if (dumpState.onTitlePrinted()) pw.println(); 12625 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12626 } 12627 12628 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12629 if (dumpState.onTitlePrinted()) pw.println(); 12630 mSettings.dumpReadMessagesLPr(pw, dumpState); 12631 12632 pw.println(); 12633 pw.println("Package warning messages:"); 12634 final File fname = getSettingsProblemFile(); 12635 FileInputStream in = null; 12636 try { 12637 in = new FileInputStream(fname); 12638 final int avail = in.available(); 12639 final byte[] data = new byte[avail]; 12640 in.read(data); 12641 pw.print(new String(data)); 12642 } catch (FileNotFoundException e) { 12643 } catch (IOException e) { 12644 } finally { 12645 if (in != null) { 12646 try { 12647 in.close(); 12648 } catch (IOException e) { 12649 } 12650 } 12651 } 12652 } 12653 12654 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 12655 BufferedReader in = null; 12656 String line = null; 12657 try { 12658 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12659 while ((line = in.readLine()) != null) { 12660 pw.print("msg,"); 12661 pw.println(line); 12662 } 12663 } catch (IOException ignored) { 12664 } finally { 12665 IoUtils.closeQuietly(in); 12666 } 12667 } 12668 } 12669 } 12670 12671 // ------- apps on sdcard specific code ------- 12672 static final boolean DEBUG_SD_INSTALL = false; 12673 12674 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12675 12676 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12677 12678 private boolean mMediaMounted = false; 12679 12680 static String getEncryptKey() { 12681 try { 12682 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12683 SD_ENCRYPTION_KEYSTORE_NAME); 12684 if (sdEncKey == null) { 12685 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12686 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12687 if (sdEncKey == null) { 12688 Slog.e(TAG, "Failed to create encryption keys"); 12689 return null; 12690 } 12691 } 12692 return sdEncKey; 12693 } catch (NoSuchAlgorithmException nsae) { 12694 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12695 return null; 12696 } catch (IOException ioe) { 12697 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12698 return null; 12699 } 12700 } 12701 12702 /* 12703 * Update media status on PackageManager. 12704 */ 12705 @Override 12706 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12707 int callingUid = Binder.getCallingUid(); 12708 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12709 throw new SecurityException("Media status can only be updated by the system"); 12710 } 12711 // reader; this apparently protects mMediaMounted, but should probably 12712 // be a different lock in that case. 12713 synchronized (mPackages) { 12714 Log.i(TAG, "Updating external media status from " 12715 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12716 + (mediaStatus ? "mounted" : "unmounted")); 12717 if (DEBUG_SD_INSTALL) 12718 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12719 + ", mMediaMounted=" + mMediaMounted); 12720 if (mediaStatus == mMediaMounted) { 12721 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12722 : 0, -1); 12723 mHandler.sendMessage(msg); 12724 return; 12725 } 12726 mMediaMounted = mediaStatus; 12727 } 12728 // Queue up an async operation since the package installation may take a 12729 // little while. 12730 mHandler.post(new Runnable() { 12731 public void run() { 12732 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12733 } 12734 }); 12735 } 12736 12737 /** 12738 * Called by MountService when the initial ASECs to scan are available. 12739 * Should block until all the ASEC containers are finished being scanned. 12740 */ 12741 public void scanAvailableAsecs() { 12742 updateExternalMediaStatusInner(true, false, false); 12743 if (mShouldRestoreconData) { 12744 SELinuxMMAC.setRestoreconDone(); 12745 mShouldRestoreconData = false; 12746 } 12747 } 12748 12749 /* 12750 * Collect information of applications on external media, map them against 12751 * existing containers and update information based on current mount status. 12752 * Please note that we always have to report status if reportStatus has been 12753 * set to true especially when unloading packages. 12754 */ 12755 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12756 boolean externalStorage) { 12757 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12758 int[] uidArr = EmptyArray.INT; 12759 12760 final String[] list = PackageHelper.getSecureContainerList(); 12761 if (ArrayUtils.isEmpty(list)) { 12762 Log.i(TAG, "No secure containers found"); 12763 } else { 12764 // Process list of secure containers and categorize them 12765 // as active or stale based on their package internal state. 12766 12767 // reader 12768 synchronized (mPackages) { 12769 for (String cid : list) { 12770 // Leave stages untouched for now; installer service owns them 12771 if (PackageInstallerService.isStageName(cid)) continue; 12772 12773 if (DEBUG_SD_INSTALL) 12774 Log.i(TAG, "Processing container " + cid); 12775 String pkgName = getAsecPackageName(cid); 12776 if (pkgName == null) { 12777 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12778 continue; 12779 } 12780 if (DEBUG_SD_INSTALL) 12781 Log.i(TAG, "Looking for pkg : " + pkgName); 12782 12783 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12784 if (ps == null) { 12785 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12786 continue; 12787 } 12788 12789 /* 12790 * Skip packages that are not external if we're unmounting 12791 * external storage. 12792 */ 12793 if (externalStorage && !isMounted && !isExternal(ps)) { 12794 continue; 12795 } 12796 12797 final AsecInstallArgs args = new AsecInstallArgs(cid, 12798 getAppDexInstructionSets(ps), isForwardLocked(ps)); 12799 // The package status is changed only if the code path 12800 // matches between settings and the container id. 12801 if (ps.codePathString != null 12802 && ps.codePathString.startsWith(args.getCodePath())) { 12803 if (DEBUG_SD_INSTALL) { 12804 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12805 + " at code path: " + ps.codePathString); 12806 } 12807 12808 // We do have a valid package installed on sdcard 12809 processCids.put(args, ps.codePathString); 12810 final int uid = ps.appId; 12811 if (uid != -1) { 12812 uidArr = ArrayUtils.appendInt(uidArr, uid); 12813 } 12814 } else { 12815 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12816 + ps.codePathString); 12817 } 12818 } 12819 } 12820 12821 Arrays.sort(uidArr); 12822 } 12823 12824 // Process packages with valid entries. 12825 if (isMounted) { 12826 if (DEBUG_SD_INSTALL) 12827 Log.i(TAG, "Loading packages"); 12828 loadMediaPackages(processCids, uidArr); 12829 startCleaningPackages(); 12830 mInstallerService.onSecureContainersAvailable(); 12831 } else { 12832 if (DEBUG_SD_INSTALL) 12833 Log.i(TAG, "Unloading packages"); 12834 unloadMediaPackages(processCids, uidArr, reportStatus); 12835 } 12836 } 12837 12838 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12839 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12840 int size = pkgList.size(); 12841 if (size > 0) { 12842 // Send broadcasts here 12843 Bundle extras = new Bundle(); 12844 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12845 .toArray(new String[size])); 12846 if (uidArr != null) { 12847 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12848 } 12849 if (replacing) { 12850 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12851 } 12852 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12853 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12854 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12855 } 12856 } 12857 12858 /* 12859 * Look at potentially valid container ids from processCids If package 12860 * information doesn't match the one on record or package scanning fails, 12861 * the cid is added to list of removeCids. We currently don't delete stale 12862 * containers. 12863 */ 12864 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12865 ArrayList<String> pkgList = new ArrayList<String>(); 12866 Set<AsecInstallArgs> keys = processCids.keySet(); 12867 12868 for (AsecInstallArgs args : keys) { 12869 String codePath = processCids.get(args); 12870 if (DEBUG_SD_INSTALL) 12871 Log.i(TAG, "Loading container : " + args.cid); 12872 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12873 try { 12874 // Make sure there are no container errors first. 12875 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12876 Slog.e(TAG, "Failed to mount cid : " + args.cid 12877 + " when installing from sdcard"); 12878 continue; 12879 } 12880 // Check code path here. 12881 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12882 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12883 + " does not match one in settings " + codePath); 12884 continue; 12885 } 12886 // Parse package 12887 int parseFlags = mDefParseFlags; 12888 if (args.isExternal()) { 12889 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12890 } 12891 if (args.isFwdLocked()) { 12892 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12893 } 12894 12895 synchronized (mInstallLock) { 12896 PackageParser.Package pkg = null; 12897 try { 12898 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12899 } catch (PackageManagerException e) { 12900 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12901 } 12902 // Scan the package 12903 if (pkg != null) { 12904 /* 12905 * TODO why is the lock being held? doPostInstall is 12906 * called in other places without the lock. This needs 12907 * to be straightened out. 12908 */ 12909 // writer 12910 synchronized (mPackages) { 12911 retCode = PackageManager.INSTALL_SUCCEEDED; 12912 pkgList.add(pkg.packageName); 12913 // Post process args 12914 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12915 pkg.applicationInfo.uid); 12916 } 12917 } else { 12918 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12919 } 12920 } 12921 12922 } finally { 12923 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12924 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12925 } 12926 } 12927 } 12928 // writer 12929 synchronized (mPackages) { 12930 // If the platform SDK has changed since the last time we booted, 12931 // we need to re-grant app permission to catch any new ones that 12932 // appear. This is really a hack, and means that apps can in some 12933 // cases get permissions that the user didn't initially explicitly 12934 // allow... it would be nice to have some better way to handle 12935 // this situation. 12936 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12937 if (regrantPermissions) 12938 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12939 + mSdkVersion + "; regranting permissions for external storage"); 12940 mSettings.mExternalSdkPlatform = mSdkVersion; 12941 12942 // Make sure group IDs have been assigned, and any permission 12943 // changes in other apps are accounted for 12944 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12945 | (regrantPermissions 12946 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12947 : 0)); 12948 12949 mSettings.updateExternalDatabaseVersion(); 12950 12951 // can downgrade to reader 12952 // Persist settings 12953 mSettings.writeLPr(); 12954 } 12955 // Send a broadcast to let everyone know we are done processing 12956 if (pkgList.size() > 0) { 12957 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12958 } 12959 } 12960 12961 /* 12962 * Utility method to unload a list of specified containers 12963 */ 12964 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12965 // Just unmount all valid containers. 12966 for (AsecInstallArgs arg : cidArgs) { 12967 synchronized (mInstallLock) { 12968 arg.doPostDeleteLI(false); 12969 } 12970 } 12971 } 12972 12973 /* 12974 * Unload packages mounted on external media. This involves deleting package 12975 * data from internal structures, sending broadcasts about diabled packages, 12976 * gc'ing to free up references, unmounting all secure containers 12977 * corresponding to packages on external media, and posting a 12978 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12979 * that we always have to post this message if status has been requested no 12980 * matter what. 12981 */ 12982 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 12983 final boolean reportStatus) { 12984 if (DEBUG_SD_INSTALL) 12985 Log.i(TAG, "unloading media packages"); 12986 ArrayList<String> pkgList = new ArrayList<String>(); 12987 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12988 final Set<AsecInstallArgs> keys = processCids.keySet(); 12989 for (AsecInstallArgs args : keys) { 12990 String pkgName = args.getPackageName(); 12991 if (DEBUG_SD_INSTALL) 12992 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12993 // Delete package internally 12994 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12995 synchronized (mInstallLock) { 12996 boolean res = deletePackageLI(pkgName, null, false, null, null, 12997 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12998 if (res) { 12999 pkgList.add(pkgName); 13000 } else { 13001 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 13002 failedList.add(args); 13003 } 13004 } 13005 } 13006 13007 // reader 13008 synchronized (mPackages) { 13009 // We didn't update the settings after removing each package; 13010 // write them now for all packages. 13011 mSettings.writeLPr(); 13012 } 13013 13014 // We have to absolutely send UPDATED_MEDIA_STATUS only 13015 // after confirming that all the receivers processed the ordered 13016 // broadcast when packages get disabled, force a gc to clean things up. 13017 // and unload all the containers. 13018 if (pkgList.size() > 0) { 13019 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 13020 new IIntentReceiver.Stub() { 13021 public void performReceive(Intent intent, int resultCode, String data, 13022 Bundle extras, boolean ordered, boolean sticky, 13023 int sendingUser) throws RemoteException { 13024 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 13025 reportStatus ? 1 : 0, 1, keys); 13026 mHandler.sendMessage(msg); 13027 } 13028 }); 13029 } else { 13030 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 13031 keys); 13032 mHandler.sendMessage(msg); 13033 } 13034 } 13035 13036 /** Binder call */ 13037 @Override 13038 public void movePackage(final String packageName, final IPackageMoveObserver observer, 13039 final int flags) { 13040 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 13041 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 13042 int returnCode = PackageManager.MOVE_SUCCEEDED; 13043 int currInstallFlags = 0; 13044 int newInstallFlags = 0; 13045 13046 File codeFile = null; 13047 String installerPackageName = null; 13048 String packageAbiOverride = null; 13049 13050 // reader 13051 synchronized (mPackages) { 13052 final PackageParser.Package pkg = mPackages.get(packageName); 13053 final PackageSetting ps = mSettings.mPackages.get(packageName); 13054 if (pkg == null || ps == null) { 13055 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13056 } else { 13057 // Disable moving fwd locked apps and system packages 13058 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 13059 Slog.w(TAG, "Cannot move system application"); 13060 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13061 } else if (pkg.mOperationPending) { 13062 Slog.w(TAG, "Attempt to move package which has pending operations"); 13063 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13064 } else { 13065 // Find install location first 13066 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13067 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13068 Slog.w(TAG, "Ambigous flags specified for move location."); 13069 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13070 } else { 13071 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13072 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13073 currInstallFlags = isExternal(pkg) 13074 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13075 13076 if (newInstallFlags == currInstallFlags) { 13077 Slog.w(TAG, "No move required. Trying to move to same location"); 13078 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13079 } else { 13080 if (isForwardLocked(pkg)) { 13081 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13082 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13083 } 13084 } 13085 } 13086 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13087 pkg.mOperationPending = true; 13088 } 13089 } 13090 13091 codeFile = new File(pkg.codePath); 13092 installerPackageName = ps.installerPackageName; 13093 packageAbiOverride = ps.cpuAbiOverrideString; 13094 } 13095 } 13096 13097 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13098 try { 13099 observer.packageMoved(packageName, returnCode); 13100 } catch (RemoteException ignored) { 13101 } 13102 return; 13103 } 13104 13105 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 13106 @Override 13107 public void onUserActionRequired(Intent intent) throws RemoteException { 13108 throw new IllegalStateException(); 13109 } 13110 13111 @Override 13112 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 13113 Bundle extras) throws RemoteException { 13114 Slog.d(TAG, "Install result for move: " 13115 + PackageManager.installStatusToString(returnCode, msg)); 13116 13117 // We usually have a new package now after the install, but if 13118 // we failed we need to clear the pending flag on the original 13119 // package object. 13120 synchronized (mPackages) { 13121 final PackageParser.Package pkg = mPackages.get(packageName); 13122 if (pkg != null) { 13123 pkg.mOperationPending = false; 13124 } 13125 } 13126 13127 final int status = PackageManager.installStatusToPublicStatus(returnCode); 13128 switch (status) { 13129 case PackageInstaller.STATUS_SUCCESS: 13130 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 13131 break; 13132 case PackageInstaller.STATUS_FAILURE_STORAGE: 13133 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 13134 break; 13135 default: 13136 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 13137 break; 13138 } 13139 } 13140 }; 13141 13142 // Treat a move like reinstalling an existing app, which ensures that we 13143 // process everythign uniformly, like unpacking native libraries. 13144 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 13145 13146 final Message msg = mHandler.obtainMessage(INIT_COPY); 13147 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 13148 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 13149 installerPackageName, null, user, packageAbiOverride); 13150 mHandler.sendMessage(msg); 13151 } 13152 13153 @Override 13154 public boolean setInstallLocation(int loc) { 13155 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13156 null); 13157 if (getInstallLocation() == loc) { 13158 return true; 13159 } 13160 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13161 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13162 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13163 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13164 return true; 13165 } 13166 return false; 13167 } 13168 13169 @Override 13170 public int getInstallLocation() { 13171 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13172 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13173 PackageHelper.APP_INSTALL_AUTO); 13174 } 13175 13176 /** Called by UserManagerService */ 13177 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 13178 mDirtyUsers.remove(userHandle); 13179 mSettings.removeUserLPw(userHandle); 13180 mPendingBroadcasts.remove(userHandle); 13181 if (mInstaller != null) { 13182 // Technically, we shouldn't be doing this with the package lock 13183 // held. However, this is very rare, and there is already so much 13184 // other disk I/O going on, that we'll let it slide for now. 13185 mInstaller.removeUserDataDirs(userHandle); 13186 } 13187 mUserNeedsBadging.delete(userHandle); 13188 removeUnusedPackagesLILPw(userManager, userHandle); 13189 } 13190 13191 /** 13192 * We're removing userHandle and would like to remove any downloaded packages 13193 * that are no longer in use by any other user. 13194 * @param userHandle the user being removed 13195 */ 13196 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 13197 final boolean DEBUG_CLEAN_APKS = false; 13198 int [] users = userManager.getUserIdsLPr(); 13199 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 13200 while (psit.hasNext()) { 13201 PackageSetting ps = psit.next(); 13202 if (ps.pkg == null) { 13203 continue; 13204 } 13205 final String packageName = ps.pkg.packageName; 13206 // Skip over if system app 13207 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13208 continue; 13209 } 13210 if (DEBUG_CLEAN_APKS) { 13211 Slog.i(TAG, "Checking package " + packageName); 13212 } 13213 boolean keep = false; 13214 for (int i = 0; i < users.length; i++) { 13215 if (users[i] != userHandle && ps.getInstalled(users[i])) { 13216 keep = true; 13217 if (DEBUG_CLEAN_APKS) { 13218 Slog.i(TAG, " Keeping package " + packageName + " for user " 13219 + users[i]); 13220 } 13221 break; 13222 } 13223 } 13224 if (!keep) { 13225 if (DEBUG_CLEAN_APKS) { 13226 Slog.i(TAG, " Removing package " + packageName); 13227 } 13228 mHandler.post(new Runnable() { 13229 public void run() { 13230 deletePackageX(packageName, userHandle, 0); 13231 } //end run 13232 }); 13233 } 13234 } 13235 } 13236 13237 /** Called by UserManagerService */ 13238 void createNewUserLILPw(int userHandle, File path) { 13239 if (mInstaller != null) { 13240 mInstaller.createUserConfig(userHandle); 13241 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13242 } 13243 } 13244 13245 @Override 13246 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13247 mContext.enforceCallingOrSelfPermission( 13248 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13249 "Only package verification agents can read the verifier device identity"); 13250 13251 synchronized (mPackages) { 13252 return mSettings.getVerifierDeviceIdentityLPw(); 13253 } 13254 } 13255 13256 @Override 13257 public void setPermissionEnforced(String permission, boolean enforced) { 13258 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13259 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13260 synchronized (mPackages) { 13261 if (mSettings.mReadExternalStorageEnforced == null 13262 || mSettings.mReadExternalStorageEnforced != enforced) { 13263 mSettings.mReadExternalStorageEnforced = enforced; 13264 mSettings.writeLPr(); 13265 } 13266 } 13267 // kill any non-foreground processes so we restart them and 13268 // grant/revoke the GID. 13269 final IActivityManager am = ActivityManagerNative.getDefault(); 13270 if (am != null) { 13271 final long token = Binder.clearCallingIdentity(); 13272 try { 13273 am.killProcessesBelowForeground("setPermissionEnforcement"); 13274 } catch (RemoteException e) { 13275 } finally { 13276 Binder.restoreCallingIdentity(token); 13277 } 13278 } 13279 } else { 13280 throw new IllegalArgumentException("No selective enforcement for " + permission); 13281 } 13282 } 13283 13284 @Override 13285 @Deprecated 13286 public boolean isPermissionEnforced(String permission) { 13287 return true; 13288 } 13289 13290 @Override 13291 public boolean isStorageLow() { 13292 final long token = Binder.clearCallingIdentity(); 13293 try { 13294 final DeviceStorageMonitorInternal 13295 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13296 if (dsm != null) { 13297 return dsm.isMemoryLow(); 13298 } else { 13299 return false; 13300 } 13301 } finally { 13302 Binder.restoreCallingIdentity(token); 13303 } 13304 } 13305 13306 @Override 13307 public IPackageInstaller getPackageInstaller() { 13308 return mInstallerService; 13309 } 13310 13311 private boolean userNeedsBadging(int userId) { 13312 int index = mUserNeedsBadging.indexOfKey(userId); 13313 if (index < 0) { 13314 final UserInfo userInfo; 13315 final long token = Binder.clearCallingIdentity(); 13316 try { 13317 userInfo = sUserManager.getUserInfo(userId); 13318 } finally { 13319 Binder.restoreCallingIdentity(token); 13320 } 13321 final boolean b; 13322 if (userInfo != null && userInfo.isManagedProfile()) { 13323 b = true; 13324 } else { 13325 b = false; 13326 } 13327 mUserNeedsBadging.put(userId, b); 13328 return b; 13329 } 13330 return mUserNeedsBadging.valueAt(index); 13331 } 13332 13333 @Override 13334 public KeySet getKeySetByAlias(String packageName, String alias) { 13335 if (packageName == null || alias == null) { 13336 return null; 13337 } 13338 synchronized(mPackages) { 13339 final PackageParser.Package pkg = mPackages.get(packageName); 13340 if (pkg == null) { 13341 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13342 throw new IllegalArgumentException("Unknown package: " + packageName); 13343 } 13344 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13345 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13346 } 13347 } 13348 13349 @Override 13350 public KeySet getSigningKeySet(String packageName) { 13351 if (packageName == null) { 13352 return null; 13353 } 13354 synchronized(mPackages) { 13355 final PackageParser.Package pkg = mPackages.get(packageName); 13356 if (pkg == null) { 13357 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13358 throw new IllegalArgumentException("Unknown package: " + packageName); 13359 } 13360 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13361 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13362 throw new SecurityException("May not access signing KeySet of other apps."); 13363 } 13364 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13365 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13366 } 13367 } 13368 13369 @Override 13370 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13371 if (packageName == null || ks == null) { 13372 return false; 13373 } 13374 synchronized(mPackages) { 13375 final PackageParser.Package pkg = mPackages.get(packageName); 13376 if (pkg == null) { 13377 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13378 throw new IllegalArgumentException("Unknown package: " + packageName); 13379 } 13380 IBinder ksh = ks.getToken(); 13381 if (ksh instanceof KeySetHandle) { 13382 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13383 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13384 } 13385 return false; 13386 } 13387 } 13388 13389 @Override 13390 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13391 if (packageName == null || ks == null) { 13392 return false; 13393 } 13394 synchronized(mPackages) { 13395 final PackageParser.Package pkg = mPackages.get(packageName); 13396 if (pkg == null) { 13397 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13398 throw new IllegalArgumentException("Unknown package: " + packageName); 13399 } 13400 IBinder ksh = ks.getToken(); 13401 if (ksh instanceof KeySetHandle) { 13402 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13403 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13404 } 13405 return false; 13406 } 13407 } 13408} 13409