PackageManagerService.java revision d052a9416ae3f7e42fc1e7de0740021df385ee48
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.app.usage.UsageStats; 88import android.app.usage.UsageStatsManager; 89import android.content.BroadcastReceiver; 90import android.content.ComponentName; 91import android.content.Context; 92import android.content.IIntentReceiver; 93import android.content.Intent; 94import android.content.IntentFilter; 95import android.content.IntentSender; 96import android.content.IntentSender.SendIntentException; 97import android.content.ServiceConnection; 98import android.content.pm.ActivityInfo; 99import android.content.pm.ApplicationInfo; 100import android.content.pm.FeatureInfo; 101import android.content.pm.IPackageDataObserver; 102import android.content.pm.IPackageDeleteObserver; 103import android.content.pm.IPackageDeleteObserver2; 104import android.content.pm.IPackageInstallObserver2; 105import android.content.pm.IPackageInstaller; 106import android.content.pm.IPackageManager; 107import android.content.pm.IPackageMoveObserver; 108import android.content.pm.IPackageStatsObserver; 109import android.content.pm.InstrumentationInfo; 110import android.content.pm.KeySet; 111import android.content.pm.ManifestDigest; 112import android.content.pm.PackageCleanItem; 113import android.content.pm.PackageInfo; 114import android.content.pm.PackageInfoLite; 115import android.content.pm.PackageInstaller; 116import android.content.pm.PackageManager; 117import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 118import android.content.pm.PackageParser.ActivityIntentInfo; 119import android.content.pm.PackageParser.PackageLite; 120import android.content.pm.PackageParser.PackageParserException; 121import android.content.pm.PackageParser; 122import android.content.pm.PackageStats; 123import android.content.pm.PackageUserState; 124import android.content.pm.ParceledListSlice; 125import android.content.pm.PermissionGroupInfo; 126import android.content.pm.PermissionInfo; 127import android.content.pm.ProviderInfo; 128import android.content.pm.ResolveInfo; 129import android.content.pm.ServiceInfo; 130import android.content.pm.Signature; 131import android.content.pm.UserInfo; 132import android.content.pm.VerificationParams; 133import android.content.pm.VerifierDeviceIdentity; 134import android.content.pm.VerifierInfo; 135import android.content.res.Resources; 136import android.hardware.display.DisplayManager; 137import android.net.Uri; 138import android.os.Binder; 139import android.os.Build; 140import android.os.Bundle; 141import android.os.Environment; 142import android.os.Environment.UserEnvironment; 143import android.os.storage.StorageManager; 144import android.os.Debug; 145import android.os.FileUtils; 146import android.os.Handler; 147import android.os.IBinder; 148import android.os.Looper; 149import android.os.Message; 150import android.os.Parcel; 151import android.os.ParcelFileDescriptor; 152import android.os.Process; 153import android.os.RemoteException; 154import android.os.SELinux; 155import android.os.ServiceManager; 156import android.os.SystemClock; 157import android.os.SystemProperties; 158import android.os.UserHandle; 159import android.os.UserManager; 160import android.security.KeyStore; 161import android.security.SystemKeyStore; 162import android.system.ErrnoException; 163import android.system.Os; 164import android.system.StructStat; 165import android.text.TextUtils; 166import android.util.ArraySet; 167import android.util.AtomicFile; 168import android.util.DisplayMetrics; 169import android.util.EventLog; 170import android.util.ExceptionUtils; 171import android.util.Log; 172import android.util.LogPrinter; 173import android.util.PrintStreamPrinter; 174import android.util.Slog; 175import android.util.SparseArray; 176import android.util.SparseBooleanArray; 177import android.view.Display; 178 179import java.io.BufferedInputStream; 180import java.io.BufferedOutputStream; 181import java.io.BufferedReader; 182import java.io.File; 183import java.io.FileDescriptor; 184import java.io.FileInputStream; 185import java.io.FileNotFoundException; 186import java.io.FileOutputStream; 187import java.io.FileReader; 188import java.io.FilenameFilter; 189import java.io.IOException; 190import java.io.InputStream; 191import java.io.PrintWriter; 192import java.nio.charset.StandardCharsets; 193import java.security.NoSuchAlgorithmException; 194import java.security.PublicKey; 195import java.security.cert.CertificateEncodingException; 196import java.security.cert.CertificateException; 197import java.text.SimpleDateFormat; 198import java.util.ArrayList; 199import java.util.Arrays; 200import java.util.Collection; 201import java.util.Collections; 202import java.util.Comparator; 203import java.util.Date; 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 long mDexOptLRUThresholdInMills; 333 final DisplayMetrics mMetrics; 334 final int mDefParseFlags; 335 final String[] mSeparateProcesses; 336 final boolean mIsUpgrade; 337 338 // This is where all application persistent data goes. 339 final File mAppDataDir; 340 341 // This is where all application persistent data goes for secondary users. 342 final File mUserAppDataDir; 343 344 /** The location for ASEC container files on internal storage. */ 345 final String mAsecInternalPath; 346 347 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 348 // LOCK HELD. Can be called with mInstallLock held. 349 final Installer mInstaller; 350 351 /** Directory where installed third-party apps stored */ 352 final File mAppInstallDir; 353 354 /** 355 * Directory to which applications installed internally have their 356 * 32 bit native libraries copied. 357 */ 358 private File mAppLib32InstallDir; 359 360 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 361 // apps. 362 final File mDrmAppPrivateInstallDir; 363 364 // ---------------------------------------------------------------- 365 366 // Lock for state used when installing and doing other long running 367 // operations. Methods that must be called with this lock held have 368 // the suffix "LI". 369 final Object mInstallLock = new Object(); 370 371 // ---------------------------------------------------------------- 372 373 // Keys are String (package name), values are Package. This also serves 374 // as the lock for the global state. Methods that must be called with 375 // this lock held have the prefix "LP". 376 final ArrayMap<String, PackageParser.Package> mPackages = 377 new ArrayMap<String, PackageParser.Package>(); 378 379 // Tracks available target package names -> overlay package paths. 380 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 381 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 382 383 final Settings mSettings; 384 boolean mRestoredSettings; 385 386 // System configuration read by SystemConfig. 387 final int[] mGlobalGids; 388 final SparseArray<ArraySet<String>> mSystemPermissions; 389 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 390 391 // If mac_permissions.xml was found for seinfo labeling. 392 boolean mFoundPolicyFile; 393 394 // If a recursive restorecon of /data/data/<pkg> is needed. 395 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 396 397 public static final class SharedLibraryEntry { 398 public final String path; 399 public final String apk; 400 401 SharedLibraryEntry(String _path, String _apk) { 402 path = _path; 403 apk = _apk; 404 } 405 } 406 407 // Currently known shared libraries. 408 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 409 new ArrayMap<String, SharedLibraryEntry>(); 410 411 // All available activities, for your resolving pleasure. 412 final ActivityIntentResolver mActivities = 413 new ActivityIntentResolver(); 414 415 // All available receivers, for your resolving pleasure. 416 final ActivityIntentResolver mReceivers = 417 new ActivityIntentResolver(); 418 419 // All available services, for your resolving pleasure. 420 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 421 422 // All available providers, for your resolving pleasure. 423 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 424 425 // Mapping from provider base names (first directory in content URI codePath) 426 // to the provider information. 427 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 428 new ArrayMap<String, PackageParser.Provider>(); 429 430 // Mapping from instrumentation class names to info about them. 431 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 432 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 433 434 // Mapping from permission names to info about them. 435 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 436 new ArrayMap<String, PackageParser.PermissionGroup>(); 437 438 // Packages whose data we have transfered into another package, thus 439 // should no longer exist. 440 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 441 442 // Broadcast actions that are only available to the system. 443 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 444 445 /** List of packages waiting for verification. */ 446 final SparseArray<PackageVerificationState> mPendingVerification 447 = new SparseArray<PackageVerificationState>(); 448 449 /** Set of packages associated with each app op permission. */ 450 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 451 452 final PackageInstallerService mInstallerService; 453 454 ArraySet<PackageParser.Package> mDeferredDexOpt = null; 455 456 // Cache of users who need badging. 457 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 458 459 /** Token for keys in mPendingVerification. */ 460 private int mPendingVerificationToken = 0; 461 462 volatile boolean mSystemReady; 463 volatile boolean mSafeMode; 464 volatile boolean mHasSystemUidErrors; 465 466 ApplicationInfo mAndroidApplication; 467 final ActivityInfo mResolveActivity = new ActivityInfo(); 468 final ResolveInfo mResolveInfo = new ResolveInfo(); 469 ComponentName mResolveComponentName; 470 PackageParser.Package mPlatformPackage; 471 ComponentName mCustomResolverComponentName; 472 473 boolean mResolverReplaced = false; 474 475 // Set of pending broadcasts for aggregating enable/disable of components. 476 static class PendingPackageBroadcasts { 477 // for each user id, a map of <package name -> components within that package> 478 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 479 480 public PendingPackageBroadcasts() { 481 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 482 } 483 484 public ArrayList<String> get(int userId, String packageName) { 485 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 486 return packages.get(packageName); 487 } 488 489 public void put(int userId, String packageName, ArrayList<String> components) { 490 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 491 packages.put(packageName, components); 492 } 493 494 public void remove(int userId, String packageName) { 495 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 496 if (packages != null) { 497 packages.remove(packageName); 498 } 499 } 500 501 public void remove(int userId) { 502 mUidMap.remove(userId); 503 } 504 505 public int userIdCount() { 506 return mUidMap.size(); 507 } 508 509 public int userIdAt(int n) { 510 return mUidMap.keyAt(n); 511 } 512 513 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 514 return mUidMap.get(userId); 515 } 516 517 public int size() { 518 // total number of pending broadcast entries across all userIds 519 int num = 0; 520 for (int i = 0; i< mUidMap.size(); i++) { 521 num += mUidMap.valueAt(i).size(); 522 } 523 return num; 524 } 525 526 public void clear() { 527 mUidMap.clear(); 528 } 529 530 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 531 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 532 if (map == null) { 533 map = new ArrayMap<String, ArrayList<String>>(); 534 mUidMap.put(userId, map); 535 } 536 return map; 537 } 538 } 539 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 540 541 // Service Connection to remote media container service to copy 542 // package uri's from external media onto secure containers 543 // or internal storage. 544 private IMediaContainerService mContainerService = null; 545 546 static final int SEND_PENDING_BROADCAST = 1; 547 static final int MCS_BOUND = 3; 548 static final int END_COPY = 4; 549 static final int INIT_COPY = 5; 550 static final int MCS_UNBIND = 6; 551 static final int START_CLEANING_PACKAGE = 7; 552 static final int FIND_INSTALL_LOC = 8; 553 static final int POST_INSTALL = 9; 554 static final int MCS_RECONNECT = 10; 555 static final int MCS_GIVE_UP = 11; 556 static final int UPDATED_MEDIA_STATUS = 12; 557 static final int WRITE_SETTINGS = 13; 558 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 559 static final int PACKAGE_VERIFIED = 15; 560 static final int CHECK_PENDING_VERIFICATION = 16; 561 562 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 563 564 // Delay time in millisecs 565 static final int BROADCAST_DELAY = 10 * 1000; 566 567 static UserManagerService sUserManager; 568 569 // Stores a list of users whose package restrictions file needs to be updated 570 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 571 572 final private DefaultContainerConnection mDefContainerConn = 573 new DefaultContainerConnection(); 574 class DefaultContainerConnection implements ServiceConnection { 575 public void onServiceConnected(ComponentName name, IBinder service) { 576 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 577 IMediaContainerService imcs = 578 IMediaContainerService.Stub.asInterface(service); 579 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 580 } 581 582 public void onServiceDisconnected(ComponentName name) { 583 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 584 } 585 }; 586 587 // Recordkeeping of restore-after-install operations that are currently in flight 588 // between the Package Manager and the Backup Manager 589 class PostInstallData { 590 public InstallArgs args; 591 public PackageInstalledInfo res; 592 593 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 594 args = _a; 595 res = _r; 596 } 597 }; 598 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 599 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 600 601 private final String mRequiredVerifierPackage; 602 603 private final PackageUsage mPackageUsage = new PackageUsage(); 604 605 private class PackageUsage { 606 private static final int WRITE_INTERVAL 607 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 608 609 private final Object mFileLock = new Object(); 610 private final AtomicLong mLastWritten = new AtomicLong(0); 611 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 612 613 private boolean mIsHistoricalPackageUsageAvailable = true; 614 615 boolean isHistoricalPackageUsageAvailable() { 616 return mIsHistoricalPackageUsageAvailable; 617 } 618 619 void write(boolean force) { 620 if (force) { 621 writeInternal(); 622 return; 623 } 624 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 625 && !DEBUG_DEXOPT) { 626 return; 627 } 628 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 629 new Thread("PackageUsage_DiskWriter") { 630 @Override 631 public void run() { 632 try { 633 writeInternal(); 634 } finally { 635 mBackgroundWriteRunning.set(false); 636 } 637 } 638 }.start(); 639 } 640 } 641 642 private void writeInternal() { 643 synchronized (mPackages) { 644 synchronized (mFileLock) { 645 AtomicFile file = getFile(); 646 FileOutputStream f = null; 647 try { 648 f = file.startWrite(); 649 BufferedOutputStream out = new BufferedOutputStream(f); 650 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 651 StringBuilder sb = new StringBuilder(); 652 for (PackageParser.Package pkg : mPackages.values()) { 653 if (pkg.mLastPackageUsageTimeInMills == 0) { 654 continue; 655 } 656 sb.setLength(0); 657 sb.append(pkg.packageName); 658 sb.append(' '); 659 sb.append((long)pkg.mLastPackageUsageTimeInMills); 660 sb.append('\n'); 661 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 662 } 663 out.flush(); 664 file.finishWrite(f); 665 } catch (IOException e) { 666 if (f != null) { 667 file.failWrite(f); 668 } 669 Log.e(TAG, "Failed to write package usage times", e); 670 } 671 } 672 } 673 mLastWritten.set(SystemClock.elapsedRealtime()); 674 } 675 676 void readLP() { 677 synchronized (mFileLock) { 678 AtomicFile file = getFile(); 679 BufferedInputStream in = null; 680 try { 681 in = new BufferedInputStream(file.openRead()); 682 StringBuffer sb = new StringBuffer(); 683 while (true) { 684 String packageName = readToken(in, sb, ' '); 685 if (packageName == null) { 686 break; 687 } 688 String timeInMillisString = readToken(in, sb, '\n'); 689 if (timeInMillisString == null) { 690 throw new IOException("Failed to find last usage time for package " 691 + packageName); 692 } 693 PackageParser.Package pkg = mPackages.get(packageName); 694 if (pkg == null) { 695 continue; 696 } 697 long timeInMillis; 698 try { 699 timeInMillis = Long.parseLong(timeInMillisString.toString()); 700 } catch (NumberFormatException e) { 701 throw new IOException("Failed to parse " + timeInMillisString 702 + " as a long.", e); 703 } 704 pkg.mLastPackageUsageTimeInMills = timeInMillis; 705 } 706 } catch (FileNotFoundException expected) { 707 mIsHistoricalPackageUsageAvailable = false; 708 } catch (IOException e) { 709 Log.w(TAG, "Failed to read package usage times", e); 710 } finally { 711 IoUtils.closeQuietly(in); 712 } 713 } 714 mLastWritten.set(SystemClock.elapsedRealtime()); 715 } 716 717 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 718 throws IOException { 719 sb.setLength(0); 720 while (true) { 721 int ch = in.read(); 722 if (ch == -1) { 723 if (sb.length() == 0) { 724 return null; 725 } 726 throw new IOException("Unexpected EOF"); 727 } 728 if (ch == endOfToken) { 729 return sb.toString(); 730 } 731 sb.append((char)ch); 732 } 733 } 734 735 private AtomicFile getFile() { 736 File dataDir = Environment.getDataDirectory(); 737 File systemDir = new File(dataDir, "system"); 738 File fname = new File(systemDir, "package-usage.list"); 739 return new AtomicFile(fname); 740 } 741 } 742 743 class PackageHandler extends Handler { 744 private boolean mBound = false; 745 final ArrayList<HandlerParams> mPendingInstalls = 746 new ArrayList<HandlerParams>(); 747 748 private boolean connectToService() { 749 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 750 " DefaultContainerService"); 751 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 752 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 753 if (mContext.bindServiceAsUser(service, mDefContainerConn, 754 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 755 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 756 mBound = true; 757 return true; 758 } 759 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 760 return false; 761 } 762 763 private void disconnectService() { 764 mContainerService = null; 765 mBound = false; 766 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 767 mContext.unbindService(mDefContainerConn); 768 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 769 } 770 771 PackageHandler(Looper looper) { 772 super(looper); 773 } 774 775 public void handleMessage(Message msg) { 776 try { 777 doHandleMessage(msg); 778 } finally { 779 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 780 } 781 } 782 783 void doHandleMessage(Message msg) { 784 switch (msg.what) { 785 case INIT_COPY: { 786 HandlerParams params = (HandlerParams) msg.obj; 787 int idx = mPendingInstalls.size(); 788 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 789 // If a bind was already initiated we dont really 790 // need to do anything. The pending install 791 // will be processed later on. 792 if (!mBound) { 793 // If this is the only one pending we might 794 // have to bind to the service again. 795 if (!connectToService()) { 796 Slog.e(TAG, "Failed to bind to media container service"); 797 params.serviceError(); 798 return; 799 } else { 800 // Once we bind to the service, the first 801 // pending request will be processed. 802 mPendingInstalls.add(idx, params); 803 } 804 } else { 805 mPendingInstalls.add(idx, params); 806 // Already bound to the service. Just make 807 // sure we trigger off processing the first request. 808 if (idx == 0) { 809 mHandler.sendEmptyMessage(MCS_BOUND); 810 } 811 } 812 break; 813 } 814 case MCS_BOUND: { 815 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 816 if (msg.obj != null) { 817 mContainerService = (IMediaContainerService) msg.obj; 818 } 819 if (mContainerService == null) { 820 // Something seriously wrong. Bail out 821 Slog.e(TAG, "Cannot bind to media container service"); 822 for (HandlerParams params : mPendingInstalls) { 823 // Indicate service bind error 824 params.serviceError(); 825 } 826 mPendingInstalls.clear(); 827 } else if (mPendingInstalls.size() > 0) { 828 HandlerParams params = mPendingInstalls.get(0); 829 if (params != null) { 830 if (params.startCopy()) { 831 // We are done... look for more work or to 832 // go idle. 833 if (DEBUG_SD_INSTALL) Log.i(TAG, 834 "Checking for more work or unbind..."); 835 // Delete pending install 836 if (mPendingInstalls.size() > 0) { 837 mPendingInstalls.remove(0); 838 } 839 if (mPendingInstalls.size() == 0) { 840 if (mBound) { 841 if (DEBUG_SD_INSTALL) Log.i(TAG, 842 "Posting delayed MCS_UNBIND"); 843 removeMessages(MCS_UNBIND); 844 Message ubmsg = obtainMessage(MCS_UNBIND); 845 // Unbind after a little delay, to avoid 846 // continual thrashing. 847 sendMessageDelayed(ubmsg, 10000); 848 } 849 } else { 850 // There are more pending requests in queue. 851 // Just post MCS_BOUND message to trigger processing 852 // of next pending install. 853 if (DEBUG_SD_INSTALL) Log.i(TAG, 854 "Posting MCS_BOUND for next work"); 855 mHandler.sendEmptyMessage(MCS_BOUND); 856 } 857 } 858 } 859 } else { 860 // Should never happen ideally. 861 Slog.w(TAG, "Empty queue"); 862 } 863 break; 864 } 865 case MCS_RECONNECT: { 866 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 867 if (mPendingInstalls.size() > 0) { 868 if (mBound) { 869 disconnectService(); 870 } 871 if (!connectToService()) { 872 Slog.e(TAG, "Failed to bind to media container service"); 873 for (HandlerParams params : mPendingInstalls) { 874 // Indicate service bind error 875 params.serviceError(); 876 } 877 mPendingInstalls.clear(); 878 } 879 } 880 break; 881 } 882 case MCS_UNBIND: { 883 // If there is no actual work left, then time to unbind. 884 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 885 886 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 887 if (mBound) { 888 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 889 890 disconnectService(); 891 } 892 } else if (mPendingInstalls.size() > 0) { 893 // There are more pending requests in queue. 894 // Just post MCS_BOUND message to trigger processing 895 // of next pending install. 896 mHandler.sendEmptyMessage(MCS_BOUND); 897 } 898 899 break; 900 } 901 case MCS_GIVE_UP: { 902 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 903 mPendingInstalls.remove(0); 904 break; 905 } 906 case SEND_PENDING_BROADCAST: { 907 String packages[]; 908 ArrayList<String> components[]; 909 int size = 0; 910 int uids[]; 911 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 912 synchronized (mPackages) { 913 if (mPendingBroadcasts == null) { 914 return; 915 } 916 size = mPendingBroadcasts.size(); 917 if (size <= 0) { 918 // Nothing to be done. Just return 919 return; 920 } 921 packages = new String[size]; 922 components = new ArrayList[size]; 923 uids = new int[size]; 924 int i = 0; // filling out the above arrays 925 926 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 927 int packageUserId = mPendingBroadcasts.userIdAt(n); 928 Iterator<Map.Entry<String, ArrayList<String>>> it 929 = mPendingBroadcasts.packagesForUserId(packageUserId) 930 .entrySet().iterator(); 931 while (it.hasNext() && i < size) { 932 Map.Entry<String, ArrayList<String>> ent = it.next(); 933 packages[i] = ent.getKey(); 934 components[i] = ent.getValue(); 935 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 936 uids[i] = (ps != null) 937 ? UserHandle.getUid(packageUserId, ps.appId) 938 : -1; 939 i++; 940 } 941 } 942 size = i; 943 mPendingBroadcasts.clear(); 944 } 945 // Send broadcasts 946 for (int i = 0; i < size; i++) { 947 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 948 } 949 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 950 break; 951 } 952 case START_CLEANING_PACKAGE: { 953 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 954 final String packageName = (String)msg.obj; 955 final int userId = msg.arg1; 956 final boolean andCode = msg.arg2 != 0; 957 synchronized (mPackages) { 958 if (userId == UserHandle.USER_ALL) { 959 int[] users = sUserManager.getUserIds(); 960 for (int user : users) { 961 mSettings.addPackageToCleanLPw( 962 new PackageCleanItem(user, packageName, andCode)); 963 } 964 } else { 965 mSettings.addPackageToCleanLPw( 966 new PackageCleanItem(userId, packageName, andCode)); 967 } 968 } 969 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 970 startCleaningPackages(); 971 } break; 972 case POST_INSTALL: { 973 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 974 PostInstallData data = mRunningInstalls.get(msg.arg1); 975 mRunningInstalls.delete(msg.arg1); 976 boolean deleteOld = false; 977 978 if (data != null) { 979 InstallArgs args = data.args; 980 PackageInstalledInfo res = data.res; 981 982 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 983 res.removedInfo.sendBroadcast(false, true, false); 984 Bundle extras = new Bundle(1); 985 extras.putInt(Intent.EXTRA_UID, res.uid); 986 // Determine the set of users who are adding this 987 // package for the first time vs. those who are seeing 988 // an update. 989 int[] firstUsers; 990 int[] updateUsers = new int[0]; 991 if (res.origUsers == null || res.origUsers.length == 0) { 992 firstUsers = res.newUsers; 993 } else { 994 firstUsers = new int[0]; 995 for (int i=0; i<res.newUsers.length; i++) { 996 int user = res.newUsers[i]; 997 boolean isNew = true; 998 for (int j=0; j<res.origUsers.length; j++) { 999 if (res.origUsers[j] == user) { 1000 isNew = false; 1001 break; 1002 } 1003 } 1004 if (isNew) { 1005 int[] newFirst = new int[firstUsers.length+1]; 1006 System.arraycopy(firstUsers, 0, newFirst, 0, 1007 firstUsers.length); 1008 newFirst[firstUsers.length] = user; 1009 firstUsers = newFirst; 1010 } else { 1011 int[] newUpdate = new int[updateUsers.length+1]; 1012 System.arraycopy(updateUsers, 0, newUpdate, 0, 1013 updateUsers.length); 1014 newUpdate[updateUsers.length] = user; 1015 updateUsers = newUpdate; 1016 } 1017 } 1018 } 1019 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1020 res.pkg.applicationInfo.packageName, 1021 extras, null, null, firstUsers); 1022 final boolean update = res.removedInfo.removedPackage != null; 1023 if (update) { 1024 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1025 } 1026 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1027 res.pkg.applicationInfo.packageName, 1028 extras, null, null, updateUsers); 1029 if (update) { 1030 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1031 res.pkg.applicationInfo.packageName, 1032 extras, null, null, updateUsers); 1033 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1034 null, null, 1035 res.pkg.applicationInfo.packageName, null, updateUsers); 1036 1037 // treat asec-hosted packages like removable media on upgrade 1038 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1039 if (DEBUG_INSTALL) { 1040 Slog.i(TAG, "upgrading pkg " + res.pkg 1041 + " is ASEC-hosted -> AVAILABLE"); 1042 } 1043 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1044 ArrayList<String> pkgList = new ArrayList<String>(1); 1045 pkgList.add(res.pkg.applicationInfo.packageName); 1046 sendResourcesChangedBroadcast(true, true, 1047 pkgList,uidArray, null); 1048 } 1049 } 1050 if (res.removedInfo.args != null) { 1051 // Remove the replaced package's older resources safely now 1052 deleteOld = true; 1053 } 1054 1055 // Log current value of "unknown sources" setting 1056 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1057 getUnknownSourcesSettings()); 1058 } 1059 // Force a gc to clear up things 1060 Runtime.getRuntime().gc(); 1061 // We delete after a gc for applications on sdcard. 1062 if (deleteOld) { 1063 synchronized (mInstallLock) { 1064 res.removedInfo.args.doPostDeleteLI(true); 1065 } 1066 } 1067 if (args.observer != null) { 1068 try { 1069 Bundle extras = extrasForInstallResult(res); 1070 args.observer.onPackageInstalled(res.name, res.returnCode, 1071 res.returnMsg, extras); 1072 } catch (RemoteException e) { 1073 Slog.i(TAG, "Observer no longer exists."); 1074 } 1075 } 1076 } else { 1077 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1078 } 1079 } break; 1080 case UPDATED_MEDIA_STATUS: { 1081 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1082 boolean reportStatus = msg.arg1 == 1; 1083 boolean doGc = msg.arg2 == 1; 1084 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1085 if (doGc) { 1086 // Force a gc to clear up stale containers. 1087 Runtime.getRuntime().gc(); 1088 } 1089 if (msg.obj != null) { 1090 @SuppressWarnings("unchecked") 1091 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1092 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1093 // Unload containers 1094 unloadAllContainers(args); 1095 } 1096 if (reportStatus) { 1097 try { 1098 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1099 PackageHelper.getMountService().finishMediaUpdate(); 1100 } catch (RemoteException e) { 1101 Log.e(TAG, "MountService not running?"); 1102 } 1103 } 1104 } break; 1105 case WRITE_SETTINGS: { 1106 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1107 synchronized (mPackages) { 1108 removeMessages(WRITE_SETTINGS); 1109 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1110 mSettings.writeLPr(); 1111 mDirtyUsers.clear(); 1112 } 1113 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1114 } break; 1115 case WRITE_PACKAGE_RESTRICTIONS: { 1116 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1117 synchronized (mPackages) { 1118 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1119 for (int userId : mDirtyUsers) { 1120 mSettings.writePackageRestrictionsLPr(userId); 1121 } 1122 mDirtyUsers.clear(); 1123 } 1124 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1125 } break; 1126 case CHECK_PENDING_VERIFICATION: { 1127 final int verificationId = msg.arg1; 1128 final PackageVerificationState state = mPendingVerification.get(verificationId); 1129 1130 if ((state != null) && !state.timeoutExtended()) { 1131 final InstallArgs args = state.getInstallArgs(); 1132 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1133 1134 Slog.i(TAG, "Verification timed out for " + originUri); 1135 mPendingVerification.remove(verificationId); 1136 1137 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1138 1139 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1140 Slog.i(TAG, "Continuing with installation of " + originUri); 1141 state.setVerifierResponse(Binder.getCallingUid(), 1142 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1143 broadcastPackageVerified(verificationId, originUri, 1144 PackageManager.VERIFICATION_ALLOW, 1145 state.getInstallArgs().getUser()); 1146 try { 1147 ret = args.copyApk(mContainerService, true); 1148 } catch (RemoteException e) { 1149 Slog.e(TAG, "Could not contact the ContainerService"); 1150 } 1151 } else { 1152 broadcastPackageVerified(verificationId, originUri, 1153 PackageManager.VERIFICATION_REJECT, 1154 state.getInstallArgs().getUser()); 1155 } 1156 1157 processPendingInstall(args, ret); 1158 mHandler.sendEmptyMessage(MCS_UNBIND); 1159 } 1160 break; 1161 } 1162 case PACKAGE_VERIFIED: { 1163 final int verificationId = msg.arg1; 1164 1165 final PackageVerificationState state = mPendingVerification.get(verificationId); 1166 if (state == null) { 1167 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1168 break; 1169 } 1170 1171 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1172 1173 state.setVerifierResponse(response.callerUid, response.code); 1174 1175 if (state.isVerificationComplete()) { 1176 mPendingVerification.remove(verificationId); 1177 1178 final InstallArgs args = state.getInstallArgs(); 1179 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1180 1181 int ret; 1182 if (state.isInstallAllowed()) { 1183 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1184 broadcastPackageVerified(verificationId, originUri, 1185 response.code, state.getInstallArgs().getUser()); 1186 try { 1187 ret = args.copyApk(mContainerService, true); 1188 } catch (RemoteException e) { 1189 Slog.e(TAG, "Could not contact the ContainerService"); 1190 } 1191 } else { 1192 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1193 } 1194 1195 processPendingInstall(args, ret); 1196 1197 mHandler.sendEmptyMessage(MCS_UNBIND); 1198 } 1199 1200 break; 1201 } 1202 } 1203 } 1204 } 1205 1206 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1207 Bundle extras = null; 1208 switch (res.returnCode) { 1209 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1210 extras = new Bundle(); 1211 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1212 res.origPermission); 1213 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1214 res.origPackage); 1215 break; 1216 } 1217 } 1218 return extras; 1219 } 1220 1221 void scheduleWriteSettingsLocked() { 1222 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1223 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1224 } 1225 } 1226 1227 void scheduleWritePackageRestrictionsLocked(int userId) { 1228 if (!sUserManager.exists(userId)) return; 1229 mDirtyUsers.add(userId); 1230 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1231 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1232 } 1233 } 1234 1235 public static final PackageManagerService main(Context context, Installer installer, 1236 boolean factoryTest, boolean onlyCore) { 1237 PackageManagerService m = new PackageManagerService(context, installer, 1238 factoryTest, onlyCore); 1239 ServiceManager.addService("package", m); 1240 return m; 1241 } 1242 1243 static String[] splitString(String str, char sep) { 1244 int count = 1; 1245 int i = 0; 1246 while ((i=str.indexOf(sep, i)) >= 0) { 1247 count++; 1248 i++; 1249 } 1250 1251 String[] res = new String[count]; 1252 i=0; 1253 count = 0; 1254 int lastI=0; 1255 while ((i=str.indexOf(sep, i)) >= 0) { 1256 res[count] = str.substring(lastI, i); 1257 count++; 1258 i++; 1259 lastI = i; 1260 } 1261 res[count] = str.substring(lastI, str.length()); 1262 return res; 1263 } 1264 1265 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1266 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1267 Context.DISPLAY_SERVICE); 1268 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1269 } 1270 1271 public PackageManagerService(Context context, Installer installer, 1272 boolean factoryTest, boolean onlyCore) { 1273 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1274 SystemClock.uptimeMillis()); 1275 1276 if (mSdkVersion <= 0) { 1277 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1278 } 1279 1280 mContext = context; 1281 mFactoryTest = factoryTest; 1282 mOnlyCore = onlyCore; 1283 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1284 mMetrics = new DisplayMetrics(); 1285 mSettings = new Settings(context); 1286 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1287 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1288 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1289 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1290 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1291 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1292 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1293 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1294 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1295 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1296 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1297 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1298 1299 // TODO: add a property to control this? 1300 long dexOptLRUThresholdInMinutes; 1301 if (mLazyDexOpt) { 1302 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1303 } else { 1304 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1305 } 1306 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1307 1308 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1309 if (separateProcesses != null && separateProcesses.length() > 0) { 1310 if ("*".equals(separateProcesses)) { 1311 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1312 mSeparateProcesses = null; 1313 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1314 } else { 1315 mDefParseFlags = 0; 1316 mSeparateProcesses = separateProcesses.split(","); 1317 Slog.w(TAG, "Running with debug.separate_processes: " 1318 + separateProcesses); 1319 } 1320 } else { 1321 mDefParseFlags = 0; 1322 mSeparateProcesses = null; 1323 } 1324 1325 mInstaller = installer; 1326 1327 getDefaultDisplayMetrics(context, mMetrics); 1328 1329 SystemConfig systemConfig = SystemConfig.getInstance(); 1330 mGlobalGids = systemConfig.getGlobalGids(); 1331 mSystemPermissions = systemConfig.getSystemPermissions(); 1332 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1333 1334 synchronized (mInstallLock) { 1335 // writer 1336 synchronized (mPackages) { 1337 mHandlerThread = new ServiceThread(TAG, 1338 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1339 mHandlerThread.start(); 1340 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1341 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1342 1343 File dataDir = Environment.getDataDirectory(); 1344 mAppDataDir = new File(dataDir, "data"); 1345 mAppInstallDir = new File(dataDir, "app"); 1346 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1347 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1348 mUserAppDataDir = new File(dataDir, "user"); 1349 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1350 1351 sUserManager = new UserManagerService(context, this, 1352 mInstallLock, mPackages); 1353 1354 // Propagate permission configuration in to package manager. 1355 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1356 = systemConfig.getPermissions(); 1357 for (int i=0; i<permConfig.size(); i++) { 1358 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1359 BasePermission bp = mSettings.mPermissions.get(perm.name); 1360 if (bp == null) { 1361 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1362 mSettings.mPermissions.put(perm.name, bp); 1363 } 1364 if (perm.gids != null) { 1365 bp.gids = appendInts(bp.gids, perm.gids); 1366 } 1367 } 1368 1369 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1370 for (int i=0; i<libConfig.size(); i++) { 1371 mSharedLibraries.put(libConfig.keyAt(i), 1372 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1373 } 1374 1375 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1376 1377 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1378 mSdkVersion, mOnlyCore); 1379 1380 String customResolverActivity = Resources.getSystem().getString( 1381 R.string.config_customResolverActivity); 1382 if (TextUtils.isEmpty(customResolverActivity)) { 1383 customResolverActivity = null; 1384 } else { 1385 mCustomResolverComponentName = ComponentName.unflattenFromString( 1386 customResolverActivity); 1387 } 1388 1389 long startTime = SystemClock.uptimeMillis(); 1390 1391 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1392 startTime); 1393 1394 // Set flag to monitor and not change apk file paths when 1395 // scanning install directories. 1396 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1397 1398 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1399 1400 /** 1401 * Add everything in the in the boot class path to the 1402 * list of process files because dexopt will have been run 1403 * if necessary during zygote startup. 1404 */ 1405 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1406 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1407 1408 if (bootClassPath != null) { 1409 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1410 for (String element : bootClassPathElements) { 1411 alreadyDexOpted.add(element); 1412 } 1413 } else { 1414 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1415 } 1416 1417 if (systemServerClassPath != null) { 1418 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1419 for (String element : systemServerClassPathElements) { 1420 alreadyDexOpted.add(element); 1421 } 1422 } else { 1423 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1424 } 1425 1426 final List<String> allInstructionSets = getAllInstructionSets(); 1427 final String[] dexCodeInstructionSets = 1428 getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()])); 1429 1430 /** 1431 * Ensure all external libraries have had dexopt run on them. 1432 */ 1433 if (mSharedLibraries.size() > 0) { 1434 // NOTE: For now, we're compiling these system "shared libraries" 1435 // (and framework jars) into all available architectures. It's possible 1436 // to compile them only when we come across an app that uses them (there's 1437 // already logic for that in scanPackageLI) but that adds some complexity. 1438 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1439 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1440 final String lib = libEntry.path; 1441 if (lib == null) { 1442 continue; 1443 } 1444 1445 try { 1446 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1447 dexCodeInstructionSet, 1448 false); 1449 if (dexoptRequired != DexFile.UP_TO_DATE) { 1450 alreadyDexOpted.add(lib); 1451 1452 // The list of "shared libraries" we have at this point is 1453 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1454 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1455 } else { 1456 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1457 } 1458 } 1459 } catch (FileNotFoundException e) { 1460 Slog.w(TAG, "Library not found: " + lib); 1461 } catch (IOException e) { 1462 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1463 + e.getMessage()); 1464 } 1465 } 1466 } 1467 } 1468 1469 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1470 1471 // Gross hack for now: we know this file doesn't contain any 1472 // code, so don't dexopt it to avoid the resulting log spew. 1473 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1474 1475 // Gross hack for now: we know this file is only part of 1476 // the boot class path for art, so don't dexopt it to 1477 // avoid the resulting log spew. 1478 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1479 1480 /** 1481 * And there are a number of commands implemented in Java, which 1482 * we currently need to do the dexopt on so that they can be 1483 * run from a non-root shell. 1484 */ 1485 String[] frameworkFiles = frameworkDir.list(); 1486 if (frameworkFiles != null) { 1487 // TODO: We could compile these only for the most preferred ABI. We should 1488 // first double check that the dex files for these commands are not referenced 1489 // by other system apps. 1490 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1491 for (int i=0; i<frameworkFiles.length; i++) { 1492 File libPath = new File(frameworkDir, frameworkFiles[i]); 1493 String path = libPath.getPath(); 1494 // Skip the file if we already did it. 1495 if (alreadyDexOpted.contains(path)) { 1496 continue; 1497 } 1498 // Skip the file if it is not a type we want to dexopt. 1499 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1500 continue; 1501 } 1502 try { 1503 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1504 dexCodeInstructionSet, 1505 false); 1506 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1507 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1508 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1509 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1510 } 1511 } catch (FileNotFoundException e) { 1512 Slog.w(TAG, "Jar not found: " + path); 1513 } catch (IOException e) { 1514 Slog.w(TAG, "Exception reading jar: " + path, e); 1515 } 1516 } 1517 } 1518 } 1519 1520 // Collect vendor overlay packages. 1521 // (Do this before scanning any apps.) 1522 // For security and version matching reason, only consider 1523 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1524 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1525 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1526 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1527 1528 // Find base frameworks (resource packages without code). 1529 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1530 | PackageParser.PARSE_IS_SYSTEM_DIR 1531 | PackageParser.PARSE_IS_PRIVILEGED, 1532 scanFlags | SCAN_NO_DEX, 0); 1533 1534 // Collected privileged system packages. 1535 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1536 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1537 | PackageParser.PARSE_IS_SYSTEM_DIR 1538 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1539 1540 // Collect ordinary system packages. 1541 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1542 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1543 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1544 1545 // Collect all vendor packages. 1546 File vendorAppDir = new File("/vendor/app"); 1547 try { 1548 vendorAppDir = vendorAppDir.getCanonicalFile(); 1549 } catch (IOException e) { 1550 // failed to look up canonical path, continue with original one 1551 } 1552 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1553 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1554 1555 // Collect all OEM packages. 1556 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1557 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1558 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1559 1560 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1561 mInstaller.moveFiles(); 1562 1563 // Prune any system packages that no longer exist. 1564 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1565 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1566 if (!mOnlyCore) { 1567 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1568 while (psit.hasNext()) { 1569 PackageSetting ps = psit.next(); 1570 1571 /* 1572 * If this is not a system app, it can't be a 1573 * disable system app. 1574 */ 1575 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1576 continue; 1577 } 1578 1579 /* 1580 * If the package is scanned, it's not erased. 1581 */ 1582 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1583 if (scannedPkg != null) { 1584 /* 1585 * If the system app is both scanned and in the 1586 * disabled packages list, then it must have been 1587 * added via OTA. Remove it from the currently 1588 * scanned package so the previously user-installed 1589 * application can be scanned. 1590 */ 1591 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1592 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1593 + ps.name + "; removing system app. Last known codePath=" 1594 + ps.codePathString + ", installStatus=" + ps.installStatus 1595 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1596 + scannedPkg.mVersionCode); 1597 removePackageLI(ps, true); 1598 expectingBetter.put(ps.name, ps.codePath); 1599 } 1600 1601 continue; 1602 } 1603 1604 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1605 psit.remove(); 1606 logCriticalInfo(Log.WARN, "System package " + ps.name 1607 + " no longer exists; wiping its data"); 1608 removeDataDirsLI(ps.name); 1609 } else { 1610 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1611 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1612 possiblyDeletedUpdatedSystemApps.add(ps.name); 1613 } 1614 } 1615 } 1616 } 1617 1618 //look for any incomplete package installations 1619 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1620 //clean up list 1621 for(int i = 0; i < deletePkgsList.size(); i++) { 1622 //clean up here 1623 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1624 } 1625 //delete tmp files 1626 deleteTempPackageFiles(); 1627 1628 // Remove any shared userIDs that have no associated packages 1629 mSettings.pruneSharedUsersLPw(); 1630 1631 if (!mOnlyCore) { 1632 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1633 SystemClock.uptimeMillis()); 1634 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1635 1636 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1637 scanFlags, 0); 1638 1639 /** 1640 * Remove disable package settings for any updated system 1641 * apps that were removed via an OTA. If they're not a 1642 * previously-updated app, remove them completely. 1643 * Otherwise, just revoke their system-level permissions. 1644 */ 1645 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1646 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1647 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1648 1649 String msg; 1650 if (deletedPkg == null) { 1651 msg = "Updated system package " + deletedAppName 1652 + " no longer exists; wiping its data"; 1653 removeDataDirsLI(deletedAppName); 1654 } else { 1655 msg = "Updated system app + " + deletedAppName 1656 + " no longer present; removing system privileges for " 1657 + deletedAppName; 1658 1659 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1660 1661 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1662 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1663 } 1664 logCriticalInfo(Log.WARN, msg); 1665 } 1666 1667 /** 1668 * Make sure all system apps that we expected to appear on 1669 * the userdata partition actually showed up. If they never 1670 * appeared, crawl back and revive the system version. 1671 */ 1672 for (int i = 0; i < expectingBetter.size(); i++) { 1673 final String packageName = expectingBetter.keyAt(i); 1674 if (!mPackages.containsKey(packageName)) { 1675 final File scanFile = expectingBetter.valueAt(i); 1676 1677 logCriticalInfo(Log.WARN, "Expected better " + packageName 1678 + " but never showed up; reverting to system"); 1679 1680 final int reparseFlags; 1681 if (FileUtils.contains(privilegedAppDir, scanFile)) { 1682 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1683 | PackageParser.PARSE_IS_SYSTEM_DIR 1684 | PackageParser.PARSE_IS_PRIVILEGED; 1685 } else if (FileUtils.contains(systemAppDir, scanFile)) { 1686 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1687 | PackageParser.PARSE_IS_SYSTEM_DIR; 1688 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 1689 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1690 | PackageParser.PARSE_IS_SYSTEM_DIR; 1691 } else if (FileUtils.contains(oemAppDir, scanFile)) { 1692 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1693 | PackageParser.PARSE_IS_SYSTEM_DIR; 1694 } else { 1695 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 1696 continue; 1697 } 1698 1699 mSettings.enableSystemPackageLPw(packageName); 1700 1701 try { 1702 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 1703 } catch (PackageManagerException e) { 1704 Slog.e(TAG, "Failed to parse original system package: " 1705 + e.getMessage()); 1706 } 1707 } 1708 } 1709 } 1710 1711 // Now that we know all of the shared libraries, update all clients to have 1712 // the correct library paths. 1713 updateAllSharedLibrariesLPw(); 1714 1715 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1716 // NOTE: We ignore potential failures here during a system scan (like 1717 // the rest of the commands above) because there's precious little we 1718 // can do about it. A settings error is reported, though. 1719 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1720 false /* force dexopt */, false /* defer dexopt */); 1721 } 1722 1723 // Now that we know all the packages we are keeping, 1724 // read and update their last usage times. 1725 mPackageUsage.readLP(); 1726 1727 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1728 SystemClock.uptimeMillis()); 1729 Slog.i(TAG, "Time to scan packages: " 1730 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1731 + " seconds"); 1732 1733 // If the platform SDK has changed since the last time we booted, 1734 // we need to re-grant app permission to catch any new ones that 1735 // appear. This is really a hack, and means that apps can in some 1736 // cases get permissions that the user didn't initially explicitly 1737 // allow... it would be nice to have some better way to handle 1738 // this situation. 1739 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1740 != mSdkVersion; 1741 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1742 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1743 + "; regranting permissions for internal storage"); 1744 mSettings.mInternalSdkPlatform = mSdkVersion; 1745 1746 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1747 | (regrantPermissions 1748 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1749 : 0)); 1750 1751 // If this is the first boot, and it is a normal boot, then 1752 // we need to initialize the default preferred apps. 1753 if (!mRestoredSettings && !onlyCore) { 1754 mSettings.readDefaultPreferredAppsLPw(this, 0); 1755 } 1756 1757 // If this is first boot after an OTA, and a normal boot, then 1758 // we need to clear code cache directories. 1759 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 1760 if (mIsUpgrade && !onlyCore) { 1761 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1762 for (String pkgName : mSettings.mPackages.keySet()) { 1763 deleteCodeCacheDirsLI(pkgName); 1764 } 1765 mSettings.mFingerprint = Build.FINGERPRINT; 1766 } 1767 1768 // All the changes are done during package scanning. 1769 mSettings.updateInternalDatabaseVersion(); 1770 1771 // can downgrade to reader 1772 mSettings.writeLPr(); 1773 1774 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1775 SystemClock.uptimeMillis()); 1776 1777 1778 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1779 } // synchronized (mPackages) 1780 } // synchronized (mInstallLock) 1781 1782 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1783 1784 // Now after opening every single application zip, make sure they 1785 // are all flushed. Not really needed, but keeps things nice and 1786 // tidy. 1787 Runtime.getRuntime().gc(); 1788 } 1789 1790 @Override 1791 public boolean isFirstBoot() { 1792 return !mRestoredSettings; 1793 } 1794 1795 @Override 1796 public boolean isOnlyCoreApps() { 1797 return mOnlyCore; 1798 } 1799 1800 @Override 1801 public boolean isUpgrade() { 1802 return mIsUpgrade; 1803 } 1804 1805 private String getRequiredVerifierLPr() { 1806 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1807 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1808 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1809 1810 String requiredVerifier = null; 1811 1812 final int N = receivers.size(); 1813 for (int i = 0; i < N; i++) { 1814 final ResolveInfo info = receivers.get(i); 1815 1816 if (info.activityInfo == null) { 1817 continue; 1818 } 1819 1820 final String packageName = info.activityInfo.packageName; 1821 1822 final PackageSetting ps = mSettings.mPackages.get(packageName); 1823 if (ps == null) { 1824 continue; 1825 } 1826 1827 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1828 if (!gp.grantedPermissions 1829 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1830 continue; 1831 } 1832 1833 if (requiredVerifier != null) { 1834 throw new RuntimeException("There can be only one required verifier"); 1835 } 1836 1837 requiredVerifier = packageName; 1838 } 1839 1840 return requiredVerifier; 1841 } 1842 1843 @Override 1844 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1845 throws RemoteException { 1846 try { 1847 return super.onTransact(code, data, reply, flags); 1848 } catch (RuntimeException e) { 1849 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1850 Slog.wtf(TAG, "Package Manager Crash", e); 1851 } 1852 throw e; 1853 } 1854 } 1855 1856 void cleanupInstallFailedPackage(PackageSetting ps) { 1857 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 1858 1859 removeDataDirsLI(ps.name); 1860 if (ps.codePath != null) { 1861 if (ps.codePath.isDirectory()) { 1862 FileUtils.deleteContents(ps.codePath); 1863 } 1864 ps.codePath.delete(); 1865 } 1866 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 1867 if (ps.resourcePath.isDirectory()) { 1868 FileUtils.deleteContents(ps.resourcePath); 1869 } 1870 ps.resourcePath.delete(); 1871 } 1872 mSettings.removePackageLPw(ps.name); 1873 } 1874 1875 static int[] appendInts(int[] cur, int[] add) { 1876 if (add == null) return cur; 1877 if (cur == null) return add; 1878 final int N = add.length; 1879 for (int i=0; i<N; i++) { 1880 cur = appendInt(cur, add[i]); 1881 } 1882 return cur; 1883 } 1884 1885 static int[] removeInts(int[] cur, int[] rem) { 1886 if (rem == null) return cur; 1887 if (cur == null) return cur; 1888 final int N = rem.length; 1889 for (int i=0; i<N; i++) { 1890 cur = removeInt(cur, rem[i]); 1891 } 1892 return cur; 1893 } 1894 1895 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1896 if (!sUserManager.exists(userId)) return null; 1897 final PackageSetting ps = (PackageSetting) p.mExtras; 1898 if (ps == null) { 1899 return null; 1900 } 1901 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1902 final PackageUserState state = ps.readUserState(userId); 1903 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1904 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1905 state, userId); 1906 } 1907 1908 @Override 1909 public boolean isPackageAvailable(String packageName, int userId) { 1910 if (!sUserManager.exists(userId)) return false; 1911 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 1912 synchronized (mPackages) { 1913 PackageParser.Package p = mPackages.get(packageName); 1914 if (p != null) { 1915 final PackageSetting ps = (PackageSetting) p.mExtras; 1916 if (ps != null) { 1917 final PackageUserState state = ps.readUserState(userId); 1918 if (state != null) { 1919 return PackageParser.isAvailable(state); 1920 } 1921 } 1922 } 1923 } 1924 return false; 1925 } 1926 1927 @Override 1928 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1929 if (!sUserManager.exists(userId)) return null; 1930 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 1931 // reader 1932 synchronized (mPackages) { 1933 PackageParser.Package p = mPackages.get(packageName); 1934 if (DEBUG_PACKAGE_INFO) 1935 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1936 if (p != null) { 1937 return generatePackageInfo(p, flags, userId); 1938 } 1939 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1940 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1941 } 1942 } 1943 return null; 1944 } 1945 1946 @Override 1947 public String[] currentToCanonicalPackageNames(String[] names) { 1948 String[] out = new String[names.length]; 1949 // reader 1950 synchronized (mPackages) { 1951 for (int i=names.length-1; i>=0; i--) { 1952 PackageSetting ps = mSettings.mPackages.get(names[i]); 1953 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1954 } 1955 } 1956 return out; 1957 } 1958 1959 @Override 1960 public String[] canonicalToCurrentPackageNames(String[] names) { 1961 String[] out = new String[names.length]; 1962 // reader 1963 synchronized (mPackages) { 1964 for (int i=names.length-1; i>=0; i--) { 1965 String cur = mSettings.mRenamedPackages.get(names[i]); 1966 out[i] = cur != null ? cur : names[i]; 1967 } 1968 } 1969 return out; 1970 } 1971 1972 @Override 1973 public int getPackageUid(String packageName, int userId) { 1974 if (!sUserManager.exists(userId)) return -1; 1975 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 1976 // reader 1977 synchronized (mPackages) { 1978 PackageParser.Package p = mPackages.get(packageName); 1979 if(p != null) { 1980 return UserHandle.getUid(userId, p.applicationInfo.uid); 1981 } 1982 PackageSetting ps = mSettings.mPackages.get(packageName); 1983 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1984 return -1; 1985 } 1986 p = ps.pkg; 1987 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1988 } 1989 } 1990 1991 @Override 1992 public int[] getPackageGids(String packageName) { 1993 // reader 1994 synchronized (mPackages) { 1995 PackageParser.Package p = mPackages.get(packageName); 1996 if (DEBUG_PACKAGE_INFO) 1997 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1998 if (p != null) { 1999 final PackageSetting ps = (PackageSetting)p.mExtras; 2000 return ps.getGids(); 2001 } 2002 } 2003 // stupid thing to indicate an error. 2004 return new int[0]; 2005 } 2006 2007 static final PermissionInfo generatePermissionInfo( 2008 BasePermission bp, int flags) { 2009 if (bp.perm != null) { 2010 return PackageParser.generatePermissionInfo(bp.perm, flags); 2011 } 2012 PermissionInfo pi = new PermissionInfo(); 2013 pi.name = bp.name; 2014 pi.packageName = bp.sourcePackage; 2015 pi.nonLocalizedLabel = bp.name; 2016 pi.protectionLevel = bp.protectionLevel; 2017 return pi; 2018 } 2019 2020 @Override 2021 public PermissionInfo getPermissionInfo(String name, int flags) { 2022 // reader 2023 synchronized (mPackages) { 2024 final BasePermission p = mSettings.mPermissions.get(name); 2025 if (p != null) { 2026 return generatePermissionInfo(p, flags); 2027 } 2028 return null; 2029 } 2030 } 2031 2032 @Override 2033 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2034 // reader 2035 synchronized (mPackages) { 2036 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2037 for (BasePermission p : mSettings.mPermissions.values()) { 2038 if (group == null) { 2039 if (p.perm == null || p.perm.info.group == null) { 2040 out.add(generatePermissionInfo(p, flags)); 2041 } 2042 } else { 2043 if (p.perm != null && group.equals(p.perm.info.group)) { 2044 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2045 } 2046 } 2047 } 2048 2049 if (out.size() > 0) { 2050 return out; 2051 } 2052 return mPermissionGroups.containsKey(group) ? out : null; 2053 } 2054 } 2055 2056 @Override 2057 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2058 // reader 2059 synchronized (mPackages) { 2060 return PackageParser.generatePermissionGroupInfo( 2061 mPermissionGroups.get(name), flags); 2062 } 2063 } 2064 2065 @Override 2066 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2067 // reader 2068 synchronized (mPackages) { 2069 final int N = mPermissionGroups.size(); 2070 ArrayList<PermissionGroupInfo> out 2071 = new ArrayList<PermissionGroupInfo>(N); 2072 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2073 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2074 } 2075 return out; 2076 } 2077 } 2078 2079 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2080 int userId) { 2081 if (!sUserManager.exists(userId)) return null; 2082 PackageSetting ps = mSettings.mPackages.get(packageName); 2083 if (ps != null) { 2084 if (ps.pkg == null) { 2085 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2086 flags, userId); 2087 if (pInfo != null) { 2088 return pInfo.applicationInfo; 2089 } 2090 return null; 2091 } 2092 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2093 ps.readUserState(userId), userId); 2094 } 2095 return null; 2096 } 2097 2098 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2099 int userId) { 2100 if (!sUserManager.exists(userId)) return null; 2101 PackageSetting ps = mSettings.mPackages.get(packageName); 2102 if (ps != null) { 2103 PackageParser.Package pkg = ps.pkg; 2104 if (pkg == null) { 2105 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2106 return null; 2107 } 2108 // Only data remains, so we aren't worried about code paths 2109 pkg = new PackageParser.Package(packageName); 2110 pkg.applicationInfo.packageName = packageName; 2111 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2112 pkg.applicationInfo.dataDir = 2113 getDataPathForPackage(packageName, 0).getPath(); 2114 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2115 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2116 } 2117 return generatePackageInfo(pkg, flags, userId); 2118 } 2119 return null; 2120 } 2121 2122 @Override 2123 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2124 if (!sUserManager.exists(userId)) return null; 2125 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2126 // writer 2127 synchronized (mPackages) { 2128 PackageParser.Package p = mPackages.get(packageName); 2129 if (DEBUG_PACKAGE_INFO) Log.v( 2130 TAG, "getApplicationInfo " + packageName 2131 + ": " + p); 2132 if (p != null) { 2133 PackageSetting ps = mSettings.mPackages.get(packageName); 2134 if (ps == null) return null; 2135 // Note: isEnabledLP() does not apply here - always return info 2136 return PackageParser.generateApplicationInfo( 2137 p, flags, ps.readUserState(userId), userId); 2138 } 2139 if ("android".equals(packageName)||"system".equals(packageName)) { 2140 return mAndroidApplication; 2141 } 2142 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2143 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2144 } 2145 } 2146 return null; 2147 } 2148 2149 2150 @Override 2151 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2152 mContext.enforceCallingOrSelfPermission( 2153 android.Manifest.permission.CLEAR_APP_CACHE, null); 2154 // Queue up an async operation since clearing cache may take a little while. 2155 mHandler.post(new Runnable() { 2156 public void run() { 2157 mHandler.removeCallbacks(this); 2158 int retCode = -1; 2159 synchronized (mInstallLock) { 2160 retCode = mInstaller.freeCache(freeStorageSize); 2161 if (retCode < 0) { 2162 Slog.w(TAG, "Couldn't clear application caches"); 2163 } 2164 } 2165 if (observer != null) { 2166 try { 2167 observer.onRemoveCompleted(null, (retCode >= 0)); 2168 } catch (RemoteException e) { 2169 Slog.w(TAG, "RemoveException when invoking call back"); 2170 } 2171 } 2172 } 2173 }); 2174 } 2175 2176 @Override 2177 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2178 mContext.enforceCallingOrSelfPermission( 2179 android.Manifest.permission.CLEAR_APP_CACHE, null); 2180 // Queue up an async operation since clearing cache may take a little while. 2181 mHandler.post(new Runnable() { 2182 public void run() { 2183 mHandler.removeCallbacks(this); 2184 int retCode = -1; 2185 synchronized (mInstallLock) { 2186 retCode = mInstaller.freeCache(freeStorageSize); 2187 if (retCode < 0) { 2188 Slog.w(TAG, "Couldn't clear application caches"); 2189 } 2190 } 2191 if(pi != null) { 2192 try { 2193 // Callback via pending intent 2194 int code = (retCode >= 0) ? 1 : 0; 2195 pi.sendIntent(null, code, null, 2196 null, null); 2197 } catch (SendIntentException e1) { 2198 Slog.i(TAG, "Failed to send pending intent"); 2199 } 2200 } 2201 } 2202 }); 2203 } 2204 2205 void freeStorage(long freeStorageSize) throws IOException { 2206 synchronized (mInstallLock) { 2207 if (mInstaller.freeCache(freeStorageSize) < 0) { 2208 throw new IOException("Failed to free enough space"); 2209 } 2210 } 2211 } 2212 2213 @Override 2214 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2215 if (!sUserManager.exists(userId)) return null; 2216 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2217 synchronized (mPackages) { 2218 PackageParser.Activity a = mActivities.mActivities.get(component); 2219 2220 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2221 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2222 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2223 if (ps == null) return null; 2224 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2225 userId); 2226 } 2227 if (mResolveComponentName.equals(component)) { 2228 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2229 new PackageUserState(), userId); 2230 } 2231 } 2232 return null; 2233 } 2234 2235 @Override 2236 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2237 String resolvedType) { 2238 synchronized (mPackages) { 2239 PackageParser.Activity a = mActivities.mActivities.get(component); 2240 if (a == null) { 2241 return false; 2242 } 2243 for (int i=0; i<a.intents.size(); i++) { 2244 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2245 intent.getData(), intent.getCategories(), TAG) >= 0) { 2246 return true; 2247 } 2248 } 2249 return false; 2250 } 2251 } 2252 2253 @Override 2254 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2255 if (!sUserManager.exists(userId)) return null; 2256 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2257 synchronized (mPackages) { 2258 PackageParser.Activity a = mReceivers.mActivities.get(component); 2259 if (DEBUG_PACKAGE_INFO) Log.v( 2260 TAG, "getReceiverInfo " + component + ": " + a); 2261 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2262 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2263 if (ps == null) return null; 2264 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2265 userId); 2266 } 2267 } 2268 return null; 2269 } 2270 2271 @Override 2272 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2273 if (!sUserManager.exists(userId)) return null; 2274 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2275 synchronized (mPackages) { 2276 PackageParser.Service s = mServices.mServices.get(component); 2277 if (DEBUG_PACKAGE_INFO) Log.v( 2278 TAG, "getServiceInfo " + component + ": " + s); 2279 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2280 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2281 if (ps == null) return null; 2282 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2283 userId); 2284 } 2285 } 2286 return null; 2287 } 2288 2289 @Override 2290 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2291 if (!sUserManager.exists(userId)) return null; 2292 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2293 synchronized (mPackages) { 2294 PackageParser.Provider p = mProviders.mProviders.get(component); 2295 if (DEBUG_PACKAGE_INFO) Log.v( 2296 TAG, "getProviderInfo " + component + ": " + p); 2297 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2298 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2299 if (ps == null) return null; 2300 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2301 userId); 2302 } 2303 } 2304 return null; 2305 } 2306 2307 @Override 2308 public String[] getSystemSharedLibraryNames() { 2309 Set<String> libSet; 2310 synchronized (mPackages) { 2311 libSet = mSharedLibraries.keySet(); 2312 int size = libSet.size(); 2313 if (size > 0) { 2314 String[] libs = new String[size]; 2315 libSet.toArray(libs); 2316 return libs; 2317 } 2318 } 2319 return null; 2320 } 2321 2322 @Override 2323 public FeatureInfo[] getSystemAvailableFeatures() { 2324 Collection<FeatureInfo> featSet; 2325 synchronized (mPackages) { 2326 featSet = mAvailableFeatures.values(); 2327 int size = featSet.size(); 2328 if (size > 0) { 2329 FeatureInfo[] features = new FeatureInfo[size+1]; 2330 featSet.toArray(features); 2331 FeatureInfo fi = new FeatureInfo(); 2332 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2333 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2334 features[size] = fi; 2335 return features; 2336 } 2337 } 2338 return null; 2339 } 2340 2341 @Override 2342 public boolean hasSystemFeature(String name) { 2343 synchronized (mPackages) { 2344 return mAvailableFeatures.containsKey(name); 2345 } 2346 } 2347 2348 private void checkValidCaller(int uid, int userId) { 2349 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2350 return; 2351 2352 throw new SecurityException("Caller uid=" + uid 2353 + " is not privileged to communicate with user=" + userId); 2354 } 2355 2356 @Override 2357 public int checkPermission(String permName, String pkgName) { 2358 synchronized (mPackages) { 2359 PackageParser.Package p = mPackages.get(pkgName); 2360 if (p != null && p.mExtras != null) { 2361 PackageSetting ps = (PackageSetting)p.mExtras; 2362 if (ps.sharedUser != null) { 2363 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2364 return PackageManager.PERMISSION_GRANTED; 2365 } 2366 } else if (ps.grantedPermissions.contains(permName)) { 2367 return PackageManager.PERMISSION_GRANTED; 2368 } 2369 } 2370 } 2371 return PackageManager.PERMISSION_DENIED; 2372 } 2373 2374 @Override 2375 public int checkUidPermission(String permName, int uid) { 2376 synchronized (mPackages) { 2377 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2378 if (obj != null) { 2379 GrantedPermissions gp = (GrantedPermissions)obj; 2380 if (gp.grantedPermissions.contains(permName)) { 2381 return PackageManager.PERMISSION_GRANTED; 2382 } 2383 } else { 2384 ArraySet<String> perms = mSystemPermissions.get(uid); 2385 if (perms != null && perms.contains(permName)) { 2386 return PackageManager.PERMISSION_GRANTED; 2387 } 2388 } 2389 } 2390 return PackageManager.PERMISSION_DENIED; 2391 } 2392 2393 /** 2394 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2395 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2396 * @param checkShell TODO(yamasani): 2397 * @param message the message to log on security exception 2398 */ 2399 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2400 boolean checkShell, String message) { 2401 if (userId < 0) { 2402 throw new IllegalArgumentException("Invalid userId " + userId); 2403 } 2404 if (checkShell) { 2405 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2406 } 2407 if (userId == UserHandle.getUserId(callingUid)) return; 2408 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2409 if (requireFullPermission) { 2410 mContext.enforceCallingOrSelfPermission( 2411 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2412 } else { 2413 try { 2414 mContext.enforceCallingOrSelfPermission( 2415 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2416 } catch (SecurityException se) { 2417 mContext.enforceCallingOrSelfPermission( 2418 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2419 } 2420 } 2421 } 2422 } 2423 2424 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2425 if (callingUid == Process.SHELL_UID) { 2426 if (userHandle >= 0 2427 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2428 throw new SecurityException("Shell does not have permission to access user " 2429 + userHandle); 2430 } else if (userHandle < 0) { 2431 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2432 + Debug.getCallers(3)); 2433 } 2434 } 2435 } 2436 2437 private BasePermission findPermissionTreeLP(String permName) { 2438 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2439 if (permName.startsWith(bp.name) && 2440 permName.length() > bp.name.length() && 2441 permName.charAt(bp.name.length()) == '.') { 2442 return bp; 2443 } 2444 } 2445 return null; 2446 } 2447 2448 private BasePermission checkPermissionTreeLP(String permName) { 2449 if (permName != null) { 2450 BasePermission bp = findPermissionTreeLP(permName); 2451 if (bp != null) { 2452 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2453 return bp; 2454 } 2455 throw new SecurityException("Calling uid " 2456 + Binder.getCallingUid() 2457 + " is not allowed to add to permission tree " 2458 + bp.name + " owned by uid " + bp.uid); 2459 } 2460 } 2461 throw new SecurityException("No permission tree found for " + permName); 2462 } 2463 2464 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2465 if (s1 == null) { 2466 return s2 == null; 2467 } 2468 if (s2 == null) { 2469 return false; 2470 } 2471 if (s1.getClass() != s2.getClass()) { 2472 return false; 2473 } 2474 return s1.equals(s2); 2475 } 2476 2477 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2478 if (pi1.icon != pi2.icon) return false; 2479 if (pi1.logo != pi2.logo) return false; 2480 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2481 if (!compareStrings(pi1.name, pi2.name)) return false; 2482 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2483 // We'll take care of setting this one. 2484 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2485 // These are not currently stored in settings. 2486 //if (!compareStrings(pi1.group, pi2.group)) return false; 2487 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2488 //if (pi1.labelRes != pi2.labelRes) return false; 2489 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2490 return true; 2491 } 2492 2493 int permissionInfoFootprint(PermissionInfo info) { 2494 int size = info.name.length(); 2495 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2496 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2497 return size; 2498 } 2499 2500 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2501 int size = 0; 2502 for (BasePermission perm : mSettings.mPermissions.values()) { 2503 if (perm.uid == tree.uid) { 2504 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2505 } 2506 } 2507 return size; 2508 } 2509 2510 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2511 // We calculate the max size of permissions defined by this uid and throw 2512 // if that plus the size of 'info' would exceed our stated maximum. 2513 if (tree.uid != Process.SYSTEM_UID) { 2514 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2515 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2516 throw new SecurityException("Permission tree size cap exceeded"); 2517 } 2518 } 2519 } 2520 2521 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2522 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2523 throw new SecurityException("Label must be specified in permission"); 2524 } 2525 BasePermission tree = checkPermissionTreeLP(info.name); 2526 BasePermission bp = mSettings.mPermissions.get(info.name); 2527 boolean added = bp == null; 2528 boolean changed = true; 2529 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2530 if (added) { 2531 enforcePermissionCapLocked(info, tree); 2532 bp = new BasePermission(info.name, tree.sourcePackage, 2533 BasePermission.TYPE_DYNAMIC); 2534 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2535 throw new SecurityException( 2536 "Not allowed to modify non-dynamic permission " 2537 + info.name); 2538 } else { 2539 if (bp.protectionLevel == fixedLevel 2540 && bp.perm.owner.equals(tree.perm.owner) 2541 && bp.uid == tree.uid 2542 && comparePermissionInfos(bp.perm.info, info)) { 2543 changed = false; 2544 } 2545 } 2546 bp.protectionLevel = fixedLevel; 2547 info = new PermissionInfo(info); 2548 info.protectionLevel = fixedLevel; 2549 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2550 bp.perm.info.packageName = tree.perm.info.packageName; 2551 bp.uid = tree.uid; 2552 if (added) { 2553 mSettings.mPermissions.put(info.name, bp); 2554 } 2555 if (changed) { 2556 if (!async) { 2557 mSettings.writeLPr(); 2558 } else { 2559 scheduleWriteSettingsLocked(); 2560 } 2561 } 2562 return added; 2563 } 2564 2565 @Override 2566 public boolean addPermission(PermissionInfo info) { 2567 synchronized (mPackages) { 2568 return addPermissionLocked(info, false); 2569 } 2570 } 2571 2572 @Override 2573 public boolean addPermissionAsync(PermissionInfo info) { 2574 synchronized (mPackages) { 2575 return addPermissionLocked(info, true); 2576 } 2577 } 2578 2579 @Override 2580 public void removePermission(String name) { 2581 synchronized (mPackages) { 2582 checkPermissionTreeLP(name); 2583 BasePermission bp = mSettings.mPermissions.get(name); 2584 if (bp != null) { 2585 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2586 throw new SecurityException( 2587 "Not allowed to modify non-dynamic permission " 2588 + name); 2589 } 2590 mSettings.mPermissions.remove(name); 2591 mSettings.writeLPr(); 2592 } 2593 } 2594 } 2595 2596 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2597 int index = pkg.requestedPermissions.indexOf(bp.name); 2598 if (index == -1) { 2599 throw new SecurityException("Package " + pkg.packageName 2600 + " has not requested permission " + bp.name); 2601 } 2602 boolean isNormal = 2603 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2604 == PermissionInfo.PROTECTION_NORMAL); 2605 boolean isDangerous = 2606 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2607 == PermissionInfo.PROTECTION_DANGEROUS); 2608 boolean isDevelopment = 2609 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2610 2611 if (!isNormal && !isDangerous && !isDevelopment) { 2612 throw new SecurityException("Permission " + bp.name 2613 + " is not a changeable permission type"); 2614 } 2615 2616 if (isNormal || isDangerous) { 2617 if (pkg.requestedPermissionsRequired.get(index)) { 2618 throw new SecurityException("Can't change " + bp.name 2619 + ". It is required by the application"); 2620 } 2621 } 2622 } 2623 2624 @Override 2625 public void grantPermission(String packageName, String permissionName) { 2626 mContext.enforceCallingOrSelfPermission( 2627 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2628 synchronized (mPackages) { 2629 final PackageParser.Package pkg = mPackages.get(packageName); 2630 if (pkg == null) { 2631 throw new IllegalArgumentException("Unknown package: " + packageName); 2632 } 2633 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2634 if (bp == null) { 2635 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2636 } 2637 2638 checkGrantRevokePermissions(pkg, bp); 2639 2640 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2641 if (ps == null) { 2642 return; 2643 } 2644 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2645 if (gp.grantedPermissions.add(permissionName)) { 2646 if (ps.haveGids) { 2647 gp.gids = appendInts(gp.gids, bp.gids); 2648 } 2649 mSettings.writeLPr(); 2650 } 2651 } 2652 } 2653 2654 @Override 2655 public void revokePermission(String packageName, String permissionName) { 2656 int changedAppId = -1; 2657 2658 synchronized (mPackages) { 2659 final PackageParser.Package pkg = mPackages.get(packageName); 2660 if (pkg == null) { 2661 throw new IllegalArgumentException("Unknown package: " + packageName); 2662 } 2663 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2664 mContext.enforceCallingOrSelfPermission( 2665 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2666 } 2667 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2668 if (bp == null) { 2669 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2670 } 2671 2672 checkGrantRevokePermissions(pkg, bp); 2673 2674 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2675 if (ps == null) { 2676 return; 2677 } 2678 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2679 if (gp.grantedPermissions.remove(permissionName)) { 2680 gp.grantedPermissions.remove(permissionName); 2681 if (ps.haveGids) { 2682 gp.gids = removeInts(gp.gids, bp.gids); 2683 } 2684 mSettings.writeLPr(); 2685 changedAppId = ps.appId; 2686 } 2687 } 2688 2689 if (changedAppId >= 0) { 2690 // We changed the perm on someone, kill its processes. 2691 IActivityManager am = ActivityManagerNative.getDefault(); 2692 if (am != null) { 2693 final int callingUserId = UserHandle.getCallingUserId(); 2694 final long ident = Binder.clearCallingIdentity(); 2695 try { 2696 //XXX we should only revoke for the calling user's app permissions, 2697 // but for now we impact all users. 2698 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2699 // "revoke " + permissionName); 2700 int[] users = sUserManager.getUserIds(); 2701 for (int user : users) { 2702 am.killUid(UserHandle.getUid(user, changedAppId), 2703 "revoke " + permissionName); 2704 } 2705 } catch (RemoteException e) { 2706 } finally { 2707 Binder.restoreCallingIdentity(ident); 2708 } 2709 } 2710 } 2711 } 2712 2713 @Override 2714 public boolean isProtectedBroadcast(String actionName) { 2715 synchronized (mPackages) { 2716 return mProtectedBroadcasts.contains(actionName); 2717 } 2718 } 2719 2720 @Override 2721 public int checkSignatures(String pkg1, String pkg2) { 2722 synchronized (mPackages) { 2723 final PackageParser.Package p1 = mPackages.get(pkg1); 2724 final PackageParser.Package p2 = mPackages.get(pkg2); 2725 if (p1 == null || p1.mExtras == null 2726 || p2 == null || p2.mExtras == null) { 2727 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2728 } 2729 return compareSignatures(p1.mSignatures, p2.mSignatures); 2730 } 2731 } 2732 2733 @Override 2734 public int checkUidSignatures(int uid1, int uid2) { 2735 // Map to base uids. 2736 uid1 = UserHandle.getAppId(uid1); 2737 uid2 = UserHandle.getAppId(uid2); 2738 // reader 2739 synchronized (mPackages) { 2740 Signature[] s1; 2741 Signature[] s2; 2742 Object obj = mSettings.getUserIdLPr(uid1); 2743 if (obj != null) { 2744 if (obj instanceof SharedUserSetting) { 2745 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2746 } else if (obj instanceof PackageSetting) { 2747 s1 = ((PackageSetting)obj).signatures.mSignatures; 2748 } else { 2749 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2750 } 2751 } else { 2752 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2753 } 2754 obj = mSettings.getUserIdLPr(uid2); 2755 if (obj != null) { 2756 if (obj instanceof SharedUserSetting) { 2757 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2758 } else if (obj instanceof PackageSetting) { 2759 s2 = ((PackageSetting)obj).signatures.mSignatures; 2760 } else { 2761 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2762 } 2763 } else { 2764 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2765 } 2766 return compareSignatures(s1, s2); 2767 } 2768 } 2769 2770 /** 2771 * Compares two sets of signatures. Returns: 2772 * <br /> 2773 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2774 * <br /> 2775 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2776 * <br /> 2777 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2778 * <br /> 2779 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2780 * <br /> 2781 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2782 */ 2783 static int compareSignatures(Signature[] s1, Signature[] s2) { 2784 if (s1 == null) { 2785 return s2 == null 2786 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2787 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2788 } 2789 2790 if (s2 == null) { 2791 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2792 } 2793 2794 if (s1.length != s2.length) { 2795 return PackageManager.SIGNATURE_NO_MATCH; 2796 } 2797 2798 // Since both signature sets are of size 1, we can compare without HashSets. 2799 if (s1.length == 1) { 2800 return s1[0].equals(s2[0]) ? 2801 PackageManager.SIGNATURE_MATCH : 2802 PackageManager.SIGNATURE_NO_MATCH; 2803 } 2804 2805 ArraySet<Signature> set1 = new ArraySet<Signature>(); 2806 for (Signature sig : s1) { 2807 set1.add(sig); 2808 } 2809 ArraySet<Signature> set2 = new ArraySet<Signature>(); 2810 for (Signature sig : s2) { 2811 set2.add(sig); 2812 } 2813 // Make sure s2 contains all signatures in s1. 2814 if (set1.equals(set2)) { 2815 return PackageManager.SIGNATURE_MATCH; 2816 } 2817 return PackageManager.SIGNATURE_NO_MATCH; 2818 } 2819 2820 /** 2821 * If the database version for this type of package (internal storage or 2822 * external storage) is less than the version where package signatures 2823 * were updated, return true. 2824 */ 2825 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2826 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2827 DatabaseVersion.SIGNATURE_END_ENTITY)) 2828 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2829 DatabaseVersion.SIGNATURE_END_ENTITY)); 2830 } 2831 2832 /** 2833 * Used for backward compatibility to make sure any packages with 2834 * certificate chains get upgraded to the new style. {@code existingSigs} 2835 * will be in the old format (since they were stored on disk from before the 2836 * system upgrade) and {@code scannedSigs} will be in the newer format. 2837 */ 2838 private int compareSignaturesCompat(PackageSignatures existingSigs, 2839 PackageParser.Package scannedPkg) { 2840 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2841 return PackageManager.SIGNATURE_NO_MATCH; 2842 } 2843 2844 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 2845 for (Signature sig : existingSigs.mSignatures) { 2846 existingSet.add(sig); 2847 } 2848 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 2849 for (Signature sig : scannedPkg.mSignatures) { 2850 try { 2851 Signature[] chainSignatures = sig.getChainSignatures(); 2852 for (Signature chainSig : chainSignatures) { 2853 scannedCompatSet.add(chainSig); 2854 } 2855 } catch (CertificateEncodingException e) { 2856 scannedCompatSet.add(sig); 2857 } 2858 } 2859 /* 2860 * Make sure the expanded scanned set contains all signatures in the 2861 * existing one. 2862 */ 2863 if (scannedCompatSet.equals(existingSet)) { 2864 // Migrate the old signatures to the new scheme. 2865 existingSigs.assignSignatures(scannedPkg.mSignatures); 2866 // The new KeySets will be re-added later in the scanning process. 2867 synchronized (mPackages) { 2868 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2869 } 2870 return PackageManager.SIGNATURE_MATCH; 2871 } 2872 return PackageManager.SIGNATURE_NO_MATCH; 2873 } 2874 2875 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2876 if (isExternal(scannedPkg)) { 2877 return mSettings.isExternalDatabaseVersionOlderThan( 2878 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 2879 } else { 2880 return mSettings.isInternalDatabaseVersionOlderThan( 2881 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 2882 } 2883 } 2884 2885 private int compareSignaturesRecover(PackageSignatures existingSigs, 2886 PackageParser.Package scannedPkg) { 2887 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 2888 return PackageManager.SIGNATURE_NO_MATCH; 2889 } 2890 2891 String msg = null; 2892 try { 2893 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 2894 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 2895 + scannedPkg.packageName); 2896 return PackageManager.SIGNATURE_MATCH; 2897 } 2898 } catch (CertificateException e) { 2899 msg = e.getMessage(); 2900 } 2901 2902 logCriticalInfo(Log.INFO, 2903 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 2904 return PackageManager.SIGNATURE_NO_MATCH; 2905 } 2906 2907 @Override 2908 public String[] getPackagesForUid(int uid) { 2909 uid = UserHandle.getAppId(uid); 2910 // reader 2911 synchronized (mPackages) { 2912 Object obj = mSettings.getUserIdLPr(uid); 2913 if (obj instanceof SharedUserSetting) { 2914 final SharedUserSetting sus = (SharedUserSetting) obj; 2915 final int N = sus.packages.size(); 2916 final String[] res = new String[N]; 2917 final Iterator<PackageSetting> it = sus.packages.iterator(); 2918 int i = 0; 2919 while (it.hasNext()) { 2920 res[i++] = it.next().name; 2921 } 2922 return res; 2923 } else if (obj instanceof PackageSetting) { 2924 final PackageSetting ps = (PackageSetting) obj; 2925 return new String[] { ps.name }; 2926 } 2927 } 2928 return null; 2929 } 2930 2931 @Override 2932 public String getNameForUid(int uid) { 2933 // reader 2934 synchronized (mPackages) { 2935 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2936 if (obj instanceof SharedUserSetting) { 2937 final SharedUserSetting sus = (SharedUserSetting) obj; 2938 return sus.name + ":" + sus.userId; 2939 } else if (obj instanceof PackageSetting) { 2940 final PackageSetting ps = (PackageSetting) obj; 2941 return ps.name; 2942 } 2943 } 2944 return null; 2945 } 2946 2947 @Override 2948 public int getUidForSharedUser(String sharedUserName) { 2949 if(sharedUserName == null) { 2950 return -1; 2951 } 2952 // reader 2953 synchronized (mPackages) { 2954 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2955 if (suid == null) { 2956 return -1; 2957 } 2958 return suid.userId; 2959 } 2960 } 2961 2962 @Override 2963 public int getFlagsForUid(int uid) { 2964 synchronized (mPackages) { 2965 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2966 if (obj instanceof SharedUserSetting) { 2967 final SharedUserSetting sus = (SharedUserSetting) obj; 2968 return sus.pkgFlags; 2969 } else if (obj instanceof PackageSetting) { 2970 final PackageSetting ps = (PackageSetting) obj; 2971 return ps.pkgFlags; 2972 } 2973 } 2974 return 0; 2975 } 2976 2977 @Override 2978 public boolean isUidPrivileged(int uid) { 2979 uid = UserHandle.getAppId(uid); 2980 // reader 2981 synchronized (mPackages) { 2982 Object obj = mSettings.getUserIdLPr(uid); 2983 if (obj instanceof SharedUserSetting) { 2984 final SharedUserSetting sus = (SharedUserSetting) obj; 2985 final Iterator<PackageSetting> it = sus.packages.iterator(); 2986 while (it.hasNext()) { 2987 if (it.next().isPrivileged()) { 2988 return true; 2989 } 2990 } 2991 } else if (obj instanceof PackageSetting) { 2992 final PackageSetting ps = (PackageSetting) obj; 2993 return ps.isPrivileged(); 2994 } 2995 } 2996 return false; 2997 } 2998 2999 @Override 3000 public String[] getAppOpPermissionPackages(String permissionName) { 3001 synchronized (mPackages) { 3002 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3003 if (pkgs == null) { 3004 return null; 3005 } 3006 return pkgs.toArray(new String[pkgs.size()]); 3007 } 3008 } 3009 3010 @Override 3011 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3012 int flags, int userId) { 3013 if (!sUserManager.exists(userId)) return null; 3014 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3015 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3016 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3017 } 3018 3019 @Override 3020 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3021 IntentFilter filter, int match, ComponentName activity) { 3022 final int userId = UserHandle.getCallingUserId(); 3023 if (DEBUG_PREFERRED) { 3024 Log.v(TAG, "setLastChosenActivity intent=" + intent 3025 + " resolvedType=" + resolvedType 3026 + " flags=" + flags 3027 + " filter=" + filter 3028 + " match=" + match 3029 + " activity=" + activity); 3030 filter.dump(new PrintStreamPrinter(System.out), " "); 3031 } 3032 intent.setComponent(null); 3033 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3034 // Find any earlier preferred or last chosen entries and nuke them 3035 findPreferredActivity(intent, resolvedType, 3036 flags, query, 0, false, true, false, userId); 3037 // Add the new activity as the last chosen for this filter 3038 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3039 "Setting last chosen"); 3040 } 3041 3042 @Override 3043 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3044 final int userId = UserHandle.getCallingUserId(); 3045 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3046 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3047 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3048 false, false, false, userId); 3049 } 3050 3051 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3052 int flags, List<ResolveInfo> query, int userId) { 3053 if (query != null) { 3054 final int N = query.size(); 3055 if (N == 1) { 3056 return query.get(0); 3057 } else if (N > 1) { 3058 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3059 // If there is more than one activity with the same priority, 3060 // then let the user decide between them. 3061 ResolveInfo r0 = query.get(0); 3062 ResolveInfo r1 = query.get(1); 3063 if (DEBUG_INTENT_MATCHING || debug) { 3064 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3065 + r1.activityInfo.name + "=" + r1.priority); 3066 } 3067 // If the first activity has a higher priority, or a different 3068 // default, then it is always desireable to pick it. 3069 if (r0.priority != r1.priority 3070 || r0.preferredOrder != r1.preferredOrder 3071 || r0.isDefault != r1.isDefault) { 3072 return query.get(0); 3073 } 3074 // If we have saved a preference for a preferred activity for 3075 // this Intent, use that. 3076 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3077 flags, query, r0.priority, true, false, debug, userId); 3078 if (ri != null) { 3079 return ri; 3080 } 3081 if (userId != 0) { 3082 ri = new ResolveInfo(mResolveInfo); 3083 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3084 ri.activityInfo.applicationInfo = new ApplicationInfo( 3085 ri.activityInfo.applicationInfo); 3086 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3087 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3088 return ri; 3089 } 3090 return mResolveInfo; 3091 } 3092 } 3093 return null; 3094 } 3095 3096 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3097 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3098 final int N = query.size(); 3099 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3100 .get(userId); 3101 // Get the list of persistent preferred activities that handle the intent 3102 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3103 List<PersistentPreferredActivity> pprefs = ppir != null 3104 ? ppir.queryIntent(intent, resolvedType, 3105 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3106 : null; 3107 if (pprefs != null && pprefs.size() > 0) { 3108 final int M = pprefs.size(); 3109 for (int i=0; i<M; i++) { 3110 final PersistentPreferredActivity ppa = pprefs.get(i); 3111 if (DEBUG_PREFERRED || debug) { 3112 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3113 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3114 + "\n component=" + ppa.mComponent); 3115 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3116 } 3117 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3118 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3119 if (DEBUG_PREFERRED || debug) { 3120 Slog.v(TAG, "Found persistent preferred activity:"); 3121 if (ai != null) { 3122 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3123 } else { 3124 Slog.v(TAG, " null"); 3125 } 3126 } 3127 if (ai == null) { 3128 // This previously registered persistent preferred activity 3129 // component is no longer known. Ignore it and do NOT remove it. 3130 continue; 3131 } 3132 for (int j=0; j<N; j++) { 3133 final ResolveInfo ri = query.get(j); 3134 if (!ri.activityInfo.applicationInfo.packageName 3135 .equals(ai.applicationInfo.packageName)) { 3136 continue; 3137 } 3138 if (!ri.activityInfo.name.equals(ai.name)) { 3139 continue; 3140 } 3141 // Found a persistent preference that can handle the intent. 3142 if (DEBUG_PREFERRED || debug) { 3143 Slog.v(TAG, "Returning persistent preferred activity: " + 3144 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3145 } 3146 return ri; 3147 } 3148 } 3149 } 3150 return null; 3151 } 3152 3153 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3154 List<ResolveInfo> query, int priority, boolean always, 3155 boolean removeMatches, boolean debug, int userId) { 3156 if (!sUserManager.exists(userId)) return null; 3157 // writer 3158 synchronized (mPackages) { 3159 if (intent.getSelector() != null) { 3160 intent = intent.getSelector(); 3161 } 3162 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3163 3164 // Try to find a matching persistent preferred activity. 3165 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3166 debug, userId); 3167 3168 // If a persistent preferred activity matched, use it. 3169 if (pri != null) { 3170 return pri; 3171 } 3172 3173 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3174 // Get the list of preferred activities that handle the intent 3175 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3176 List<PreferredActivity> prefs = pir != null 3177 ? pir.queryIntent(intent, resolvedType, 3178 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3179 : null; 3180 if (prefs != null && prefs.size() > 0) { 3181 boolean changed = false; 3182 try { 3183 // First figure out how good the original match set is. 3184 // We will only allow preferred activities that came 3185 // from the same match quality. 3186 int match = 0; 3187 3188 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3189 3190 final int N = query.size(); 3191 for (int j=0; j<N; j++) { 3192 final ResolveInfo ri = query.get(j); 3193 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3194 + ": 0x" + Integer.toHexString(match)); 3195 if (ri.match > match) { 3196 match = ri.match; 3197 } 3198 } 3199 3200 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3201 + Integer.toHexString(match)); 3202 3203 match &= IntentFilter.MATCH_CATEGORY_MASK; 3204 final int M = prefs.size(); 3205 for (int i=0; i<M; i++) { 3206 final PreferredActivity pa = prefs.get(i); 3207 if (DEBUG_PREFERRED || debug) { 3208 Slog.v(TAG, "Checking PreferredActivity ds=" 3209 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3210 + "\n component=" + pa.mPref.mComponent); 3211 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3212 } 3213 if (pa.mPref.mMatch != match) { 3214 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3215 + Integer.toHexString(pa.mPref.mMatch)); 3216 continue; 3217 } 3218 // If it's not an "always" type preferred activity and that's what we're 3219 // looking for, skip it. 3220 if (always && !pa.mPref.mAlways) { 3221 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3222 continue; 3223 } 3224 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3225 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3226 if (DEBUG_PREFERRED || debug) { 3227 Slog.v(TAG, "Found preferred activity:"); 3228 if (ai != null) { 3229 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3230 } else { 3231 Slog.v(TAG, " null"); 3232 } 3233 } 3234 if (ai == null) { 3235 // This previously registered preferred activity 3236 // component is no longer known. Most likely an update 3237 // to the app was installed and in the new version this 3238 // component no longer exists. Clean it up by removing 3239 // it from the preferred activities list, and skip it. 3240 Slog.w(TAG, "Removing dangling preferred activity: " 3241 + pa.mPref.mComponent); 3242 pir.removeFilter(pa); 3243 changed = true; 3244 continue; 3245 } 3246 for (int j=0; j<N; j++) { 3247 final ResolveInfo ri = query.get(j); 3248 if (!ri.activityInfo.applicationInfo.packageName 3249 .equals(ai.applicationInfo.packageName)) { 3250 continue; 3251 } 3252 if (!ri.activityInfo.name.equals(ai.name)) { 3253 continue; 3254 } 3255 3256 if (removeMatches) { 3257 pir.removeFilter(pa); 3258 changed = true; 3259 if (DEBUG_PREFERRED) { 3260 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3261 } 3262 break; 3263 } 3264 3265 // Okay we found a previously set preferred or last chosen app. 3266 // If the result set is different from when this 3267 // was created, we need to clear it and re-ask the 3268 // user their preference, if we're looking for an "always" type entry. 3269 if (always && !pa.mPref.sameSet(query, priority)) { 3270 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3271 + intent + " type " + resolvedType); 3272 if (DEBUG_PREFERRED) { 3273 Slog.v(TAG, "Removing preferred activity since set changed " 3274 + pa.mPref.mComponent); 3275 } 3276 pir.removeFilter(pa); 3277 // Re-add the filter as a "last chosen" entry (!always) 3278 PreferredActivity lastChosen = new PreferredActivity( 3279 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3280 pir.addFilter(lastChosen); 3281 changed = true; 3282 return null; 3283 } 3284 3285 // Yay! Either the set matched or we're looking for the last chosen 3286 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3287 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3288 return ri; 3289 } 3290 } 3291 } finally { 3292 if (changed) { 3293 if (DEBUG_PREFERRED) { 3294 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3295 } 3296 scheduleWritePackageRestrictionsLocked(userId); 3297 } 3298 } 3299 } 3300 } 3301 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3302 return null; 3303 } 3304 3305 /* 3306 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3307 */ 3308 @Override 3309 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3310 int targetUserId) { 3311 mContext.enforceCallingOrSelfPermission( 3312 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3313 List<CrossProfileIntentFilter> matches = 3314 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3315 if (matches != null) { 3316 int size = matches.size(); 3317 for (int i = 0; i < size; i++) { 3318 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3319 } 3320 } 3321 return false; 3322 } 3323 3324 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3325 String resolvedType, int userId) { 3326 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3327 if (resolver != null) { 3328 return resolver.queryIntent(intent, resolvedType, false, userId); 3329 } 3330 return null; 3331 } 3332 3333 @Override 3334 public List<ResolveInfo> queryIntentActivities(Intent intent, 3335 String resolvedType, int flags, int userId) { 3336 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3337 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3338 ComponentName comp = intent.getComponent(); 3339 if (comp == null) { 3340 if (intent.getSelector() != null) { 3341 intent = intent.getSelector(); 3342 comp = intent.getComponent(); 3343 } 3344 } 3345 3346 if (comp != null) { 3347 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3348 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3349 if (ai != null) { 3350 final ResolveInfo ri = new ResolveInfo(); 3351 ri.activityInfo = ai; 3352 list.add(ri); 3353 } 3354 return list; 3355 } 3356 3357 // reader 3358 synchronized (mPackages) { 3359 final String pkgName = intent.getPackage(); 3360 if (pkgName == null) { 3361 List<CrossProfileIntentFilter> matchingFilters = 3362 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3363 // Check for results that need to skip the current profile. 3364 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3365 resolvedType, flags, userId); 3366 if (resolveInfo != null) { 3367 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3368 result.add(resolveInfo); 3369 return result; 3370 } 3371 // Check for cross profile results. 3372 resolveInfo = queryCrossProfileIntents( 3373 matchingFilters, intent, resolvedType, flags, userId); 3374 3375 // Check for results in the current profile. 3376 List<ResolveInfo> result = mActivities.queryIntent( 3377 intent, resolvedType, flags, userId); 3378 if (resolveInfo != null) { 3379 result.add(resolveInfo); 3380 Collections.sort(result, mResolvePrioritySorter); 3381 } 3382 return result; 3383 } 3384 final PackageParser.Package pkg = mPackages.get(pkgName); 3385 if (pkg != null) { 3386 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3387 pkg.activities, userId); 3388 } 3389 return new ArrayList<ResolveInfo>(); 3390 } 3391 } 3392 3393 private ResolveInfo querySkipCurrentProfileIntents( 3394 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3395 int flags, int sourceUserId) { 3396 if (matchingFilters != null) { 3397 int size = matchingFilters.size(); 3398 for (int i = 0; i < size; i ++) { 3399 CrossProfileIntentFilter filter = matchingFilters.get(i); 3400 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 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) { 3406 return resolveInfo; 3407 } 3408 } 3409 } 3410 } 3411 return null; 3412 } 3413 3414 // Return matching ResolveInfo if any for skip current profile intent filters. 3415 private ResolveInfo queryCrossProfileIntents( 3416 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3417 int flags, int sourceUserId) { 3418 if (matchingFilters != null) { 3419 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3420 // match the same intent. For performance reasons, it is better not to 3421 // run queryIntent twice for the same userId 3422 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3423 int size = matchingFilters.size(); 3424 for (int i = 0; i < size; i++) { 3425 CrossProfileIntentFilter filter = matchingFilters.get(i); 3426 int targetUserId = filter.getTargetUserId(); 3427 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3428 && !alreadyTriedUserIds.get(targetUserId)) { 3429 // Checking if there are activities in the target user that can handle the 3430 // intent. 3431 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3432 flags, sourceUserId); 3433 if (resolveInfo != null) return resolveInfo; 3434 alreadyTriedUserIds.put(targetUserId, true); 3435 } 3436 } 3437 } 3438 return null; 3439 } 3440 3441 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3442 String resolvedType, int flags, int sourceUserId) { 3443 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3444 resolvedType, flags, filter.getTargetUserId()); 3445 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3446 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3447 } 3448 return null; 3449 } 3450 3451 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3452 int sourceUserId, int targetUserId) { 3453 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3454 String className; 3455 if (targetUserId == UserHandle.USER_OWNER) { 3456 className = FORWARD_INTENT_TO_USER_OWNER; 3457 } else { 3458 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3459 } 3460 ComponentName forwardingActivityComponentName = new ComponentName( 3461 mAndroidApplication.packageName, className); 3462 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3463 sourceUserId); 3464 if (targetUserId == UserHandle.USER_OWNER) { 3465 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3466 forwardingResolveInfo.noResourceId = true; 3467 } 3468 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3469 forwardingResolveInfo.priority = 0; 3470 forwardingResolveInfo.preferredOrder = 0; 3471 forwardingResolveInfo.match = 0; 3472 forwardingResolveInfo.isDefault = true; 3473 forwardingResolveInfo.filter = filter; 3474 forwardingResolveInfo.targetUserId = targetUserId; 3475 return forwardingResolveInfo; 3476 } 3477 3478 @Override 3479 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3480 Intent[] specifics, String[] specificTypes, Intent intent, 3481 String resolvedType, int flags, int userId) { 3482 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3483 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3484 false, "query intent activity options"); 3485 final String resultsAction = intent.getAction(); 3486 3487 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3488 | PackageManager.GET_RESOLVED_FILTER, userId); 3489 3490 if (DEBUG_INTENT_MATCHING) { 3491 Log.v(TAG, "Query " + intent + ": " + results); 3492 } 3493 3494 int specificsPos = 0; 3495 int N; 3496 3497 // todo: note that the algorithm used here is O(N^2). This 3498 // isn't a problem in our current environment, but if we start running 3499 // into situations where we have more than 5 or 10 matches then this 3500 // should probably be changed to something smarter... 3501 3502 // First we go through and resolve each of the specific items 3503 // that were supplied, taking care of removing any corresponding 3504 // duplicate items in the generic resolve list. 3505 if (specifics != null) { 3506 for (int i=0; i<specifics.length; i++) { 3507 final Intent sintent = specifics[i]; 3508 if (sintent == null) { 3509 continue; 3510 } 3511 3512 if (DEBUG_INTENT_MATCHING) { 3513 Log.v(TAG, "Specific #" + i + ": " + sintent); 3514 } 3515 3516 String action = sintent.getAction(); 3517 if (resultsAction != null && resultsAction.equals(action)) { 3518 // If this action was explicitly requested, then don't 3519 // remove things that have it. 3520 action = null; 3521 } 3522 3523 ResolveInfo ri = null; 3524 ActivityInfo ai = null; 3525 3526 ComponentName comp = sintent.getComponent(); 3527 if (comp == null) { 3528 ri = resolveIntent( 3529 sintent, 3530 specificTypes != null ? specificTypes[i] : null, 3531 flags, userId); 3532 if (ri == null) { 3533 continue; 3534 } 3535 if (ri == mResolveInfo) { 3536 // ACK! Must do something better with this. 3537 } 3538 ai = ri.activityInfo; 3539 comp = new ComponentName(ai.applicationInfo.packageName, 3540 ai.name); 3541 } else { 3542 ai = getActivityInfo(comp, flags, userId); 3543 if (ai == null) { 3544 continue; 3545 } 3546 } 3547 3548 // Look for any generic query activities that are duplicates 3549 // of this specific one, and remove them from the results. 3550 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3551 N = results.size(); 3552 int j; 3553 for (j=specificsPos; j<N; j++) { 3554 ResolveInfo sri = results.get(j); 3555 if ((sri.activityInfo.name.equals(comp.getClassName()) 3556 && sri.activityInfo.applicationInfo.packageName.equals( 3557 comp.getPackageName())) 3558 || (action != null && sri.filter.matchAction(action))) { 3559 results.remove(j); 3560 if (DEBUG_INTENT_MATCHING) Log.v( 3561 TAG, "Removing duplicate item from " + j 3562 + " due to specific " + specificsPos); 3563 if (ri == null) { 3564 ri = sri; 3565 } 3566 j--; 3567 N--; 3568 } 3569 } 3570 3571 // Add this specific item to its proper place. 3572 if (ri == null) { 3573 ri = new ResolveInfo(); 3574 ri.activityInfo = ai; 3575 } 3576 results.add(specificsPos, ri); 3577 ri.specificIndex = i; 3578 specificsPos++; 3579 } 3580 } 3581 3582 // Now we go through the remaining generic results and remove any 3583 // duplicate actions that are found here. 3584 N = results.size(); 3585 for (int i=specificsPos; i<N-1; i++) { 3586 final ResolveInfo rii = results.get(i); 3587 if (rii.filter == null) { 3588 continue; 3589 } 3590 3591 // Iterate over all of the actions of this result's intent 3592 // filter... typically this should be just one. 3593 final Iterator<String> it = rii.filter.actionsIterator(); 3594 if (it == null) { 3595 continue; 3596 } 3597 while (it.hasNext()) { 3598 final String action = it.next(); 3599 if (resultsAction != null && resultsAction.equals(action)) { 3600 // If this action was explicitly requested, then don't 3601 // remove things that have it. 3602 continue; 3603 } 3604 for (int j=i+1; j<N; j++) { 3605 final ResolveInfo rij = results.get(j); 3606 if (rij.filter != null && rij.filter.hasAction(action)) { 3607 results.remove(j); 3608 if (DEBUG_INTENT_MATCHING) Log.v( 3609 TAG, "Removing duplicate item from " + j 3610 + " due to action " + action + " at " + i); 3611 j--; 3612 N--; 3613 } 3614 } 3615 } 3616 3617 // If the caller didn't request filter information, drop it now 3618 // so we don't have to marshall/unmarshall it. 3619 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3620 rii.filter = null; 3621 } 3622 } 3623 3624 // Filter out the caller activity if so requested. 3625 if (caller != null) { 3626 N = results.size(); 3627 for (int i=0; i<N; i++) { 3628 ActivityInfo ainfo = results.get(i).activityInfo; 3629 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3630 && caller.getClassName().equals(ainfo.name)) { 3631 results.remove(i); 3632 break; 3633 } 3634 } 3635 } 3636 3637 // If the caller didn't request filter information, 3638 // drop them now so we don't have to 3639 // marshall/unmarshall it. 3640 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3641 N = results.size(); 3642 for (int i=0; i<N; i++) { 3643 results.get(i).filter = null; 3644 } 3645 } 3646 3647 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3648 return results; 3649 } 3650 3651 @Override 3652 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3653 int userId) { 3654 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3655 ComponentName comp = intent.getComponent(); 3656 if (comp == null) { 3657 if (intent.getSelector() != null) { 3658 intent = intent.getSelector(); 3659 comp = intent.getComponent(); 3660 } 3661 } 3662 if (comp != null) { 3663 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3664 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3665 if (ai != null) { 3666 ResolveInfo ri = new ResolveInfo(); 3667 ri.activityInfo = ai; 3668 list.add(ri); 3669 } 3670 return list; 3671 } 3672 3673 // reader 3674 synchronized (mPackages) { 3675 String pkgName = intent.getPackage(); 3676 if (pkgName == null) { 3677 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3678 } 3679 final PackageParser.Package pkg = mPackages.get(pkgName); 3680 if (pkg != null) { 3681 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3682 userId); 3683 } 3684 return null; 3685 } 3686 } 3687 3688 @Override 3689 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3690 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3691 if (!sUserManager.exists(userId)) return null; 3692 if (query != null) { 3693 if (query.size() >= 1) { 3694 // If there is more than one service with the same priority, 3695 // just arbitrarily pick the first one. 3696 return query.get(0); 3697 } 3698 } 3699 return null; 3700 } 3701 3702 @Override 3703 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3704 int userId) { 3705 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3706 ComponentName comp = intent.getComponent(); 3707 if (comp == null) { 3708 if (intent.getSelector() != null) { 3709 intent = intent.getSelector(); 3710 comp = intent.getComponent(); 3711 } 3712 } 3713 if (comp != null) { 3714 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3715 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3716 if (si != null) { 3717 final ResolveInfo ri = new ResolveInfo(); 3718 ri.serviceInfo = si; 3719 list.add(ri); 3720 } 3721 return list; 3722 } 3723 3724 // reader 3725 synchronized (mPackages) { 3726 String pkgName = intent.getPackage(); 3727 if (pkgName == null) { 3728 return mServices.queryIntent(intent, resolvedType, flags, userId); 3729 } 3730 final PackageParser.Package pkg = mPackages.get(pkgName); 3731 if (pkg != null) { 3732 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3733 userId); 3734 } 3735 return null; 3736 } 3737 } 3738 3739 @Override 3740 public List<ResolveInfo> queryIntentContentProviders( 3741 Intent intent, String resolvedType, int flags, int userId) { 3742 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3743 ComponentName comp = intent.getComponent(); 3744 if (comp == null) { 3745 if (intent.getSelector() != null) { 3746 intent = intent.getSelector(); 3747 comp = intent.getComponent(); 3748 } 3749 } 3750 if (comp != null) { 3751 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3752 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3753 if (pi != null) { 3754 final ResolveInfo ri = new ResolveInfo(); 3755 ri.providerInfo = pi; 3756 list.add(ri); 3757 } 3758 return list; 3759 } 3760 3761 // reader 3762 synchronized (mPackages) { 3763 String pkgName = intent.getPackage(); 3764 if (pkgName == null) { 3765 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3766 } 3767 final PackageParser.Package pkg = mPackages.get(pkgName); 3768 if (pkg != null) { 3769 return mProviders.queryIntentForPackage( 3770 intent, resolvedType, flags, pkg.providers, userId); 3771 } 3772 return null; 3773 } 3774 } 3775 3776 @Override 3777 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3778 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3779 3780 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 3781 3782 // writer 3783 synchronized (mPackages) { 3784 ArrayList<PackageInfo> list; 3785 if (listUninstalled) { 3786 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3787 for (PackageSetting ps : mSettings.mPackages.values()) { 3788 PackageInfo pi; 3789 if (ps.pkg != null) { 3790 pi = generatePackageInfo(ps.pkg, flags, userId); 3791 } else { 3792 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3793 } 3794 if (pi != null) { 3795 list.add(pi); 3796 } 3797 } 3798 } else { 3799 list = new ArrayList<PackageInfo>(mPackages.size()); 3800 for (PackageParser.Package p : mPackages.values()) { 3801 PackageInfo pi = generatePackageInfo(p, flags, userId); 3802 if (pi != null) { 3803 list.add(pi); 3804 } 3805 } 3806 } 3807 3808 return new ParceledListSlice<PackageInfo>(list); 3809 } 3810 } 3811 3812 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3813 String[] permissions, boolean[] tmp, int flags, int userId) { 3814 int numMatch = 0; 3815 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3816 for (int i=0; i<permissions.length; i++) { 3817 if (gp.grantedPermissions.contains(permissions[i])) { 3818 tmp[i] = true; 3819 numMatch++; 3820 } else { 3821 tmp[i] = false; 3822 } 3823 } 3824 if (numMatch == 0) { 3825 return; 3826 } 3827 PackageInfo pi; 3828 if (ps.pkg != null) { 3829 pi = generatePackageInfo(ps.pkg, flags, userId); 3830 } else { 3831 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3832 } 3833 // The above might return null in cases of uninstalled apps or install-state 3834 // skew across users/profiles. 3835 if (pi != null) { 3836 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3837 if (numMatch == permissions.length) { 3838 pi.requestedPermissions = permissions; 3839 } else { 3840 pi.requestedPermissions = new String[numMatch]; 3841 numMatch = 0; 3842 for (int i=0; i<permissions.length; i++) { 3843 if (tmp[i]) { 3844 pi.requestedPermissions[numMatch] = permissions[i]; 3845 numMatch++; 3846 } 3847 } 3848 } 3849 } 3850 list.add(pi); 3851 } 3852 } 3853 3854 @Override 3855 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3856 String[] permissions, int flags, int userId) { 3857 if (!sUserManager.exists(userId)) return null; 3858 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3859 3860 // writer 3861 synchronized (mPackages) { 3862 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3863 boolean[] tmpBools = new boolean[permissions.length]; 3864 if (listUninstalled) { 3865 for (PackageSetting ps : mSettings.mPackages.values()) { 3866 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3867 } 3868 } else { 3869 for (PackageParser.Package pkg : mPackages.values()) { 3870 PackageSetting ps = (PackageSetting)pkg.mExtras; 3871 if (ps != null) { 3872 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3873 userId); 3874 } 3875 } 3876 } 3877 3878 return new ParceledListSlice<PackageInfo>(list); 3879 } 3880 } 3881 3882 @Override 3883 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3884 if (!sUserManager.exists(userId)) return null; 3885 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3886 3887 // writer 3888 synchronized (mPackages) { 3889 ArrayList<ApplicationInfo> list; 3890 if (listUninstalled) { 3891 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3892 for (PackageSetting ps : mSettings.mPackages.values()) { 3893 ApplicationInfo ai; 3894 if (ps.pkg != null) { 3895 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3896 ps.readUserState(userId), userId); 3897 } else { 3898 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3899 } 3900 if (ai != null) { 3901 list.add(ai); 3902 } 3903 } 3904 } else { 3905 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3906 for (PackageParser.Package p : mPackages.values()) { 3907 if (p.mExtras != null) { 3908 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3909 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3910 if (ai != null) { 3911 list.add(ai); 3912 } 3913 } 3914 } 3915 } 3916 3917 return new ParceledListSlice<ApplicationInfo>(list); 3918 } 3919 } 3920 3921 public List<ApplicationInfo> getPersistentApplications(int flags) { 3922 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3923 3924 // reader 3925 synchronized (mPackages) { 3926 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3927 final int userId = UserHandle.getCallingUserId(); 3928 while (i.hasNext()) { 3929 final PackageParser.Package p = i.next(); 3930 if (p.applicationInfo != null 3931 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3932 && (!mSafeMode || isSystemApp(p))) { 3933 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3934 if (ps != null) { 3935 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3936 ps.readUserState(userId), userId); 3937 if (ai != null) { 3938 finalList.add(ai); 3939 } 3940 } 3941 } 3942 } 3943 } 3944 3945 return finalList; 3946 } 3947 3948 @Override 3949 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3950 if (!sUserManager.exists(userId)) return null; 3951 // reader 3952 synchronized (mPackages) { 3953 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3954 PackageSetting ps = provider != null 3955 ? mSettings.mPackages.get(provider.owner.packageName) 3956 : null; 3957 return ps != null 3958 && mSettings.isEnabledLPr(provider.info, flags, userId) 3959 && (!mSafeMode || (provider.info.applicationInfo.flags 3960 &ApplicationInfo.FLAG_SYSTEM) != 0) 3961 ? PackageParser.generateProviderInfo(provider, flags, 3962 ps.readUserState(userId), userId) 3963 : null; 3964 } 3965 } 3966 3967 /** 3968 * @deprecated 3969 */ 3970 @Deprecated 3971 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3972 // reader 3973 synchronized (mPackages) { 3974 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3975 .entrySet().iterator(); 3976 final int userId = UserHandle.getCallingUserId(); 3977 while (i.hasNext()) { 3978 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3979 PackageParser.Provider p = entry.getValue(); 3980 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3981 3982 if (ps != null && p.syncable 3983 && (!mSafeMode || (p.info.applicationInfo.flags 3984 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3985 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3986 ps.readUserState(userId), userId); 3987 if (info != null) { 3988 outNames.add(entry.getKey()); 3989 outInfo.add(info); 3990 } 3991 } 3992 } 3993 } 3994 } 3995 3996 @Override 3997 public List<ProviderInfo> queryContentProviders(String processName, 3998 int uid, int flags) { 3999 ArrayList<ProviderInfo> finalList = null; 4000 // reader 4001 synchronized (mPackages) { 4002 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4003 final int userId = processName != null ? 4004 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4005 while (i.hasNext()) { 4006 final PackageParser.Provider p = i.next(); 4007 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4008 if (ps != null && p.info.authority != null 4009 && (processName == null 4010 || (p.info.processName.equals(processName) 4011 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4012 && mSettings.isEnabledLPr(p.info, flags, userId) 4013 && (!mSafeMode 4014 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4015 if (finalList == null) { 4016 finalList = new ArrayList<ProviderInfo>(3); 4017 } 4018 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4019 ps.readUserState(userId), userId); 4020 if (info != null) { 4021 finalList.add(info); 4022 } 4023 } 4024 } 4025 } 4026 4027 if (finalList != null) { 4028 Collections.sort(finalList, mProviderInitOrderSorter); 4029 } 4030 4031 return finalList; 4032 } 4033 4034 @Override 4035 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4036 int flags) { 4037 // reader 4038 synchronized (mPackages) { 4039 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4040 return PackageParser.generateInstrumentationInfo(i, flags); 4041 } 4042 } 4043 4044 @Override 4045 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4046 int flags) { 4047 ArrayList<InstrumentationInfo> finalList = 4048 new ArrayList<InstrumentationInfo>(); 4049 4050 // reader 4051 synchronized (mPackages) { 4052 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4053 while (i.hasNext()) { 4054 final PackageParser.Instrumentation p = i.next(); 4055 if (targetPackage == null 4056 || targetPackage.equals(p.info.targetPackage)) { 4057 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4058 flags); 4059 if (ii != null) { 4060 finalList.add(ii); 4061 } 4062 } 4063 } 4064 } 4065 4066 return finalList; 4067 } 4068 4069 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4070 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4071 if (overlays == null) { 4072 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4073 return; 4074 } 4075 for (PackageParser.Package opkg : overlays.values()) { 4076 // Not much to do if idmap fails: we already logged the error 4077 // and we certainly don't want to abort installation of pkg simply 4078 // because an overlay didn't fit properly. For these reasons, 4079 // ignore the return value of createIdmapForPackagePairLI. 4080 createIdmapForPackagePairLI(pkg, opkg); 4081 } 4082 } 4083 4084 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4085 PackageParser.Package opkg) { 4086 if (!opkg.mTrustedOverlay) { 4087 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4088 opkg.baseCodePath + ": overlay not trusted"); 4089 return false; 4090 } 4091 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4092 if (overlaySet == null) { 4093 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4094 opkg.baseCodePath + " but target package has no known overlays"); 4095 return false; 4096 } 4097 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4098 // TODO: generate idmap for split APKs 4099 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4100 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4101 + opkg.baseCodePath); 4102 return false; 4103 } 4104 PackageParser.Package[] overlayArray = 4105 overlaySet.values().toArray(new PackageParser.Package[0]); 4106 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4107 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4108 return p1.mOverlayPriority - p2.mOverlayPriority; 4109 } 4110 }; 4111 Arrays.sort(overlayArray, cmp); 4112 4113 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4114 int i = 0; 4115 for (PackageParser.Package p : overlayArray) { 4116 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4117 } 4118 return true; 4119 } 4120 4121 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4122 final File[] files = dir.listFiles(); 4123 if (ArrayUtils.isEmpty(files)) { 4124 Log.d(TAG, "No files in app dir " + dir); 4125 return; 4126 } 4127 4128 if (DEBUG_PACKAGE_SCANNING) { 4129 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4130 + " flags=0x" + Integer.toHexString(parseFlags)); 4131 } 4132 4133 for (File file : files) { 4134 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4135 && !PackageInstallerService.isStageName(file.getName()); 4136 if (!isPackage) { 4137 // Ignore entries which are not packages 4138 continue; 4139 } 4140 try { 4141 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4142 scanFlags, currentTime, null); 4143 } catch (PackageManagerException e) { 4144 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4145 4146 // Delete invalid userdata apps 4147 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4148 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4149 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4150 if (file.isDirectory()) { 4151 FileUtils.deleteContents(file); 4152 } 4153 file.delete(); 4154 } 4155 } 4156 } 4157 } 4158 4159 private static File getSettingsProblemFile() { 4160 File dataDir = Environment.getDataDirectory(); 4161 File systemDir = new File(dataDir, "system"); 4162 File fname = new File(systemDir, "uiderrors.txt"); 4163 return fname; 4164 } 4165 4166 static void reportSettingsProblem(int priority, String msg) { 4167 logCriticalInfo(priority, msg); 4168 } 4169 4170 static void logCriticalInfo(int priority, String msg) { 4171 Slog.println(priority, TAG, msg); 4172 EventLogTags.writePmCriticalInfo(msg); 4173 try { 4174 File fname = getSettingsProblemFile(); 4175 FileOutputStream out = new FileOutputStream(fname, true); 4176 PrintWriter pw = new FastPrintWriter(out); 4177 SimpleDateFormat formatter = new SimpleDateFormat(); 4178 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4179 pw.println(dateString + ": " + msg); 4180 pw.close(); 4181 FileUtils.setPermissions( 4182 fname.toString(), 4183 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4184 -1, -1); 4185 } catch (java.io.IOException e) { 4186 } 4187 } 4188 4189 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4190 PackageParser.Package pkg, File srcFile, int parseFlags) 4191 throws PackageManagerException { 4192 if (ps != null 4193 && ps.codePath.equals(srcFile) 4194 && ps.timeStamp == srcFile.lastModified() 4195 && !isCompatSignatureUpdateNeeded(pkg) 4196 && !isRecoverSignatureUpdateNeeded(pkg)) { 4197 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4198 if (ps.signatures.mSignatures != null 4199 && ps.signatures.mSignatures.length != 0 4200 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4201 // Optimization: reuse the existing cached certificates 4202 // if the package appears to be unchanged. 4203 pkg.mSignatures = ps.signatures.mSignatures; 4204 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4205 synchronized (mPackages) { 4206 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4207 } 4208 return; 4209 } 4210 4211 Slog.w(TAG, "PackageSetting for " + ps.name 4212 + " is missing signatures. Collecting certs again to recover them."); 4213 } else { 4214 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4215 } 4216 4217 try { 4218 pp.collectCertificates(pkg, parseFlags); 4219 pp.collectManifestDigest(pkg); 4220 } catch (PackageParserException e) { 4221 throw PackageManagerException.from(e); 4222 } 4223 } 4224 4225 /* 4226 * Scan a package and return the newly parsed package. 4227 * Returns null in case of errors and the error code is stored in mLastScanError 4228 */ 4229 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4230 long currentTime, UserHandle user) throws PackageManagerException { 4231 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4232 parseFlags |= mDefParseFlags; 4233 PackageParser pp = new PackageParser(); 4234 pp.setSeparateProcesses(mSeparateProcesses); 4235 pp.setOnlyCoreApps(mOnlyCore); 4236 pp.setDisplayMetrics(mMetrics); 4237 4238 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4239 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4240 } 4241 4242 final PackageParser.Package pkg; 4243 try { 4244 pkg = pp.parsePackage(scanFile, parseFlags); 4245 } catch (PackageParserException e) { 4246 throw PackageManagerException.from(e); 4247 } 4248 4249 PackageSetting ps = null; 4250 PackageSetting updatedPkg; 4251 // reader 4252 synchronized (mPackages) { 4253 // Look to see if we already know about this package. 4254 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4255 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4256 // This package has been renamed to its original name. Let's 4257 // use that. 4258 ps = mSettings.peekPackageLPr(oldName); 4259 } 4260 // If there was no original package, see one for the real package name. 4261 if (ps == null) { 4262 ps = mSettings.peekPackageLPr(pkg.packageName); 4263 } 4264 // Check to see if this package could be hiding/updating a system 4265 // package. Must look for it either under the original or real 4266 // package name depending on our state. 4267 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4268 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4269 } 4270 boolean updatedPkgBetter = false; 4271 // First check if this is a system package that may involve an update 4272 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4273 if (ps != null && !ps.codePath.equals(scanFile)) { 4274 // The path has changed from what was last scanned... check the 4275 // version of the new path against what we have stored to determine 4276 // what to do. 4277 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4278 if (pkg.mVersionCode < ps.versionCode) { 4279 // The system package has been updated and the code path does not match 4280 // Ignore entry. Skip it. 4281 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 4282 + " ignored: updated version " + ps.versionCode 4283 + " better than this " + pkg.mVersionCode); 4284 if (!updatedPkg.codePath.equals(scanFile)) { 4285 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4286 + ps.name + " changing from " + updatedPkg.codePathString 4287 + " to " + scanFile); 4288 updatedPkg.codePath = scanFile; 4289 updatedPkg.codePathString = scanFile.toString(); 4290 // This is the point at which we know that the system-disk APK 4291 // for this package has moved during a reboot (e.g. due to an OTA), 4292 // so we need to reevaluate it for privilege policy. 4293 if (locationIsPrivileged(scanFile)) { 4294 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4295 } 4296 } 4297 updatedPkg.pkg = pkg; 4298 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4299 } else { 4300 // The current app on the system partition is better than 4301 // what we have updated to on the data partition; switch 4302 // back to the system partition version. 4303 // At this point, its safely assumed that package installation for 4304 // apps in system partition will go through. If not there won't be a working 4305 // version of the app 4306 // writer 4307 synchronized (mPackages) { 4308 // Just remove the loaded entries from package lists. 4309 mPackages.remove(ps.name); 4310 } 4311 4312 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4313 + " reverting from " + ps.codePathString 4314 + ": new version " + pkg.mVersionCode 4315 + " better than installed " + ps.versionCode); 4316 4317 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4318 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4319 getAppDexInstructionSets(ps)); 4320 synchronized (mInstallLock) { 4321 args.cleanUpResourcesLI(); 4322 } 4323 synchronized (mPackages) { 4324 mSettings.enableSystemPackageLPw(ps.name); 4325 } 4326 updatedPkgBetter = true; 4327 } 4328 } 4329 } 4330 4331 if (updatedPkg != null) { 4332 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4333 // initially 4334 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4335 4336 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4337 // flag set initially 4338 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4339 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4340 } 4341 } 4342 4343 // Verify certificates against what was last scanned 4344 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4345 4346 /* 4347 * A new system app appeared, but we already had a non-system one of the 4348 * same name installed earlier. 4349 */ 4350 boolean shouldHideSystemApp = false; 4351 if (updatedPkg == null && ps != null 4352 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4353 /* 4354 * Check to make sure the signatures match first. If they don't, 4355 * wipe the installed application and its data. 4356 */ 4357 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4358 != PackageManager.SIGNATURE_MATCH) { 4359 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4360 + " signatures don't match existing userdata copy; removing"); 4361 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4362 ps = null; 4363 } else { 4364 /* 4365 * If the newly-added system app is an older version than the 4366 * already installed version, hide it. It will be scanned later 4367 * and re-added like an update. 4368 */ 4369 if (pkg.mVersionCode < ps.versionCode) { 4370 shouldHideSystemApp = true; 4371 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4372 + " but new version " + pkg.mVersionCode + " better than installed " 4373 + ps.versionCode + "; hiding system"); 4374 } else { 4375 /* 4376 * The newly found system app is a newer version that the 4377 * one previously installed. Simply remove the 4378 * already-installed application and replace it with our own 4379 * while keeping the application data. 4380 */ 4381 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4382 + " reverting from " + ps.codePathString + ": new version " 4383 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4384 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4385 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4386 getAppDexInstructionSets(ps)); 4387 synchronized (mInstallLock) { 4388 args.cleanUpResourcesLI(); 4389 } 4390 } 4391 } 4392 } 4393 4394 // The apk is forward locked (not public) if its code and resources 4395 // are kept in different files. (except for app in either system or 4396 // vendor path). 4397 // TODO grab this value from PackageSettings 4398 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4399 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4400 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4401 } 4402 } 4403 4404 // TODO: extend to support forward-locked splits 4405 String resourcePath = null; 4406 String baseResourcePath = null; 4407 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4408 if (ps != null && ps.resourcePathString != null) { 4409 resourcePath = ps.resourcePathString; 4410 baseResourcePath = ps.resourcePathString; 4411 } else { 4412 // Should not happen at all. Just log an error. 4413 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4414 } 4415 } else { 4416 resourcePath = pkg.codePath; 4417 baseResourcePath = pkg.baseCodePath; 4418 } 4419 4420 // Set application objects path explicitly. 4421 pkg.applicationInfo.setCodePath(pkg.codePath); 4422 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4423 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4424 pkg.applicationInfo.setResourcePath(resourcePath); 4425 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4426 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4427 4428 // Note that we invoke the following method only if we are about to unpack an application 4429 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4430 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4431 4432 /* 4433 * If the system app should be overridden by a previously installed 4434 * data, hide the system app now and let the /data/app scan pick it up 4435 * again. 4436 */ 4437 if (shouldHideSystemApp) { 4438 synchronized (mPackages) { 4439 /* 4440 * We have to grant systems permissions before we hide, because 4441 * grantPermissions will assume the package update is trying to 4442 * expand its permissions. 4443 */ 4444 grantPermissionsLPw(pkg, true, pkg.packageName); 4445 mSettings.disableSystemPackageLPw(pkg.packageName); 4446 } 4447 } 4448 4449 return scannedPkg; 4450 } 4451 4452 private static String fixProcessName(String defProcessName, 4453 String processName, int uid) { 4454 if (processName == null) { 4455 return defProcessName; 4456 } 4457 return processName; 4458 } 4459 4460 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4461 throws PackageManagerException { 4462 if (pkgSetting.signatures.mSignatures != null) { 4463 // Already existing package. Make sure signatures match 4464 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4465 == PackageManager.SIGNATURE_MATCH; 4466 if (!match) { 4467 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4468 == PackageManager.SIGNATURE_MATCH; 4469 } 4470 if (!match) { 4471 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 4472 == PackageManager.SIGNATURE_MATCH; 4473 } 4474 if (!match) { 4475 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4476 + pkg.packageName + " signatures do not match the " 4477 + "previously installed version; ignoring!"); 4478 } 4479 } 4480 4481 // Check for shared user signatures 4482 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4483 // Already existing package. Make sure signatures match 4484 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4485 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4486 if (!match) { 4487 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4488 == PackageManager.SIGNATURE_MATCH; 4489 } 4490 if (!match) { 4491 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 4492 == PackageManager.SIGNATURE_MATCH; 4493 } 4494 if (!match) { 4495 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4496 "Package " + pkg.packageName 4497 + " has no signatures that match those in shared user " 4498 + pkgSetting.sharedUser.name + "; ignoring!"); 4499 } 4500 } 4501 } 4502 4503 /** 4504 * Enforces that only the system UID or root's UID can call a method exposed 4505 * via Binder. 4506 * 4507 * @param message used as message if SecurityException is thrown 4508 * @throws SecurityException if the caller is not system or root 4509 */ 4510 private static final void enforceSystemOrRoot(String message) { 4511 final int uid = Binder.getCallingUid(); 4512 if (uid != Process.SYSTEM_UID && uid != 0) { 4513 throw new SecurityException(message); 4514 } 4515 } 4516 4517 @Override 4518 public void performBootDexOpt() { 4519 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4520 4521 final ArraySet<PackageParser.Package> pkgs; 4522 synchronized (mPackages) { 4523 pkgs = mDeferredDexOpt; 4524 mDeferredDexOpt = null; 4525 } 4526 4527 if (pkgs != null) { 4528 // Sort apps by importance for dexopt ordering. Important apps are given more priority 4529 // in case the device runs out of space. 4530 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 4531 // Give priority to core apps. 4532 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4533 PackageParser.Package pkg = it.next(); 4534 if (pkg.coreApp) { 4535 if (DEBUG_DEXOPT) { 4536 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 4537 } 4538 sortedPkgs.add(pkg); 4539 it.remove(); 4540 } 4541 } 4542 // Give priority to system apps that listen for pre boot complete. 4543 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 4544 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 4545 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4546 PackageParser.Package pkg = it.next(); 4547 if (pkgNames.contains(pkg.packageName)) { 4548 if (DEBUG_DEXOPT) { 4549 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 4550 } 4551 sortedPkgs.add(pkg); 4552 it.remove(); 4553 } 4554 } 4555 // Give priority to system apps. 4556 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4557 PackageParser.Package pkg = it.next(); 4558 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 4559 if (DEBUG_DEXOPT) { 4560 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 4561 } 4562 sortedPkgs.add(pkg); 4563 it.remove(); 4564 } 4565 } 4566 // Give priority to updated system apps. 4567 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4568 PackageParser.Package pkg = it.next(); 4569 if (isUpdatedSystemApp(pkg)) { 4570 if (DEBUG_DEXOPT) { 4571 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 4572 } 4573 sortedPkgs.add(pkg); 4574 it.remove(); 4575 } 4576 } 4577 // Give priority to apps that listen for boot complete. 4578 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 4579 pkgNames = getPackageNamesForIntent(intent); 4580 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4581 PackageParser.Package pkg = it.next(); 4582 if (pkgNames.contains(pkg.packageName)) { 4583 if (DEBUG_DEXOPT) { 4584 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 4585 } 4586 sortedPkgs.add(pkg); 4587 it.remove(); 4588 } 4589 } 4590 // Filter out packages that aren't recently used. 4591 filterRecentlyUsedApps(pkgs); 4592 // Add all remaining apps. 4593 for (PackageParser.Package pkg : pkgs) { 4594 if (DEBUG_DEXOPT) { 4595 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 4596 } 4597 sortedPkgs.add(pkg); 4598 } 4599 4600 // If we want to be lazy, filter everything that wasn't recently used. 4601 if (mLazyDexOpt) { 4602 filterRecentlyUsedApps(sortedPkgs); 4603 } 4604 4605 int i = 0; 4606 int total = sortedPkgs.size(); 4607 File dataDir = Environment.getDataDirectory(); 4608 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 4609 if (lowThreshold == 0) { 4610 throw new IllegalStateException("Invalid low memory threshold"); 4611 } 4612 for (PackageParser.Package pkg : sortedPkgs) { 4613 long usableSpace = dataDir.getUsableSpace(); 4614 if (usableSpace < lowThreshold) { 4615 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 4616 break; 4617 } 4618 performBootDexOpt(pkg, ++i, total); 4619 } 4620 } 4621 } 4622 4623 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 4624 // Filter out packages that aren't recently used. 4625 // 4626 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4627 // should do a full dexopt. 4628 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4629 int total = pkgs.size(); 4630 int skipped = 0; 4631 long now = System.currentTimeMillis(); 4632 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4633 PackageParser.Package pkg = i.next(); 4634 long then = pkg.mLastPackageUsageTimeInMills; 4635 if (then + mDexOptLRUThresholdInMills < now) { 4636 if (DEBUG_DEXOPT) { 4637 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4638 ((then == 0) ? "never" : new Date(then))); 4639 } 4640 i.remove(); 4641 skipped++; 4642 } 4643 } 4644 if (DEBUG_DEXOPT) { 4645 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4646 } 4647 } 4648 } 4649 4650 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 4651 List<ResolveInfo> ris = null; 4652 try { 4653 ris = AppGlobals.getPackageManager().queryIntentReceivers( 4654 intent, null, 0, UserHandle.USER_OWNER); 4655 } catch (RemoteException e) { 4656 } 4657 ArraySet<String> pkgNames = new ArraySet<String>(); 4658 if (ris != null) { 4659 for (ResolveInfo ri : ris) { 4660 pkgNames.add(ri.activityInfo.packageName); 4661 } 4662 } 4663 return pkgNames; 4664 } 4665 4666 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 4667 if (DEBUG_DEXOPT) { 4668 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 4669 } 4670 if (!isFirstBoot()) { 4671 try { 4672 ActivityManagerNative.getDefault().showBootMessage( 4673 mContext.getResources().getString(R.string.android_upgrading_apk, 4674 curr, total), true); 4675 } catch (RemoteException e) { 4676 } 4677 } 4678 PackageParser.Package p = pkg; 4679 synchronized (mInstallLock) { 4680 performDexOptLI(p, null /* instruction sets */, false /* force dex */, 4681 false /* defer */, true /* include dependencies */); 4682 } 4683 } 4684 4685 @Override 4686 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4687 return performDexOpt(packageName, instructionSet, false); 4688 } 4689 4690 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4691 if (info.primaryCpuAbi == null) { 4692 return getPreferredInstructionSet(); 4693 } 4694 4695 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4696 } 4697 4698 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4699 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4700 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4701 if (!dexopt && !updateUsage) { 4702 // We aren't going to dexopt or update usage, so bail early. 4703 return false; 4704 } 4705 PackageParser.Package p; 4706 final String targetInstructionSet; 4707 synchronized (mPackages) { 4708 p = mPackages.get(packageName); 4709 if (p == null) { 4710 return false; 4711 } 4712 if (updateUsage) { 4713 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4714 } 4715 mPackageUsage.write(false); 4716 if (!dexopt) { 4717 // We aren't going to dexopt, so bail early. 4718 return false; 4719 } 4720 4721 targetInstructionSet = instructionSet != null ? instructionSet : 4722 getPrimaryInstructionSet(p.applicationInfo); 4723 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4724 return false; 4725 } 4726 } 4727 4728 synchronized (mInstallLock) { 4729 final String[] instructionSets = new String[] { targetInstructionSet }; 4730 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4731 true /* include dependencies */) == DEX_OPT_PERFORMED; 4732 } 4733 } 4734 4735 public ArraySet<String> getPackagesThatNeedDexOpt() { 4736 ArraySet<String> pkgs = null; 4737 synchronized (mPackages) { 4738 for (PackageParser.Package p : mPackages.values()) { 4739 if (DEBUG_DEXOPT) { 4740 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4741 } 4742 if (!p.mDexOptPerformed.isEmpty()) { 4743 continue; 4744 } 4745 if (pkgs == null) { 4746 pkgs = new ArraySet<String>(); 4747 } 4748 pkgs.add(p.packageName); 4749 } 4750 } 4751 return pkgs; 4752 } 4753 4754 public void shutdown() { 4755 mPackageUsage.write(true); 4756 } 4757 4758 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4759 boolean forceDex, boolean defer, ArraySet<String> done) { 4760 for (int i=0; i<libs.size(); i++) { 4761 PackageParser.Package libPkg; 4762 String libName; 4763 synchronized (mPackages) { 4764 libName = libs.get(i); 4765 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4766 if (lib != null && lib.apk != null) { 4767 libPkg = mPackages.get(lib.apk); 4768 } else { 4769 libPkg = null; 4770 } 4771 } 4772 if (libPkg != null && !done.contains(libName)) { 4773 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4774 } 4775 } 4776 } 4777 4778 static final int DEX_OPT_SKIPPED = 0; 4779 static final int DEX_OPT_PERFORMED = 1; 4780 static final int DEX_OPT_DEFERRED = 2; 4781 static final int DEX_OPT_FAILED = -1; 4782 4783 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4784 boolean forceDex, boolean defer, ArraySet<String> done) { 4785 final String[] instructionSets = targetInstructionSets != null ? 4786 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4787 4788 if (done != null) { 4789 done.add(pkg.packageName); 4790 if (pkg.usesLibraries != null) { 4791 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4792 } 4793 if (pkg.usesOptionalLibraries != null) { 4794 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4795 } 4796 } 4797 4798 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4799 return DEX_OPT_SKIPPED; 4800 } 4801 4802 final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0; 4803 4804 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4805 boolean performedDexOpt = false; 4806 // There are three basic cases here: 4807 // 1.) we need to dexopt, either because we are forced or it is needed 4808 // 2.) we are defering a needed dexopt 4809 // 3.) we are skipping an unneeded dexopt 4810 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4811 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4812 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4813 continue; 4814 } 4815 4816 for (String path : paths) { 4817 try { 4818 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4819 // patckage or the one we find does not match the image checksum (i.e. it was 4820 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4821 // odex file and it matches the checksum of the image but not its base address, 4822 // meaning we need to move it. 4823 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4824 pkg.packageName, dexCodeInstructionSet, defer); 4825 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4826 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4827 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet 4828 + " vmSafeMode=" + vmSafeMode); 4829 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4830 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4831 pkg.packageName, dexCodeInstructionSet, vmSafeMode); 4832 4833 if (ret < 0) { 4834 // Don't bother running dexopt again if we failed, it will probably 4835 // just result in an error again. Also, don't bother dexopting for other 4836 // paths & ISAs. 4837 return DEX_OPT_FAILED; 4838 } 4839 4840 performedDexOpt = true; 4841 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4842 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4843 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4844 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4845 pkg.packageName, dexCodeInstructionSet); 4846 4847 if (ret < 0) { 4848 // Don't bother running patchoat again if we failed, it will probably 4849 // just result in an error again. Also, don't bother dexopting for other 4850 // paths & ISAs. 4851 return DEX_OPT_FAILED; 4852 } 4853 4854 performedDexOpt = true; 4855 } 4856 4857 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4858 // paths and instruction sets. We'll deal with them all together when we process 4859 // our list of deferred dexopts. 4860 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4861 if (mDeferredDexOpt == null) { 4862 mDeferredDexOpt = new ArraySet<PackageParser.Package>(); 4863 } 4864 mDeferredDexOpt.add(pkg); 4865 return DEX_OPT_DEFERRED; 4866 } 4867 } catch (FileNotFoundException e) { 4868 Slog.w(TAG, "Apk not found for dexopt: " + path); 4869 return DEX_OPT_FAILED; 4870 } catch (IOException e) { 4871 Slog.w(TAG, "IOException reading apk: " + path, e); 4872 return DEX_OPT_FAILED; 4873 } catch (StaleDexCacheError e) { 4874 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4875 return DEX_OPT_FAILED; 4876 } catch (Exception e) { 4877 Slog.w(TAG, "Exception when doing dexopt : ", e); 4878 return DEX_OPT_FAILED; 4879 } 4880 } 4881 4882 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4883 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4884 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4885 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4886 // it. 4887 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4888 } 4889 4890 // If we've gotten here, we're sure that no error occurred and that we haven't 4891 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4892 // we've skipped all of them because they are up to date. In both cases this 4893 // package doesn't need dexopt any longer. 4894 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4895 } 4896 4897 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4898 if (info.primaryCpuAbi != null) { 4899 if (info.secondaryCpuAbi != null) { 4900 return new String[] { 4901 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4902 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4903 } else { 4904 return new String[] { 4905 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4906 } 4907 } 4908 4909 return new String[] { getPreferredInstructionSet() }; 4910 } 4911 4912 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4913 if (ps.primaryCpuAbiString != null) { 4914 if (ps.secondaryCpuAbiString != null) { 4915 return new String[] { 4916 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4917 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4918 } else { 4919 return new String[] { 4920 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4921 } 4922 } 4923 4924 return new String[] { getPreferredInstructionSet() }; 4925 } 4926 4927 private static String getPreferredInstructionSet() { 4928 if (sPreferredInstructionSet == null) { 4929 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4930 } 4931 4932 return sPreferredInstructionSet; 4933 } 4934 4935 private static List<String> getAllInstructionSets() { 4936 final String[] allAbis = Build.SUPPORTED_ABIS; 4937 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4938 4939 for (String abi : allAbis) { 4940 final String instructionSet = VMRuntime.getInstructionSet(abi); 4941 if (!allInstructionSets.contains(instructionSet)) { 4942 allInstructionSets.add(instructionSet); 4943 } 4944 } 4945 4946 return allInstructionSets; 4947 } 4948 4949 /** 4950 * Returns the instruction set that should be used to compile dex code. In the presence of 4951 * a native bridge this might be different than the one shared libraries use. 4952 */ 4953 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4954 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4955 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4956 } 4957 4958 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4959 ArraySet<String> dexCodeInstructionSets = new ArraySet<String>(instructionSets.length); 4960 for (String instructionSet : instructionSets) { 4961 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4962 } 4963 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4964 } 4965 4966 /** 4967 * Returns deduplicated list of supported instructions for dex code. 4968 */ 4969 public static String[] getAllDexCodeInstructionSets() { 4970 String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length]; 4971 for (int i = 0; i < supportedInstructionSets.length; i++) { 4972 String abi = Build.SUPPORTED_ABIS[i]; 4973 supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi); 4974 } 4975 return getDexCodeInstructionSets(supportedInstructionSets); 4976 } 4977 4978 @Override 4979 public void forceDexOpt(String packageName) { 4980 enforceSystemOrRoot("forceDexOpt"); 4981 4982 PackageParser.Package pkg; 4983 synchronized (mPackages) { 4984 pkg = mPackages.get(packageName); 4985 if (pkg == null) { 4986 throw new IllegalArgumentException("Missing package: " + packageName); 4987 } 4988 } 4989 4990 synchronized (mInstallLock) { 4991 final String[] instructionSets = new String[] { 4992 getPrimaryInstructionSet(pkg.applicationInfo) }; 4993 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4994 if (res != DEX_OPT_PERFORMED) { 4995 throw new IllegalStateException("Failed to dexopt: " + res); 4996 } 4997 } 4998 } 4999 5000 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 5001 boolean forceDex, boolean defer, boolean inclDependencies) { 5002 ArraySet<String> done; 5003 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 5004 done = new ArraySet<String>(); 5005 done.add(pkg.packageName); 5006 } else { 5007 done = null; 5008 } 5009 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 5010 } 5011 5012 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5013 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5014 Slog.w(TAG, "Unable to update from " + oldPkg.name 5015 + " to " + newPkg.packageName 5016 + ": old package not in system partition"); 5017 return false; 5018 } else if (mPackages.get(oldPkg.name) != null) { 5019 Slog.w(TAG, "Unable to update from " + oldPkg.name 5020 + " to " + newPkg.packageName 5021 + ": old package still exists"); 5022 return false; 5023 } 5024 return true; 5025 } 5026 5027 File getDataPathForUser(int userId) { 5028 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 5029 } 5030 5031 private File getDataPathForPackage(String packageName, int userId) { 5032 /* 5033 * Until we fully support multiple users, return the directory we 5034 * previously would have. The PackageManagerTests will need to be 5035 * revised when this is changed back.. 5036 */ 5037 if (userId == 0) { 5038 return new File(mAppDataDir, packageName); 5039 } else { 5040 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 5041 + File.separator + packageName); 5042 } 5043 } 5044 5045 private int createDataDirsLI(String packageName, int uid, String seinfo) { 5046 int[] users = sUserManager.getUserIds(); 5047 int res = mInstaller.install(packageName, uid, uid, seinfo); 5048 if (res < 0) { 5049 return res; 5050 } 5051 for (int user : users) { 5052 if (user != 0) { 5053 res = mInstaller.createUserData(packageName, 5054 UserHandle.getUid(user, uid), user, seinfo); 5055 if (res < 0) { 5056 return res; 5057 } 5058 } 5059 } 5060 return res; 5061 } 5062 5063 private int removeDataDirsLI(String packageName) { 5064 int[] users = sUserManager.getUserIds(); 5065 int res = 0; 5066 for (int user : users) { 5067 int resInner = mInstaller.remove(packageName, user); 5068 if (resInner < 0) { 5069 res = resInner; 5070 } 5071 } 5072 5073 return res; 5074 } 5075 5076 private int deleteCodeCacheDirsLI(String packageName) { 5077 int[] users = sUserManager.getUserIds(); 5078 int res = 0; 5079 for (int user : users) { 5080 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 5081 if (resInner < 0) { 5082 res = resInner; 5083 } 5084 } 5085 return res; 5086 } 5087 5088 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5089 PackageParser.Package changingLib) { 5090 if (file.path != null) { 5091 usesLibraryFiles.add(file.path); 5092 return; 5093 } 5094 PackageParser.Package p = mPackages.get(file.apk); 5095 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5096 // If we are doing this while in the middle of updating a library apk, 5097 // then we need to make sure to use that new apk for determining the 5098 // dependencies here. (We haven't yet finished committing the new apk 5099 // to the package manager state.) 5100 if (p == null || p.packageName.equals(changingLib.packageName)) { 5101 p = changingLib; 5102 } 5103 } 5104 if (p != null) { 5105 usesLibraryFiles.addAll(p.getAllCodePaths()); 5106 } 5107 } 5108 5109 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5110 PackageParser.Package changingLib) throws PackageManagerException { 5111 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5112 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5113 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5114 for (int i=0; i<N; i++) { 5115 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5116 if (file == null) { 5117 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5118 "Package " + pkg.packageName + " requires unavailable shared library " 5119 + pkg.usesLibraries.get(i) + "; failing!"); 5120 } 5121 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5122 } 5123 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5124 for (int i=0; i<N; i++) { 5125 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5126 if (file == null) { 5127 Slog.w(TAG, "Package " + pkg.packageName 5128 + " desires unavailable shared library " 5129 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5130 } else { 5131 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5132 } 5133 } 5134 N = usesLibraryFiles.size(); 5135 if (N > 0) { 5136 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5137 } else { 5138 pkg.usesLibraryFiles = null; 5139 } 5140 } 5141 } 5142 5143 private static boolean hasString(List<String> list, List<String> which) { 5144 if (list == null) { 5145 return false; 5146 } 5147 for (int i=list.size()-1; i>=0; i--) { 5148 for (int j=which.size()-1; j>=0; j--) { 5149 if (which.get(j).equals(list.get(i))) { 5150 return true; 5151 } 5152 } 5153 } 5154 return false; 5155 } 5156 5157 private void updateAllSharedLibrariesLPw() { 5158 for (PackageParser.Package pkg : mPackages.values()) { 5159 try { 5160 updateSharedLibrariesLPw(pkg, null); 5161 } catch (PackageManagerException e) { 5162 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5163 } 5164 } 5165 } 5166 5167 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5168 PackageParser.Package changingPkg) { 5169 ArrayList<PackageParser.Package> res = null; 5170 for (PackageParser.Package pkg : mPackages.values()) { 5171 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5172 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5173 if (res == null) { 5174 res = new ArrayList<PackageParser.Package>(); 5175 } 5176 res.add(pkg); 5177 try { 5178 updateSharedLibrariesLPw(pkg, changingPkg); 5179 } catch (PackageManagerException e) { 5180 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5181 } 5182 } 5183 } 5184 return res; 5185 } 5186 5187 /** 5188 * Derive the value of the {@code cpuAbiOverride} based on the provided 5189 * value and an optional stored value from the package settings. 5190 */ 5191 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5192 String cpuAbiOverride = null; 5193 5194 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5195 cpuAbiOverride = null; 5196 } else if (abiOverride != null) { 5197 cpuAbiOverride = abiOverride; 5198 } else if (settings != null) { 5199 cpuAbiOverride = settings.cpuAbiOverrideString; 5200 } 5201 5202 return cpuAbiOverride; 5203 } 5204 5205 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5206 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5207 boolean success = false; 5208 try { 5209 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5210 currentTime, user); 5211 success = true; 5212 return res; 5213 } finally { 5214 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5215 removeDataDirsLI(pkg.packageName); 5216 } 5217 } 5218 } 5219 5220 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5221 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5222 final File scanFile = new File(pkg.codePath); 5223 if (pkg.applicationInfo.getCodePath() == null || 5224 pkg.applicationInfo.getResourcePath() == null) { 5225 // Bail out. The resource and code paths haven't been set. 5226 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5227 "Code and resource paths haven't been set correctly"); 5228 } 5229 5230 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5231 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5232 } else { 5233 // Only allow system apps to be flagged as core apps. 5234 pkg.coreApp = false; 5235 } 5236 5237 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5238 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5239 } 5240 5241 if (mCustomResolverComponentName != null && 5242 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5243 setUpCustomResolverActivity(pkg); 5244 } 5245 5246 if (pkg.packageName.equals("android")) { 5247 synchronized (mPackages) { 5248 if (mAndroidApplication != null) { 5249 Slog.w(TAG, "*************************************************"); 5250 Slog.w(TAG, "Core android package being redefined. Skipping."); 5251 Slog.w(TAG, " file=" + scanFile); 5252 Slog.w(TAG, "*************************************************"); 5253 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5254 "Core android package being redefined. Skipping."); 5255 } 5256 5257 // Set up information for our fall-back user intent resolution activity. 5258 mPlatformPackage = pkg; 5259 pkg.mVersionCode = mSdkVersion; 5260 mAndroidApplication = pkg.applicationInfo; 5261 5262 if (!mResolverReplaced) { 5263 mResolveActivity.applicationInfo = mAndroidApplication; 5264 mResolveActivity.name = ResolverActivity.class.getName(); 5265 mResolveActivity.packageName = mAndroidApplication.packageName; 5266 mResolveActivity.processName = "system:ui"; 5267 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5268 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5269 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5270 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5271 mResolveActivity.exported = true; 5272 mResolveActivity.enabled = true; 5273 mResolveInfo.activityInfo = mResolveActivity; 5274 mResolveInfo.priority = 0; 5275 mResolveInfo.preferredOrder = 0; 5276 mResolveInfo.match = 0; 5277 mResolveComponentName = new ComponentName( 5278 mAndroidApplication.packageName, mResolveActivity.name); 5279 } 5280 } 5281 } 5282 5283 if (DEBUG_PACKAGE_SCANNING) { 5284 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5285 Log.d(TAG, "Scanning package " + pkg.packageName); 5286 } 5287 5288 if (mPackages.containsKey(pkg.packageName) 5289 || mSharedLibraries.containsKey(pkg.packageName)) { 5290 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5291 "Application package " + pkg.packageName 5292 + " already installed. Skipping duplicate."); 5293 } 5294 5295 // Initialize package source and resource directories 5296 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5297 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5298 5299 SharedUserSetting suid = null; 5300 PackageSetting pkgSetting = null; 5301 5302 if (!isSystemApp(pkg)) { 5303 // Only system apps can use these features. 5304 pkg.mOriginalPackages = null; 5305 pkg.mRealPackage = null; 5306 pkg.mAdoptPermissions = null; 5307 } 5308 5309 // writer 5310 synchronized (mPackages) { 5311 if (pkg.mSharedUserId != null) { 5312 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5313 if (suid == null) { 5314 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5315 "Creating application package " + pkg.packageName 5316 + " for shared user failed"); 5317 } 5318 if (DEBUG_PACKAGE_SCANNING) { 5319 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5320 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5321 + "): packages=" + suid.packages); 5322 } 5323 } 5324 5325 // Check if we are renaming from an original package name. 5326 PackageSetting origPackage = null; 5327 String realName = null; 5328 if (pkg.mOriginalPackages != null) { 5329 // This package may need to be renamed to a previously 5330 // installed name. Let's check on that... 5331 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5332 if (pkg.mOriginalPackages.contains(renamed)) { 5333 // This package had originally been installed as the 5334 // original name, and we have already taken care of 5335 // transitioning to the new one. Just update the new 5336 // one to continue using the old name. 5337 realName = pkg.mRealPackage; 5338 if (!pkg.packageName.equals(renamed)) { 5339 // Callers into this function may have already taken 5340 // care of renaming the package; only do it here if 5341 // it is not already done. 5342 pkg.setPackageName(renamed); 5343 } 5344 5345 } else { 5346 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5347 if ((origPackage = mSettings.peekPackageLPr( 5348 pkg.mOriginalPackages.get(i))) != null) { 5349 // We do have the package already installed under its 5350 // original name... should we use it? 5351 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5352 // New package is not compatible with original. 5353 origPackage = null; 5354 continue; 5355 } else if (origPackage.sharedUser != null) { 5356 // Make sure uid is compatible between packages. 5357 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5358 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5359 + " to " + pkg.packageName + ": old uid " 5360 + origPackage.sharedUser.name 5361 + " differs from " + pkg.mSharedUserId); 5362 origPackage = null; 5363 continue; 5364 } 5365 } else { 5366 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5367 + pkg.packageName + " to old name " + origPackage.name); 5368 } 5369 break; 5370 } 5371 } 5372 } 5373 } 5374 5375 if (mTransferedPackages.contains(pkg.packageName)) { 5376 Slog.w(TAG, "Package " + pkg.packageName 5377 + " was transferred to another, but its .apk remains"); 5378 } 5379 5380 // Just create the setting, don't add it yet. For already existing packages 5381 // the PkgSetting exists already and doesn't have to be created. 5382 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5383 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5384 pkg.applicationInfo.primaryCpuAbi, 5385 pkg.applicationInfo.secondaryCpuAbi, 5386 pkg.applicationInfo.flags, user, false); 5387 if (pkgSetting == null) { 5388 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5389 "Creating application package " + pkg.packageName + " failed"); 5390 } 5391 5392 if (pkgSetting.origPackage != null) { 5393 // If we are first transitioning from an original package, 5394 // fix up the new package's name now. We need to do this after 5395 // looking up the package under its new name, so getPackageLP 5396 // can take care of fiddling things correctly. 5397 pkg.setPackageName(origPackage.name); 5398 5399 // File a report about this. 5400 String msg = "New package " + pkgSetting.realName 5401 + " renamed to replace old package " + pkgSetting.name; 5402 reportSettingsProblem(Log.WARN, msg); 5403 5404 // Make a note of it. 5405 mTransferedPackages.add(origPackage.name); 5406 5407 // No longer need to retain this. 5408 pkgSetting.origPackage = null; 5409 } 5410 5411 if (realName != null) { 5412 // Make a note of it. 5413 mTransferedPackages.add(pkg.packageName); 5414 } 5415 5416 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5417 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5418 } 5419 5420 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5421 // Check all shared libraries and map to their actual file path. 5422 // We only do this here for apps not on a system dir, because those 5423 // are the only ones that can fail an install due to this. We 5424 // will take care of the system apps by updating all of their 5425 // library paths after the scan is done. 5426 updateSharedLibrariesLPw(pkg, null); 5427 } 5428 5429 if (mFoundPolicyFile) { 5430 SELinuxMMAC.assignSeinfoValue(pkg); 5431 } 5432 5433 pkg.applicationInfo.uid = pkgSetting.appId; 5434 pkg.mExtras = pkgSetting; 5435 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5436 try { 5437 verifySignaturesLP(pkgSetting, pkg); 5438 // We just determined the app is signed correctly, so bring 5439 // over the latest parsed certs. 5440 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5441 } catch (PackageManagerException e) { 5442 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5443 throw e; 5444 } 5445 // The signature has changed, but this package is in the system 5446 // image... let's recover! 5447 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5448 // However... if this package is part of a shared user, but it 5449 // doesn't match the signature of the shared user, let's fail. 5450 // What this means is that you can't change the signatures 5451 // associated with an overall shared user, which doesn't seem all 5452 // that unreasonable. 5453 if (pkgSetting.sharedUser != null) { 5454 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5455 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5456 throw new PackageManagerException( 5457 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5458 "Signature mismatch for shared user : " 5459 + pkgSetting.sharedUser); 5460 } 5461 } 5462 // File a report about this. 5463 String msg = "System package " + pkg.packageName 5464 + " signature changed; retaining data."; 5465 reportSettingsProblem(Log.WARN, msg); 5466 } 5467 } else { 5468 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5469 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5470 + pkg.packageName + " upgrade keys do not match the " 5471 + "previously installed version"); 5472 } else { 5473 // We just determined the app is signed correctly, so bring 5474 // over the latest parsed certs. 5475 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5476 } 5477 } 5478 // Verify that this new package doesn't have any content providers 5479 // that conflict with existing packages. Only do this if the 5480 // package isn't already installed, since we don't want to break 5481 // things that are installed. 5482 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5483 final int N = pkg.providers.size(); 5484 int i; 5485 for (i=0; i<N; i++) { 5486 PackageParser.Provider p = pkg.providers.get(i); 5487 if (p.info.authority != null) { 5488 String names[] = p.info.authority.split(";"); 5489 for (int j = 0; j < names.length; j++) { 5490 if (mProvidersByAuthority.containsKey(names[j])) { 5491 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5492 final String otherPackageName = 5493 ((other != null && other.getComponentName() != null) ? 5494 other.getComponentName().getPackageName() : "?"); 5495 throw new PackageManagerException( 5496 INSTALL_FAILED_CONFLICTING_PROVIDER, 5497 "Can't install because provider name " + names[j] 5498 + " (in package " + pkg.applicationInfo.packageName 5499 + ") is already used by " + otherPackageName); 5500 } 5501 } 5502 } 5503 } 5504 } 5505 5506 if (pkg.mAdoptPermissions != null) { 5507 // This package wants to adopt ownership of permissions from 5508 // another package. 5509 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5510 final String origName = pkg.mAdoptPermissions.get(i); 5511 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5512 if (orig != null) { 5513 if (verifyPackageUpdateLPr(orig, pkg)) { 5514 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5515 + pkg.packageName); 5516 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5517 } 5518 } 5519 } 5520 } 5521 } 5522 5523 final String pkgName = pkg.packageName; 5524 5525 final long scanFileTime = scanFile.lastModified(); 5526 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5527 pkg.applicationInfo.processName = fixProcessName( 5528 pkg.applicationInfo.packageName, 5529 pkg.applicationInfo.processName, 5530 pkg.applicationInfo.uid); 5531 5532 File dataPath; 5533 if (mPlatformPackage == pkg) { 5534 // The system package is special. 5535 dataPath = new File(Environment.getDataDirectory(), "system"); 5536 5537 pkg.applicationInfo.dataDir = dataPath.getPath(); 5538 5539 } else { 5540 // This is a normal package, need to make its data directory. 5541 dataPath = getDataPathForPackage(pkg.packageName, 0); 5542 5543 boolean uidError = false; 5544 if (dataPath.exists()) { 5545 int currentUid = 0; 5546 try { 5547 StructStat stat = Os.stat(dataPath.getPath()); 5548 currentUid = stat.st_uid; 5549 } catch (ErrnoException e) { 5550 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5551 } 5552 5553 // If we have mismatched owners for the data path, we have a problem. 5554 if (currentUid != pkg.applicationInfo.uid) { 5555 boolean recovered = false; 5556 if (currentUid == 0) { 5557 // The directory somehow became owned by root. Wow. 5558 // This is probably because the system was stopped while 5559 // installd was in the middle of messing with its libs 5560 // directory. Ask installd to fix that. 5561 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5562 pkg.applicationInfo.uid); 5563 if (ret >= 0) { 5564 recovered = true; 5565 String msg = "Package " + pkg.packageName 5566 + " unexpectedly changed to uid 0; recovered to " + 5567 + pkg.applicationInfo.uid; 5568 reportSettingsProblem(Log.WARN, msg); 5569 } 5570 } 5571 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5572 || (scanFlags&SCAN_BOOTING) != 0)) { 5573 // If this is a system app, we can at least delete its 5574 // current data so the application will still work. 5575 int ret = removeDataDirsLI(pkgName); 5576 if (ret >= 0) { 5577 // TODO: Kill the processes first 5578 // Old data gone! 5579 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5580 ? "System package " : "Third party package "; 5581 String msg = prefix + pkg.packageName 5582 + " has changed from uid: " 5583 + currentUid + " to " 5584 + pkg.applicationInfo.uid + "; old data erased"; 5585 reportSettingsProblem(Log.WARN, msg); 5586 recovered = true; 5587 5588 // And now re-install the app. 5589 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5590 pkg.applicationInfo.seinfo); 5591 if (ret == -1) { 5592 // Ack should not happen! 5593 msg = prefix + pkg.packageName 5594 + " could not have data directory re-created after delete."; 5595 reportSettingsProblem(Log.WARN, msg); 5596 throw new PackageManagerException( 5597 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5598 } 5599 } 5600 if (!recovered) { 5601 mHasSystemUidErrors = true; 5602 } 5603 } else if (!recovered) { 5604 // If we allow this install to proceed, we will be broken. 5605 // Abort, abort! 5606 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5607 "scanPackageLI"); 5608 } 5609 if (!recovered) { 5610 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5611 + pkg.applicationInfo.uid + "/fs_" 5612 + currentUid; 5613 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5614 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5615 String msg = "Package " + pkg.packageName 5616 + " has mismatched uid: " 5617 + currentUid + " on disk, " 5618 + pkg.applicationInfo.uid + " in settings"; 5619 // writer 5620 synchronized (mPackages) { 5621 mSettings.mReadMessages.append(msg); 5622 mSettings.mReadMessages.append('\n'); 5623 uidError = true; 5624 if (!pkgSetting.uidError) { 5625 reportSettingsProblem(Log.ERROR, msg); 5626 } 5627 } 5628 } 5629 } 5630 pkg.applicationInfo.dataDir = dataPath.getPath(); 5631 if (mShouldRestoreconData) { 5632 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5633 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5634 pkg.applicationInfo.uid); 5635 } 5636 } else { 5637 if (DEBUG_PACKAGE_SCANNING) { 5638 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5639 Log.v(TAG, "Want this data dir: " + dataPath); 5640 } 5641 //invoke installer to do the actual installation 5642 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5643 pkg.applicationInfo.seinfo); 5644 if (ret < 0) { 5645 // Error from installer 5646 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5647 "Unable to create data dirs [errorCode=" + ret + "]"); 5648 } 5649 5650 if (dataPath.exists()) { 5651 pkg.applicationInfo.dataDir = dataPath.getPath(); 5652 } else { 5653 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5654 pkg.applicationInfo.dataDir = null; 5655 } 5656 } 5657 5658 pkgSetting.uidError = uidError; 5659 } 5660 5661 final String path = scanFile.getPath(); 5662 final String codePath = pkg.applicationInfo.getCodePath(); 5663 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5664 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5665 setBundledAppAbisAndRoots(pkg, pkgSetting); 5666 5667 // If we haven't found any native libraries for the app, check if it has 5668 // renderscript code. We'll need to force the app to 32 bit if it has 5669 // renderscript bitcode. 5670 if (pkg.applicationInfo.primaryCpuAbi == null 5671 && pkg.applicationInfo.secondaryCpuAbi == null 5672 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5673 NativeLibraryHelper.Handle handle = null; 5674 try { 5675 handle = NativeLibraryHelper.Handle.create(scanFile); 5676 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5677 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5678 } 5679 } catch (IOException ioe) { 5680 Slog.w(TAG, "Error scanning system app : " + ioe); 5681 } finally { 5682 IoUtils.closeQuietly(handle); 5683 } 5684 } 5685 5686 setNativeLibraryPaths(pkg); 5687 } else { 5688 // TODO: We can probably be smarter about this stuff. For installed apps, 5689 // we can calculate this information at install time once and for all. For 5690 // system apps, we can probably assume that this information doesn't change 5691 // after the first boot scan. As things stand, we do lots of unnecessary work. 5692 5693 // Give ourselves some initial paths; we'll come back for another 5694 // pass once we've determined ABI below. 5695 setNativeLibraryPaths(pkg); 5696 5697 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5698 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5699 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5700 5701 NativeLibraryHelper.Handle handle = null; 5702 try { 5703 handle = NativeLibraryHelper.Handle.create(scanFile); 5704 // TODO(multiArch): This can be null for apps that didn't go through the 5705 // usual installation process. We can calculate it again, like we 5706 // do during install time. 5707 // 5708 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5709 // unnecessary. 5710 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5711 5712 // Null out the abis so that they can be recalculated. 5713 pkg.applicationInfo.primaryCpuAbi = null; 5714 pkg.applicationInfo.secondaryCpuAbi = null; 5715 if (isMultiArch(pkg.applicationInfo)) { 5716 // Warn if we've set an abiOverride for multi-lib packages.. 5717 // By definition, we need to copy both 32 and 64 bit libraries for 5718 // such packages. 5719 if (pkg.cpuAbiOverride != null 5720 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5721 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5722 } 5723 5724 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5725 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5726 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5727 if (isAsec) { 5728 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5729 } else { 5730 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5731 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5732 useIsaSpecificSubdirs); 5733 } 5734 } 5735 5736 maybeThrowExceptionForMultiArchCopy( 5737 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5738 5739 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5740 if (isAsec) { 5741 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5742 } else { 5743 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5744 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5745 useIsaSpecificSubdirs); 5746 } 5747 } 5748 5749 maybeThrowExceptionForMultiArchCopy( 5750 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5751 5752 if (abi64 >= 0) { 5753 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5754 } 5755 5756 if (abi32 >= 0) { 5757 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5758 if (abi64 >= 0) { 5759 pkg.applicationInfo.secondaryCpuAbi = abi; 5760 } else { 5761 pkg.applicationInfo.primaryCpuAbi = abi; 5762 } 5763 } 5764 } else { 5765 String[] abiList = (cpuAbiOverride != null) ? 5766 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5767 5768 // Enable gross and lame hacks for apps that are built with old 5769 // SDK tools. We must scan their APKs for renderscript bitcode and 5770 // not launch them if it's present. Don't bother checking on devices 5771 // that don't have 64 bit support. 5772 boolean needsRenderScriptOverride = false; 5773 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5774 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5775 abiList = Build.SUPPORTED_32_BIT_ABIS; 5776 needsRenderScriptOverride = true; 5777 } 5778 5779 final int copyRet; 5780 if (isAsec) { 5781 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5782 } else { 5783 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5784 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5785 } 5786 5787 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5788 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5789 "Error unpackaging native libs for app, errorCode=" + copyRet); 5790 } 5791 5792 if (copyRet >= 0) { 5793 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5794 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5795 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5796 } else if (needsRenderScriptOverride) { 5797 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5798 } 5799 } 5800 } catch (IOException ioe) { 5801 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5802 } finally { 5803 IoUtils.closeQuietly(handle); 5804 } 5805 5806 // Now that we've calculated the ABIs and determined if it's an internal app, 5807 // we will go ahead and populate the nativeLibraryPath. 5808 setNativeLibraryPaths(pkg); 5809 5810 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5811 final int[] userIds = sUserManager.getUserIds(); 5812 synchronized (mInstallLock) { 5813 // Create a native library symlink only if we have native libraries 5814 // and if the native libraries are 32 bit libraries. We do not provide 5815 // this symlink for 64 bit libraries. 5816 if (pkg.applicationInfo.primaryCpuAbi != null && 5817 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5818 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5819 for (int userId : userIds) { 5820 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5821 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5822 "Failed linking native library dir (user=" + userId + ")"); 5823 } 5824 } 5825 } 5826 } 5827 } 5828 5829 // This is a special case for the "system" package, where the ABI is 5830 // dictated by the zygote configuration (and init.rc). We should keep track 5831 // of this ABI so that we can deal with "normal" applications that run under 5832 // the same UID correctly. 5833 if (mPlatformPackage == pkg) { 5834 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5835 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5836 } 5837 5838 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5839 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5840 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5841 // Copy the derived override back to the parsed package, so that we can 5842 // update the package settings accordingly. 5843 pkg.cpuAbiOverride = cpuAbiOverride; 5844 5845 if (DEBUG_ABI_SELECTION) { 5846 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5847 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5848 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5849 } 5850 5851 // Push the derived path down into PackageSettings so we know what to 5852 // clean up at uninstall time. 5853 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5854 5855 if (DEBUG_ABI_SELECTION) { 5856 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5857 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5858 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5859 } 5860 5861 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5862 // We don't do this here during boot because we can do it all 5863 // at once after scanning all existing packages. 5864 // 5865 // We also do this *before* we perform dexopt on this package, so that 5866 // we can avoid redundant dexopts, and also to make sure we've got the 5867 // code and package path correct. 5868 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5869 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5870 } 5871 5872 if ((scanFlags & SCAN_NO_DEX) == 0) { 5873 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, 5874 (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { 5875 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5876 } 5877 } 5878 5879 if (mFactoryTest && pkg.requestedPermissions.contains( 5880 android.Manifest.permission.FACTORY_TEST)) { 5881 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5882 } 5883 5884 ArrayList<PackageParser.Package> clientLibPkgs = null; 5885 5886 // writer 5887 synchronized (mPackages) { 5888 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5889 // Only system apps can add new shared libraries. 5890 if (pkg.libraryNames != null) { 5891 for (int i=0; i<pkg.libraryNames.size(); i++) { 5892 String name = pkg.libraryNames.get(i); 5893 boolean allowed = false; 5894 if (isUpdatedSystemApp(pkg)) { 5895 // New library entries can only be added through the 5896 // system image. This is important to get rid of a lot 5897 // of nasty edge cases: for example if we allowed a non- 5898 // system update of the app to add a library, then uninstalling 5899 // the update would make the library go away, and assumptions 5900 // we made such as through app install filtering would now 5901 // have allowed apps on the device which aren't compatible 5902 // with it. Better to just have the restriction here, be 5903 // conservative, and create many fewer cases that can negatively 5904 // impact the user experience. 5905 final PackageSetting sysPs = mSettings 5906 .getDisabledSystemPkgLPr(pkg.packageName); 5907 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5908 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5909 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5910 allowed = true; 5911 allowed = true; 5912 break; 5913 } 5914 } 5915 } 5916 } else { 5917 allowed = true; 5918 } 5919 if (allowed) { 5920 if (!mSharedLibraries.containsKey(name)) { 5921 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5922 } else if (!name.equals(pkg.packageName)) { 5923 Slog.w(TAG, "Package " + pkg.packageName + " library " 5924 + name + " already exists; skipping"); 5925 } 5926 } else { 5927 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5928 + name + " that is not declared on system image; skipping"); 5929 } 5930 } 5931 if ((scanFlags&SCAN_BOOTING) == 0) { 5932 // If we are not booting, we need to update any applications 5933 // that are clients of our shared library. If we are booting, 5934 // this will all be done once the scan is complete. 5935 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5936 } 5937 } 5938 } 5939 } 5940 5941 // We also need to dexopt any apps that are dependent on this library. Note that 5942 // if these fail, we should abort the install since installing the library will 5943 // result in some apps being broken. 5944 if (clientLibPkgs != null) { 5945 if ((scanFlags & SCAN_NO_DEX) == 0) { 5946 for (int i = 0; i < clientLibPkgs.size(); i++) { 5947 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5948 if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex, 5949 (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { 5950 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5951 "scanPackageLI failed to dexopt clientLibPkgs"); 5952 } 5953 } 5954 } 5955 } 5956 5957 // Request the ActivityManager to kill the process(only for existing packages) 5958 // so that we do not end up in a confused state while the user is still using the older 5959 // version of the application while the new one gets installed. 5960 if ((scanFlags & SCAN_REPLACING) != 0) { 5961 killApplication(pkg.applicationInfo.packageName, 5962 pkg.applicationInfo.uid, "update pkg"); 5963 } 5964 5965 // Also need to kill any apps that are dependent on the library. 5966 if (clientLibPkgs != null) { 5967 for (int i=0; i<clientLibPkgs.size(); i++) { 5968 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5969 killApplication(clientPkg.applicationInfo.packageName, 5970 clientPkg.applicationInfo.uid, "update lib"); 5971 } 5972 } 5973 5974 // writer 5975 synchronized (mPackages) { 5976 // We don't expect installation to fail beyond this point 5977 5978 // Add the new setting to mSettings 5979 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5980 // Add the new setting to mPackages 5981 mPackages.put(pkg.applicationInfo.packageName, pkg); 5982 // Make sure we don't accidentally delete its data. 5983 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5984 while (iter.hasNext()) { 5985 PackageCleanItem item = iter.next(); 5986 if (pkgName.equals(item.packageName)) { 5987 iter.remove(); 5988 } 5989 } 5990 5991 // Take care of first install / last update times. 5992 if (currentTime != 0) { 5993 if (pkgSetting.firstInstallTime == 0) { 5994 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5995 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5996 pkgSetting.lastUpdateTime = currentTime; 5997 } 5998 } else if (pkgSetting.firstInstallTime == 0) { 5999 // We need *something*. Take time time stamp of the file. 6000 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6001 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6002 if (scanFileTime != pkgSetting.timeStamp) { 6003 // A package on the system image has changed; consider this 6004 // to be an update. 6005 pkgSetting.lastUpdateTime = scanFileTime; 6006 } 6007 } 6008 6009 // Add the package's KeySets to the global KeySetManagerService 6010 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6011 try { 6012 // Old KeySetData no longer valid. 6013 ksms.removeAppKeySetDataLPw(pkg.packageName); 6014 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6015 if (pkg.mKeySetMapping != null) { 6016 for (Map.Entry<String, ArraySet<PublicKey>> entry : 6017 pkg.mKeySetMapping.entrySet()) { 6018 if (entry.getValue() != null) { 6019 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 6020 entry.getValue(), entry.getKey()); 6021 } 6022 } 6023 if (pkg.mUpgradeKeySets != null) { 6024 for (String upgradeAlias : pkg.mUpgradeKeySets) { 6025 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 6026 } 6027 } 6028 } 6029 } catch (NullPointerException e) { 6030 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6031 } catch (IllegalArgumentException e) { 6032 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6033 } 6034 6035 int N = pkg.providers.size(); 6036 StringBuilder r = null; 6037 int i; 6038 for (i=0; i<N; i++) { 6039 PackageParser.Provider p = pkg.providers.get(i); 6040 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6041 p.info.processName, pkg.applicationInfo.uid); 6042 mProviders.addProvider(p); 6043 p.syncable = p.info.isSyncable; 6044 if (p.info.authority != null) { 6045 String names[] = p.info.authority.split(";"); 6046 p.info.authority = null; 6047 for (int j = 0; j < names.length; j++) { 6048 if (j == 1 && p.syncable) { 6049 // We only want the first authority for a provider to possibly be 6050 // syncable, so if we already added this provider using a different 6051 // authority clear the syncable flag. We copy the provider before 6052 // changing it because the mProviders object contains a reference 6053 // to a provider that we don't want to change. 6054 // Only do this for the second authority since the resulting provider 6055 // object can be the same for all future authorities for this provider. 6056 p = new PackageParser.Provider(p); 6057 p.syncable = false; 6058 } 6059 if (!mProvidersByAuthority.containsKey(names[j])) { 6060 mProvidersByAuthority.put(names[j], p); 6061 if (p.info.authority == null) { 6062 p.info.authority = names[j]; 6063 } else { 6064 p.info.authority = p.info.authority + ";" + names[j]; 6065 } 6066 if (DEBUG_PACKAGE_SCANNING) { 6067 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6068 Log.d(TAG, "Registered content provider: " + names[j] 6069 + ", className = " + p.info.name + ", isSyncable = " 6070 + p.info.isSyncable); 6071 } 6072 } else { 6073 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6074 Slog.w(TAG, "Skipping provider name " + names[j] + 6075 " (in package " + pkg.applicationInfo.packageName + 6076 "): name already used by " 6077 + ((other != null && other.getComponentName() != null) 6078 ? other.getComponentName().getPackageName() : "?")); 6079 } 6080 } 6081 } 6082 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6083 if (r == null) { 6084 r = new StringBuilder(256); 6085 } else { 6086 r.append(' '); 6087 } 6088 r.append(p.info.name); 6089 } 6090 } 6091 if (r != null) { 6092 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6093 } 6094 6095 N = pkg.services.size(); 6096 r = null; 6097 for (i=0; i<N; i++) { 6098 PackageParser.Service s = pkg.services.get(i); 6099 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6100 s.info.processName, pkg.applicationInfo.uid); 6101 mServices.addService(s); 6102 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6103 if (r == null) { 6104 r = new StringBuilder(256); 6105 } else { 6106 r.append(' '); 6107 } 6108 r.append(s.info.name); 6109 } 6110 } 6111 if (r != null) { 6112 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6113 } 6114 6115 N = pkg.receivers.size(); 6116 r = null; 6117 for (i=0; i<N; i++) { 6118 PackageParser.Activity a = pkg.receivers.get(i); 6119 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6120 a.info.processName, pkg.applicationInfo.uid); 6121 mReceivers.addActivity(a, "receiver"); 6122 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6123 if (r == null) { 6124 r = new StringBuilder(256); 6125 } else { 6126 r.append(' '); 6127 } 6128 r.append(a.info.name); 6129 } 6130 } 6131 if (r != null) { 6132 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6133 } 6134 6135 N = pkg.activities.size(); 6136 r = null; 6137 for (i=0; i<N; i++) { 6138 PackageParser.Activity a = pkg.activities.get(i); 6139 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6140 a.info.processName, pkg.applicationInfo.uid); 6141 mActivities.addActivity(a, "activity"); 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(a.info.name); 6149 } 6150 } 6151 if (r != null) { 6152 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6153 } 6154 6155 N = pkg.permissionGroups.size(); 6156 r = null; 6157 for (i=0; i<N; i++) { 6158 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6159 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6160 if (cur == null) { 6161 mPermissionGroups.put(pg.info.name, pg); 6162 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6163 if (r == null) { 6164 r = new StringBuilder(256); 6165 } else { 6166 r.append(' '); 6167 } 6168 r.append(pg.info.name); 6169 } 6170 } else { 6171 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6172 + pg.info.packageName + " ignored: original from " 6173 + cur.info.packageName); 6174 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6175 if (r == null) { 6176 r = new StringBuilder(256); 6177 } else { 6178 r.append(' '); 6179 } 6180 r.append("DUP:"); 6181 r.append(pg.info.name); 6182 } 6183 } 6184 } 6185 if (r != null) { 6186 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6187 } 6188 6189 N = pkg.permissions.size(); 6190 r = null; 6191 for (i=0; i<N; i++) { 6192 PackageParser.Permission p = pkg.permissions.get(i); 6193 ArrayMap<String, BasePermission> permissionMap = 6194 p.tree ? mSettings.mPermissionTrees 6195 : mSettings.mPermissions; 6196 p.group = mPermissionGroups.get(p.info.group); 6197 if (p.info.group == null || p.group != null) { 6198 BasePermission bp = permissionMap.get(p.info.name); 6199 6200 // Allow system apps to redefine non-system permissions 6201 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6202 final boolean currentOwnerIsSystem = (bp.perm != null 6203 && isSystemApp(bp.perm.owner)); 6204 if (isSystemApp(p.owner)) { 6205 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6206 // It's a built-in permission and no owner, take ownership now 6207 bp.packageSetting = pkgSetting; 6208 bp.perm = p; 6209 bp.uid = pkg.applicationInfo.uid; 6210 bp.sourcePackage = p.info.packageName; 6211 } else if (!currentOwnerIsSystem) { 6212 String msg = "New decl " + p.owner + " of permission " 6213 + p.info.name + " is system; overriding " + bp.sourcePackage; 6214 reportSettingsProblem(Log.WARN, msg); 6215 bp = null; 6216 } 6217 } 6218 } 6219 6220 if (bp == null) { 6221 bp = new BasePermission(p.info.name, p.info.packageName, 6222 BasePermission.TYPE_NORMAL); 6223 permissionMap.put(p.info.name, bp); 6224 } 6225 6226 if (bp.perm == null) { 6227 if (bp.sourcePackage == null 6228 || bp.sourcePackage.equals(p.info.packageName)) { 6229 BasePermission tree = findPermissionTreeLP(p.info.name); 6230 if (tree == null 6231 || tree.sourcePackage.equals(p.info.packageName)) { 6232 bp.packageSetting = pkgSetting; 6233 bp.perm = p; 6234 bp.uid = pkg.applicationInfo.uid; 6235 bp.sourcePackage = p.info.packageName; 6236 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6237 if (r == null) { 6238 r = new StringBuilder(256); 6239 } else { 6240 r.append(' '); 6241 } 6242 r.append(p.info.name); 6243 } 6244 } else { 6245 Slog.w(TAG, "Permission " + p.info.name + " from package " 6246 + p.info.packageName + " ignored: base tree " 6247 + tree.name + " is from package " 6248 + tree.sourcePackage); 6249 } 6250 } else { 6251 Slog.w(TAG, "Permission " + p.info.name + " from package " 6252 + p.info.packageName + " ignored: original from " 6253 + bp.sourcePackage); 6254 } 6255 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6256 if (r == null) { 6257 r = new StringBuilder(256); 6258 } else { 6259 r.append(' '); 6260 } 6261 r.append("DUP:"); 6262 r.append(p.info.name); 6263 } 6264 if (bp.perm == p) { 6265 bp.protectionLevel = p.info.protectionLevel; 6266 } 6267 } else { 6268 Slog.w(TAG, "Permission " + p.info.name + " from package " 6269 + p.info.packageName + " ignored: no group " 6270 + p.group); 6271 } 6272 } 6273 if (r != null) { 6274 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6275 } 6276 6277 N = pkg.instrumentation.size(); 6278 r = null; 6279 for (i=0; i<N; i++) { 6280 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6281 a.info.packageName = pkg.applicationInfo.packageName; 6282 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6283 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6284 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6285 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6286 a.info.dataDir = pkg.applicationInfo.dataDir; 6287 6288 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6289 // need other information about the application, like the ABI and what not ? 6290 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6291 mInstrumentation.put(a.getComponentName(), a); 6292 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6293 if (r == null) { 6294 r = new StringBuilder(256); 6295 } else { 6296 r.append(' '); 6297 } 6298 r.append(a.info.name); 6299 } 6300 } 6301 if (r != null) { 6302 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6303 } 6304 6305 if (pkg.protectedBroadcasts != null) { 6306 N = pkg.protectedBroadcasts.size(); 6307 for (i=0; i<N; i++) { 6308 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6309 } 6310 } 6311 6312 pkgSetting.setTimeStamp(scanFileTime); 6313 6314 // Create idmap files for pairs of (packages, overlay packages). 6315 // Note: "android", ie framework-res.apk, is handled by native layers. 6316 if (pkg.mOverlayTarget != null) { 6317 // This is an overlay package. 6318 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6319 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6320 mOverlays.put(pkg.mOverlayTarget, 6321 new ArrayMap<String, PackageParser.Package>()); 6322 } 6323 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6324 map.put(pkg.packageName, pkg); 6325 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6326 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6327 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6328 "scanPackageLI failed to createIdmap"); 6329 } 6330 } 6331 } else if (mOverlays.containsKey(pkg.packageName) && 6332 !pkg.packageName.equals("android")) { 6333 // This is a regular package, with one or more known overlay packages. 6334 createIdmapsForPackageLI(pkg); 6335 } 6336 } 6337 6338 return pkg; 6339 } 6340 6341 /** 6342 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6343 * i.e, so that all packages can be run inside a single process if required. 6344 * 6345 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6346 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6347 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6348 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6349 * updating a package that belongs to a shared user. 6350 * 6351 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6352 * adds unnecessary complexity. 6353 */ 6354 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6355 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6356 String requiredInstructionSet = null; 6357 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6358 requiredInstructionSet = VMRuntime.getInstructionSet( 6359 scannedPackage.applicationInfo.primaryCpuAbi); 6360 } 6361 6362 PackageSetting requirer = null; 6363 for (PackageSetting ps : packagesForUser) { 6364 // If packagesForUser contains scannedPackage, we skip it. This will happen 6365 // when scannedPackage is an update of an existing package. Without this check, 6366 // we will never be able to change the ABI of any package belonging to a shared 6367 // user, even if it's compatible with other packages. 6368 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6369 if (ps.primaryCpuAbiString == null) { 6370 continue; 6371 } 6372 6373 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6374 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6375 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6376 // this but there's not much we can do. 6377 String errorMessage = "Instruction set mismatch, " 6378 + ((requirer == null) ? "[caller]" : requirer) 6379 + " requires " + requiredInstructionSet + " whereas " + ps 6380 + " requires " + instructionSet; 6381 Slog.w(TAG, errorMessage); 6382 } 6383 6384 if (requiredInstructionSet == null) { 6385 requiredInstructionSet = instructionSet; 6386 requirer = ps; 6387 } 6388 } 6389 } 6390 6391 if (requiredInstructionSet != null) { 6392 String adjustedAbi; 6393 if (requirer != null) { 6394 // requirer != null implies that either scannedPackage was null or that scannedPackage 6395 // did not require an ABI, in which case we have to adjust scannedPackage to match 6396 // the ABI of the set (which is the same as requirer's ABI) 6397 adjustedAbi = requirer.primaryCpuAbiString; 6398 if (scannedPackage != null) { 6399 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6400 } 6401 } else { 6402 // requirer == null implies that we're updating all ABIs in the set to 6403 // match scannedPackage. 6404 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6405 } 6406 6407 for (PackageSetting ps : packagesForUser) { 6408 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6409 if (ps.primaryCpuAbiString != null) { 6410 continue; 6411 } 6412 6413 ps.primaryCpuAbiString = adjustedAbi; 6414 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6415 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6416 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6417 6418 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6419 deferDexOpt, true) == DEX_OPT_FAILED) { 6420 ps.primaryCpuAbiString = null; 6421 ps.pkg.applicationInfo.primaryCpuAbi = null; 6422 return; 6423 } else { 6424 mInstaller.rmdex(ps.codePathString, 6425 getDexCodeInstructionSet(getPreferredInstructionSet())); 6426 } 6427 } 6428 } 6429 } 6430 } 6431 } 6432 6433 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6434 synchronized (mPackages) { 6435 mResolverReplaced = true; 6436 // Set up information for custom user intent resolution activity. 6437 mResolveActivity.applicationInfo = pkg.applicationInfo; 6438 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6439 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6440 mResolveActivity.processName = pkg.applicationInfo.packageName; 6441 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6442 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6443 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6444 mResolveActivity.theme = 0; 6445 mResolveActivity.exported = true; 6446 mResolveActivity.enabled = true; 6447 mResolveInfo.activityInfo = mResolveActivity; 6448 mResolveInfo.priority = 0; 6449 mResolveInfo.preferredOrder = 0; 6450 mResolveInfo.match = 0; 6451 mResolveComponentName = mCustomResolverComponentName; 6452 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6453 mResolveComponentName); 6454 } 6455 } 6456 6457 private static String calculateBundledApkRoot(final String codePathString) { 6458 final File codePath = new File(codePathString); 6459 final File codeRoot; 6460 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6461 codeRoot = Environment.getRootDirectory(); 6462 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6463 codeRoot = Environment.getOemDirectory(); 6464 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6465 codeRoot = Environment.getVendorDirectory(); 6466 } else { 6467 // Unrecognized code path; take its top real segment as the apk root: 6468 // e.g. /something/app/blah.apk => /something 6469 try { 6470 File f = codePath.getCanonicalFile(); 6471 File parent = f.getParentFile(); // non-null because codePath is a file 6472 File tmp; 6473 while ((tmp = parent.getParentFile()) != null) { 6474 f = parent; 6475 parent = tmp; 6476 } 6477 codeRoot = f; 6478 Slog.w(TAG, "Unrecognized code path " 6479 + codePath + " - using " + codeRoot); 6480 } catch (IOException e) { 6481 // Can't canonicalize the code path -- shenanigans? 6482 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6483 return Environment.getRootDirectory().getPath(); 6484 } 6485 } 6486 return codeRoot.getPath(); 6487 } 6488 6489 /** 6490 * Derive and set the location of native libraries for the given package, 6491 * which varies depending on where and how the package was installed. 6492 */ 6493 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6494 final ApplicationInfo info = pkg.applicationInfo; 6495 final String codePath = pkg.codePath; 6496 final File codeFile = new File(codePath); 6497 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6498 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6499 6500 info.nativeLibraryRootDir = null; 6501 info.nativeLibraryRootRequiresIsa = false; 6502 info.nativeLibraryDir = null; 6503 info.secondaryNativeLibraryDir = null; 6504 6505 if (isApkFile(codeFile)) { 6506 // Monolithic install 6507 if (bundledApp) { 6508 // If "/system/lib64/apkname" exists, assume that is the per-package 6509 // native library directory to use; otherwise use "/system/lib/apkname". 6510 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6511 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6512 getPrimaryInstructionSet(info)); 6513 6514 // This is a bundled system app so choose the path based on the ABI. 6515 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6516 // is just the default path. 6517 final String apkName = deriveCodePathName(codePath); 6518 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6519 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6520 apkName).getAbsolutePath(); 6521 6522 if (info.secondaryCpuAbi != null) { 6523 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6524 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6525 secondaryLibDir, apkName).getAbsolutePath(); 6526 } 6527 } else if (asecApp) { 6528 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6529 .getAbsolutePath(); 6530 } else { 6531 final String apkName = deriveCodePathName(codePath); 6532 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6533 .getAbsolutePath(); 6534 } 6535 6536 info.nativeLibraryRootRequiresIsa = false; 6537 info.nativeLibraryDir = info.nativeLibraryRootDir; 6538 } else { 6539 // Cluster install 6540 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6541 info.nativeLibraryRootRequiresIsa = true; 6542 6543 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6544 getPrimaryInstructionSet(info)).getAbsolutePath(); 6545 6546 if (info.secondaryCpuAbi != null) { 6547 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6548 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6549 } 6550 } 6551 } 6552 6553 /** 6554 * Calculate the abis and roots for a bundled app. These can uniquely 6555 * be determined from the contents of the system partition, i.e whether 6556 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6557 * of this information, and instead assume that the system was built 6558 * sensibly. 6559 */ 6560 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6561 PackageSetting pkgSetting) { 6562 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6563 6564 // If "/system/lib64/apkname" exists, assume that is the per-package 6565 // native library directory to use; otherwise use "/system/lib/apkname". 6566 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6567 setBundledAppAbi(pkg, apkRoot, apkName); 6568 // pkgSetting might be null during rescan following uninstall of updates 6569 // to a bundled app, so accommodate that possibility. The settings in 6570 // that case will be established later from the parsed package. 6571 // 6572 // If the settings aren't null, sync them up with what we've just derived. 6573 // note that apkRoot isn't stored in the package settings. 6574 if (pkgSetting != null) { 6575 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6576 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6577 } 6578 } 6579 6580 /** 6581 * Deduces the ABI of a bundled app and sets the relevant fields on the 6582 * parsed pkg object. 6583 * 6584 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6585 * under which system libraries are installed. 6586 * @param apkName the name of the installed package. 6587 */ 6588 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6589 final File codeFile = new File(pkg.codePath); 6590 6591 final boolean has64BitLibs; 6592 final boolean has32BitLibs; 6593 if (isApkFile(codeFile)) { 6594 // Monolithic install 6595 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6596 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6597 } else { 6598 // Cluster install 6599 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6600 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6601 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6602 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6603 has64BitLibs = (new File(rootDir, isa)).exists(); 6604 } else { 6605 has64BitLibs = false; 6606 } 6607 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6608 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6609 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6610 has32BitLibs = (new File(rootDir, isa)).exists(); 6611 } else { 6612 has32BitLibs = false; 6613 } 6614 } 6615 6616 if (has64BitLibs && !has32BitLibs) { 6617 // The package has 64 bit libs, but not 32 bit libs. Its primary 6618 // ABI should be 64 bit. We can safely assume here that the bundled 6619 // native libraries correspond to the most preferred ABI in the list. 6620 6621 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6622 pkg.applicationInfo.secondaryCpuAbi = null; 6623 } else if (has32BitLibs && !has64BitLibs) { 6624 // The package has 32 bit libs but not 64 bit libs. Its primary 6625 // ABI should be 32 bit. 6626 6627 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6628 pkg.applicationInfo.secondaryCpuAbi = null; 6629 } else if (has32BitLibs && has64BitLibs) { 6630 // The application has both 64 and 32 bit bundled libraries. We check 6631 // here that the app declares multiArch support, and warn if it doesn't. 6632 // 6633 // We will be lenient here and record both ABIs. The primary will be the 6634 // ABI that's higher on the list, i.e, a device that's configured to prefer 6635 // 64 bit apps will see a 64 bit primary ABI, 6636 6637 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6638 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6639 } 6640 6641 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6642 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6643 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6644 } else { 6645 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6646 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6647 } 6648 } else { 6649 pkg.applicationInfo.primaryCpuAbi = null; 6650 pkg.applicationInfo.secondaryCpuAbi = null; 6651 } 6652 } 6653 6654 private void killApplication(String pkgName, int appId, String reason) { 6655 // Request the ActivityManager to kill the process(only for existing packages) 6656 // so that we do not end up in a confused state while the user is still using the older 6657 // version of the application while the new one gets installed. 6658 IActivityManager am = ActivityManagerNative.getDefault(); 6659 if (am != null) { 6660 try { 6661 am.killApplicationWithAppId(pkgName, appId, reason); 6662 } catch (RemoteException e) { 6663 } 6664 } 6665 } 6666 6667 void removePackageLI(PackageSetting ps, boolean chatty) { 6668 if (DEBUG_INSTALL) { 6669 if (chatty) 6670 Log.d(TAG, "Removing package " + ps.name); 6671 } 6672 6673 // writer 6674 synchronized (mPackages) { 6675 mPackages.remove(ps.name); 6676 final PackageParser.Package pkg = ps.pkg; 6677 if (pkg != null) { 6678 cleanPackageDataStructuresLILPw(pkg, chatty); 6679 } 6680 } 6681 } 6682 6683 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6684 if (DEBUG_INSTALL) { 6685 if (chatty) 6686 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6687 } 6688 6689 // writer 6690 synchronized (mPackages) { 6691 mPackages.remove(pkg.applicationInfo.packageName); 6692 cleanPackageDataStructuresLILPw(pkg, chatty); 6693 } 6694 } 6695 6696 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6697 int N = pkg.providers.size(); 6698 StringBuilder r = null; 6699 int i; 6700 for (i=0; i<N; i++) { 6701 PackageParser.Provider p = pkg.providers.get(i); 6702 mProviders.removeProvider(p); 6703 if (p.info.authority == null) { 6704 6705 /* There was another ContentProvider with this authority when 6706 * this app was installed so this authority is null, 6707 * Ignore it as we don't have to unregister the provider. 6708 */ 6709 continue; 6710 } 6711 String names[] = p.info.authority.split(";"); 6712 for (int j = 0; j < names.length; j++) { 6713 if (mProvidersByAuthority.get(names[j]) == p) { 6714 mProvidersByAuthority.remove(names[j]); 6715 if (DEBUG_REMOVE) { 6716 if (chatty) 6717 Log.d(TAG, "Unregistered content provider: " + names[j] 6718 + ", className = " + p.info.name + ", isSyncable = " 6719 + p.info.isSyncable); 6720 } 6721 } 6722 } 6723 if (DEBUG_REMOVE && chatty) { 6724 if (r == null) { 6725 r = new StringBuilder(256); 6726 } else { 6727 r.append(' '); 6728 } 6729 r.append(p.info.name); 6730 } 6731 } 6732 if (r != null) { 6733 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6734 } 6735 6736 N = pkg.services.size(); 6737 r = null; 6738 for (i=0; i<N; i++) { 6739 PackageParser.Service s = pkg.services.get(i); 6740 mServices.removeService(s); 6741 if (chatty) { 6742 if (r == null) { 6743 r = new StringBuilder(256); 6744 } else { 6745 r.append(' '); 6746 } 6747 r.append(s.info.name); 6748 } 6749 } 6750 if (r != null) { 6751 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6752 } 6753 6754 N = pkg.receivers.size(); 6755 r = null; 6756 for (i=0; i<N; i++) { 6757 PackageParser.Activity a = pkg.receivers.get(i); 6758 mReceivers.removeActivity(a, "receiver"); 6759 if (DEBUG_REMOVE && chatty) { 6760 if (r == null) { 6761 r = new StringBuilder(256); 6762 } else { 6763 r.append(' '); 6764 } 6765 r.append(a.info.name); 6766 } 6767 } 6768 if (r != null) { 6769 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6770 } 6771 6772 N = pkg.activities.size(); 6773 r = null; 6774 for (i=0; i<N; i++) { 6775 PackageParser.Activity a = pkg.activities.get(i); 6776 mActivities.removeActivity(a, "activity"); 6777 if (DEBUG_REMOVE && chatty) { 6778 if (r == null) { 6779 r = new StringBuilder(256); 6780 } else { 6781 r.append(' '); 6782 } 6783 r.append(a.info.name); 6784 } 6785 } 6786 if (r != null) { 6787 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6788 } 6789 6790 N = pkg.permissions.size(); 6791 r = null; 6792 for (i=0; i<N; i++) { 6793 PackageParser.Permission p = pkg.permissions.get(i); 6794 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6795 if (bp == null) { 6796 bp = mSettings.mPermissionTrees.get(p.info.name); 6797 } 6798 if (bp != null && bp.perm == p) { 6799 bp.perm = null; 6800 if (DEBUG_REMOVE && chatty) { 6801 if (r == null) { 6802 r = new StringBuilder(256); 6803 } else { 6804 r.append(' '); 6805 } 6806 r.append(p.info.name); 6807 } 6808 } 6809 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6810 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6811 if (appOpPerms != null) { 6812 appOpPerms.remove(pkg.packageName); 6813 } 6814 } 6815 } 6816 if (r != null) { 6817 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6818 } 6819 6820 N = pkg.requestedPermissions.size(); 6821 r = null; 6822 for (i=0; i<N; i++) { 6823 String perm = pkg.requestedPermissions.get(i); 6824 BasePermission bp = mSettings.mPermissions.get(perm); 6825 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6826 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6827 if (appOpPerms != null) { 6828 appOpPerms.remove(pkg.packageName); 6829 if (appOpPerms.isEmpty()) { 6830 mAppOpPermissionPackages.remove(perm); 6831 } 6832 } 6833 } 6834 } 6835 if (r != null) { 6836 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6837 } 6838 6839 N = pkg.instrumentation.size(); 6840 r = null; 6841 for (i=0; i<N; i++) { 6842 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6843 mInstrumentation.remove(a.getComponentName()); 6844 if (DEBUG_REMOVE && chatty) { 6845 if (r == null) { 6846 r = new StringBuilder(256); 6847 } else { 6848 r.append(' '); 6849 } 6850 r.append(a.info.name); 6851 } 6852 } 6853 if (r != null) { 6854 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6855 } 6856 6857 r = null; 6858 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6859 // Only system apps can hold shared libraries. 6860 if (pkg.libraryNames != null) { 6861 for (i=0; i<pkg.libraryNames.size(); i++) { 6862 String name = pkg.libraryNames.get(i); 6863 SharedLibraryEntry cur = mSharedLibraries.get(name); 6864 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6865 mSharedLibraries.remove(name); 6866 if (DEBUG_REMOVE && chatty) { 6867 if (r == null) { 6868 r = new StringBuilder(256); 6869 } else { 6870 r.append(' '); 6871 } 6872 r.append(name); 6873 } 6874 } 6875 } 6876 } 6877 } 6878 if (r != null) { 6879 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6880 } 6881 } 6882 6883 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6884 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6885 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6886 return true; 6887 } 6888 } 6889 return false; 6890 } 6891 6892 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6893 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6894 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6895 6896 private void updatePermissionsLPw(String changingPkg, 6897 PackageParser.Package pkgInfo, int flags) { 6898 // Make sure there are no dangling permission trees. 6899 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6900 while (it.hasNext()) { 6901 final BasePermission bp = it.next(); 6902 if (bp.packageSetting == null) { 6903 // We may not yet have parsed the package, so just see if 6904 // we still know about its settings. 6905 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6906 } 6907 if (bp.packageSetting == null) { 6908 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6909 + " from package " + bp.sourcePackage); 6910 it.remove(); 6911 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6912 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6913 Slog.i(TAG, "Removing old permission tree: " + bp.name 6914 + " from package " + bp.sourcePackage); 6915 flags |= UPDATE_PERMISSIONS_ALL; 6916 it.remove(); 6917 } 6918 } 6919 } 6920 6921 // Make sure all dynamic permissions have been assigned to a package, 6922 // and make sure there are no dangling permissions. 6923 it = mSettings.mPermissions.values().iterator(); 6924 while (it.hasNext()) { 6925 final BasePermission bp = it.next(); 6926 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6927 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6928 + bp.name + " pkg=" + bp.sourcePackage 6929 + " info=" + bp.pendingInfo); 6930 if (bp.packageSetting == null && bp.pendingInfo != null) { 6931 final BasePermission tree = findPermissionTreeLP(bp.name); 6932 if (tree != null && tree.perm != null) { 6933 bp.packageSetting = tree.packageSetting; 6934 bp.perm = new PackageParser.Permission(tree.perm.owner, 6935 new PermissionInfo(bp.pendingInfo)); 6936 bp.perm.info.packageName = tree.perm.info.packageName; 6937 bp.perm.info.name = bp.name; 6938 bp.uid = tree.uid; 6939 } 6940 } 6941 } 6942 if (bp.packageSetting == null) { 6943 // We may not yet have parsed the package, so just see if 6944 // we still know about its settings. 6945 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6946 } 6947 if (bp.packageSetting == null) { 6948 Slog.w(TAG, "Removing dangling permission: " + bp.name 6949 + " from package " + bp.sourcePackage); 6950 it.remove(); 6951 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6952 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6953 Slog.i(TAG, "Removing old permission: " + bp.name 6954 + " from package " + bp.sourcePackage); 6955 flags |= UPDATE_PERMISSIONS_ALL; 6956 it.remove(); 6957 } 6958 } 6959 } 6960 6961 // Now update the permissions for all packages, in particular 6962 // replace the granted permissions of the system packages. 6963 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6964 for (PackageParser.Package pkg : mPackages.values()) { 6965 if (pkg != pkgInfo) { 6966 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 6967 changingPkg); 6968 } 6969 } 6970 } 6971 6972 if (pkgInfo != null) { 6973 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 6974 } 6975 } 6976 6977 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 6978 String packageOfInterest) { 6979 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6980 if (ps == null) { 6981 return; 6982 } 6983 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6984 ArraySet<String> origPermissions = gp.grantedPermissions; 6985 boolean changedPermission = false; 6986 6987 if (replace) { 6988 ps.permissionsFixed = false; 6989 if (gp == ps) { 6990 origPermissions = new ArraySet<String>(gp.grantedPermissions); 6991 gp.grantedPermissions.clear(); 6992 gp.gids = mGlobalGids; 6993 } 6994 } 6995 6996 if (gp.gids == null) { 6997 gp.gids = mGlobalGids; 6998 } 6999 7000 final int N = pkg.requestedPermissions.size(); 7001 for (int i=0; i<N; i++) { 7002 final String name = pkg.requestedPermissions.get(i); 7003 final boolean required = pkg.requestedPermissionsRequired.get(i); 7004 final BasePermission bp = mSettings.mPermissions.get(name); 7005 if (DEBUG_INSTALL) { 7006 if (gp != ps) { 7007 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7008 } 7009 } 7010 7011 if (bp == null || bp.packageSetting == null) { 7012 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7013 Slog.w(TAG, "Unknown permission " + name 7014 + " in package " + pkg.packageName); 7015 } 7016 continue; 7017 } 7018 7019 final String perm = bp.name; 7020 boolean allowed; 7021 boolean allowedSig = false; 7022 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7023 // Keep track of app op permissions. 7024 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7025 if (pkgs == null) { 7026 pkgs = new ArraySet<>(); 7027 mAppOpPermissionPackages.put(bp.name, pkgs); 7028 } 7029 pkgs.add(pkg.packageName); 7030 } 7031 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7032 if (level == PermissionInfo.PROTECTION_NORMAL 7033 || level == PermissionInfo.PROTECTION_DANGEROUS) { 7034 // We grant a normal or dangerous permission if any of the following 7035 // are true: 7036 // 1) The permission is required 7037 // 2) The permission is optional, but was granted in the past 7038 // 3) The permission is optional, but was requested by an 7039 // app in /system (not /data) 7040 // 7041 // Otherwise, reject the permission. 7042 allowed = (required || origPermissions.contains(perm) 7043 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 7044 } else if (bp.packageSetting == null) { 7045 // This permission is invalid; skip it. 7046 allowed = false; 7047 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 7048 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 7049 if (allowed) { 7050 allowedSig = true; 7051 } 7052 } else { 7053 allowed = false; 7054 } 7055 if (DEBUG_INSTALL) { 7056 if (gp != ps) { 7057 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7058 } 7059 } 7060 if (allowed) { 7061 if (!isSystemApp(ps) && ps.permissionsFixed) { 7062 // If this is an existing, non-system package, then 7063 // we can't add any new permissions to it. 7064 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 7065 // Except... if this is a permission that was added 7066 // to the platform (note: need to only do this when 7067 // updating the platform). 7068 allowed = isNewPlatformPermissionForPackage(perm, pkg); 7069 } 7070 } 7071 if (allowed) { 7072 if (!gp.grantedPermissions.contains(perm)) { 7073 changedPermission = true; 7074 gp.grantedPermissions.add(perm); 7075 gp.gids = appendInts(gp.gids, bp.gids); 7076 } else if (!ps.haveGids) { 7077 gp.gids = appendInts(gp.gids, bp.gids); 7078 } 7079 } else { 7080 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7081 Slog.w(TAG, "Not granting permission " + perm 7082 + " to package " + pkg.packageName 7083 + " because it was previously installed without"); 7084 } 7085 } 7086 } else { 7087 if (gp.grantedPermissions.remove(perm)) { 7088 changedPermission = true; 7089 gp.gids = removeInts(gp.gids, bp.gids); 7090 Slog.i(TAG, "Un-granting permission " + perm 7091 + " from package " + pkg.packageName 7092 + " (protectionLevel=" + bp.protectionLevel 7093 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7094 + ")"); 7095 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7096 // Don't print warning for app op permissions, since it is fine for them 7097 // not to be granted, there is a UI for the user to decide. 7098 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7099 Slog.w(TAG, "Not granting permission " + perm 7100 + " to package " + pkg.packageName 7101 + " (protectionLevel=" + bp.protectionLevel 7102 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7103 + ")"); 7104 } 7105 } 7106 } 7107 } 7108 7109 if ((changedPermission || replace) && !ps.permissionsFixed && 7110 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7111 // This is the first that we have heard about this package, so the 7112 // permissions we have now selected are fixed until explicitly 7113 // changed. 7114 ps.permissionsFixed = true; 7115 } 7116 ps.haveGids = true; 7117 } 7118 7119 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7120 boolean allowed = false; 7121 final int NP = PackageParser.NEW_PERMISSIONS.length; 7122 for (int ip=0; ip<NP; ip++) { 7123 final PackageParser.NewPermissionInfo npi 7124 = PackageParser.NEW_PERMISSIONS[ip]; 7125 if (npi.name.equals(perm) 7126 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7127 allowed = true; 7128 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7129 + pkg.packageName); 7130 break; 7131 } 7132 } 7133 return allowed; 7134 } 7135 7136 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7137 BasePermission bp, ArraySet<String> origPermissions) { 7138 boolean allowed; 7139 allowed = (compareSignatures( 7140 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7141 == PackageManager.SIGNATURE_MATCH) 7142 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7143 == PackageManager.SIGNATURE_MATCH); 7144 if (!allowed && (bp.protectionLevel 7145 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7146 if (isSystemApp(pkg)) { 7147 // For updated system applications, a system permission 7148 // is granted only if it had been defined by the original application. 7149 if (isUpdatedSystemApp(pkg)) { 7150 final PackageSetting sysPs = mSettings 7151 .getDisabledSystemPkgLPr(pkg.packageName); 7152 final GrantedPermissions origGp = sysPs.sharedUser != null 7153 ? sysPs.sharedUser : sysPs; 7154 7155 if (origGp.grantedPermissions.contains(perm)) { 7156 // If the original was granted this permission, we take 7157 // that grant decision as read and propagate it to the 7158 // update. 7159 allowed = true; 7160 } else { 7161 // The system apk may have been updated with an older 7162 // version of the one on the data partition, but which 7163 // granted a new system permission that it didn't have 7164 // before. In this case we do want to allow the app to 7165 // now get the new permission if the ancestral apk is 7166 // privileged to get it. 7167 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7168 for (int j=0; 7169 j<sysPs.pkg.requestedPermissions.size(); j++) { 7170 if (perm.equals( 7171 sysPs.pkg.requestedPermissions.get(j))) { 7172 allowed = true; 7173 break; 7174 } 7175 } 7176 } 7177 } 7178 } else { 7179 allowed = isPrivilegedApp(pkg); 7180 } 7181 } 7182 } 7183 if (!allowed && (bp.protectionLevel 7184 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7185 // For development permissions, a development permission 7186 // is granted only if it was already granted. 7187 allowed = origPermissions.contains(perm); 7188 } 7189 return allowed; 7190 } 7191 7192 final class ActivityIntentResolver 7193 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7194 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7195 boolean defaultOnly, int userId) { 7196 if (!sUserManager.exists(userId)) return null; 7197 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7198 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7199 } 7200 7201 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7202 int userId) { 7203 if (!sUserManager.exists(userId)) return null; 7204 mFlags = flags; 7205 return super.queryIntent(intent, resolvedType, 7206 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7207 } 7208 7209 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7210 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7211 if (!sUserManager.exists(userId)) return null; 7212 if (packageActivities == null) { 7213 return null; 7214 } 7215 mFlags = flags; 7216 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7217 final int N = packageActivities.size(); 7218 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7219 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7220 7221 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7222 for (int i = 0; i < N; ++i) { 7223 intentFilters = packageActivities.get(i).intents; 7224 if (intentFilters != null && intentFilters.size() > 0) { 7225 PackageParser.ActivityIntentInfo[] array = 7226 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7227 intentFilters.toArray(array); 7228 listCut.add(array); 7229 } 7230 } 7231 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7232 } 7233 7234 public final void addActivity(PackageParser.Activity a, String type) { 7235 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7236 mActivities.put(a.getComponentName(), a); 7237 if (DEBUG_SHOW_INFO) 7238 Log.v( 7239 TAG, " " + type + " " + 7240 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7241 if (DEBUG_SHOW_INFO) 7242 Log.v(TAG, " Class=" + a.info.name); 7243 final int NI = a.intents.size(); 7244 for (int j=0; j<NI; j++) { 7245 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7246 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7247 intent.setPriority(0); 7248 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7249 + a.className + " with priority > 0, forcing to 0"); 7250 } 7251 if (DEBUG_SHOW_INFO) { 7252 Log.v(TAG, " IntentFilter:"); 7253 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7254 } 7255 if (!intent.debugCheck()) { 7256 Log.w(TAG, "==> For Activity " + a.info.name); 7257 } 7258 addFilter(intent); 7259 } 7260 } 7261 7262 public final void removeActivity(PackageParser.Activity a, String type) { 7263 mActivities.remove(a.getComponentName()); 7264 if (DEBUG_SHOW_INFO) { 7265 Log.v(TAG, " " + type + " " 7266 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7267 : a.info.name) + ":"); 7268 Log.v(TAG, " Class=" + a.info.name); 7269 } 7270 final int NI = a.intents.size(); 7271 for (int j=0; j<NI; j++) { 7272 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7273 if (DEBUG_SHOW_INFO) { 7274 Log.v(TAG, " IntentFilter:"); 7275 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7276 } 7277 removeFilter(intent); 7278 } 7279 } 7280 7281 @Override 7282 protected boolean allowFilterResult( 7283 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7284 ActivityInfo filterAi = filter.activity.info; 7285 for (int i=dest.size()-1; i>=0; i--) { 7286 ActivityInfo destAi = dest.get(i).activityInfo; 7287 if (destAi.name == filterAi.name 7288 && destAi.packageName == filterAi.packageName) { 7289 return false; 7290 } 7291 } 7292 return true; 7293 } 7294 7295 @Override 7296 protected ActivityIntentInfo[] newArray(int size) { 7297 return new ActivityIntentInfo[size]; 7298 } 7299 7300 @Override 7301 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7302 if (!sUserManager.exists(userId)) return true; 7303 PackageParser.Package p = filter.activity.owner; 7304 if (p != null) { 7305 PackageSetting ps = (PackageSetting)p.mExtras; 7306 if (ps != null) { 7307 // System apps are never considered stopped for purposes of 7308 // filtering, because there may be no way for the user to 7309 // actually re-launch them. 7310 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7311 && ps.getStopped(userId); 7312 } 7313 } 7314 return false; 7315 } 7316 7317 @Override 7318 protected boolean isPackageForFilter(String packageName, 7319 PackageParser.ActivityIntentInfo info) { 7320 return packageName.equals(info.activity.owner.packageName); 7321 } 7322 7323 @Override 7324 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7325 int match, int userId) { 7326 if (!sUserManager.exists(userId)) return null; 7327 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7328 return null; 7329 } 7330 final PackageParser.Activity activity = info.activity; 7331 if (mSafeMode && (activity.info.applicationInfo.flags 7332 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7333 return null; 7334 } 7335 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7336 if (ps == null) { 7337 return null; 7338 } 7339 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7340 ps.readUserState(userId), userId); 7341 if (ai == null) { 7342 return null; 7343 } 7344 final ResolveInfo res = new ResolveInfo(); 7345 res.activityInfo = ai; 7346 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7347 res.filter = info; 7348 } 7349 res.priority = info.getPriority(); 7350 res.preferredOrder = activity.owner.mPreferredOrder; 7351 //System.out.println("Result: " + res.activityInfo.className + 7352 // " = " + res.priority); 7353 res.match = match; 7354 res.isDefault = info.hasDefault; 7355 res.labelRes = info.labelRes; 7356 res.nonLocalizedLabel = info.nonLocalizedLabel; 7357 if (userNeedsBadging(userId)) { 7358 res.noResourceId = true; 7359 } else { 7360 res.icon = info.icon; 7361 } 7362 res.system = isSystemApp(res.activityInfo.applicationInfo); 7363 return res; 7364 } 7365 7366 @Override 7367 protected void sortResults(List<ResolveInfo> results) { 7368 Collections.sort(results, mResolvePrioritySorter); 7369 } 7370 7371 @Override 7372 protected void dumpFilter(PrintWriter out, String prefix, 7373 PackageParser.ActivityIntentInfo filter) { 7374 out.print(prefix); out.print( 7375 Integer.toHexString(System.identityHashCode(filter.activity))); 7376 out.print(' '); 7377 filter.activity.printComponentShortName(out); 7378 out.print(" filter "); 7379 out.println(Integer.toHexString(System.identityHashCode(filter))); 7380 } 7381 7382 @Override 7383 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7384 return filter.activity; 7385 } 7386 7387 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7388 PackageParser.Activity activity = (PackageParser.Activity)label; 7389 out.print(prefix); out.print( 7390 Integer.toHexString(System.identityHashCode(activity))); 7391 out.print(' '); 7392 activity.printComponentShortName(out); 7393 if (count > 1) { 7394 out.print(" ("); out.print(count); out.print(" filters)"); 7395 } 7396 out.println(); 7397 } 7398 7399// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7400// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7401// final List<ResolveInfo> retList = Lists.newArrayList(); 7402// while (i.hasNext()) { 7403// final ResolveInfo resolveInfo = i.next(); 7404// if (isEnabledLP(resolveInfo.activityInfo)) { 7405// retList.add(resolveInfo); 7406// } 7407// } 7408// return retList; 7409// } 7410 7411 // Keys are String (activity class name), values are Activity. 7412 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 7413 = new ArrayMap<ComponentName, PackageParser.Activity>(); 7414 private int mFlags; 7415 } 7416 7417 private final class ServiceIntentResolver 7418 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7419 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7420 boolean defaultOnly, int userId) { 7421 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7422 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7423 } 7424 7425 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7426 int userId) { 7427 if (!sUserManager.exists(userId)) return null; 7428 mFlags = flags; 7429 return super.queryIntent(intent, resolvedType, 7430 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7431 } 7432 7433 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7434 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7435 if (!sUserManager.exists(userId)) return null; 7436 if (packageServices == null) { 7437 return null; 7438 } 7439 mFlags = flags; 7440 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7441 final int N = packageServices.size(); 7442 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7443 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7444 7445 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7446 for (int i = 0; i < N; ++i) { 7447 intentFilters = packageServices.get(i).intents; 7448 if (intentFilters != null && intentFilters.size() > 0) { 7449 PackageParser.ServiceIntentInfo[] array = 7450 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7451 intentFilters.toArray(array); 7452 listCut.add(array); 7453 } 7454 } 7455 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7456 } 7457 7458 public final void addService(PackageParser.Service s) { 7459 mServices.put(s.getComponentName(), s); 7460 if (DEBUG_SHOW_INFO) { 7461 Log.v(TAG, " " 7462 + (s.info.nonLocalizedLabel != null 7463 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7464 Log.v(TAG, " Class=" + s.info.name); 7465 } 7466 final int NI = s.intents.size(); 7467 int j; 7468 for (j=0; j<NI; j++) { 7469 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7470 if (DEBUG_SHOW_INFO) { 7471 Log.v(TAG, " IntentFilter:"); 7472 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7473 } 7474 if (!intent.debugCheck()) { 7475 Log.w(TAG, "==> For Service " + s.info.name); 7476 } 7477 addFilter(intent); 7478 } 7479 } 7480 7481 public final void removeService(PackageParser.Service s) { 7482 mServices.remove(s.getComponentName()); 7483 if (DEBUG_SHOW_INFO) { 7484 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7485 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7486 Log.v(TAG, " Class=" + s.info.name); 7487 } 7488 final int NI = s.intents.size(); 7489 int j; 7490 for (j=0; j<NI; j++) { 7491 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7492 if (DEBUG_SHOW_INFO) { 7493 Log.v(TAG, " IntentFilter:"); 7494 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7495 } 7496 removeFilter(intent); 7497 } 7498 } 7499 7500 @Override 7501 protected boolean allowFilterResult( 7502 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7503 ServiceInfo filterSi = filter.service.info; 7504 for (int i=dest.size()-1; i>=0; i--) { 7505 ServiceInfo destAi = dest.get(i).serviceInfo; 7506 if (destAi.name == filterSi.name 7507 && destAi.packageName == filterSi.packageName) { 7508 return false; 7509 } 7510 } 7511 return true; 7512 } 7513 7514 @Override 7515 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7516 return new PackageParser.ServiceIntentInfo[size]; 7517 } 7518 7519 @Override 7520 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7521 if (!sUserManager.exists(userId)) return true; 7522 PackageParser.Package p = filter.service.owner; 7523 if (p != null) { 7524 PackageSetting ps = (PackageSetting)p.mExtras; 7525 if (ps != null) { 7526 // System apps are never considered stopped for purposes of 7527 // filtering, because there may be no way for the user to 7528 // actually re-launch them. 7529 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7530 && ps.getStopped(userId); 7531 } 7532 } 7533 return false; 7534 } 7535 7536 @Override 7537 protected boolean isPackageForFilter(String packageName, 7538 PackageParser.ServiceIntentInfo info) { 7539 return packageName.equals(info.service.owner.packageName); 7540 } 7541 7542 @Override 7543 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7544 int match, int userId) { 7545 if (!sUserManager.exists(userId)) return null; 7546 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7547 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7548 return null; 7549 } 7550 final PackageParser.Service service = info.service; 7551 if (mSafeMode && (service.info.applicationInfo.flags 7552 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7553 return null; 7554 } 7555 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7556 if (ps == null) { 7557 return null; 7558 } 7559 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7560 ps.readUserState(userId), userId); 7561 if (si == null) { 7562 return null; 7563 } 7564 final ResolveInfo res = new ResolveInfo(); 7565 res.serviceInfo = si; 7566 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7567 res.filter = filter; 7568 } 7569 res.priority = info.getPriority(); 7570 res.preferredOrder = service.owner.mPreferredOrder; 7571 //System.out.println("Result: " + res.activityInfo.className + 7572 // " = " + res.priority); 7573 res.match = match; 7574 res.isDefault = info.hasDefault; 7575 res.labelRes = info.labelRes; 7576 res.nonLocalizedLabel = info.nonLocalizedLabel; 7577 res.icon = info.icon; 7578 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7579 return res; 7580 } 7581 7582 @Override 7583 protected void sortResults(List<ResolveInfo> results) { 7584 Collections.sort(results, mResolvePrioritySorter); 7585 } 7586 7587 @Override 7588 protected void dumpFilter(PrintWriter out, String prefix, 7589 PackageParser.ServiceIntentInfo filter) { 7590 out.print(prefix); out.print( 7591 Integer.toHexString(System.identityHashCode(filter.service))); 7592 out.print(' '); 7593 filter.service.printComponentShortName(out); 7594 out.print(" filter "); 7595 out.println(Integer.toHexString(System.identityHashCode(filter))); 7596 } 7597 7598 @Override 7599 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 7600 return filter.service; 7601 } 7602 7603 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7604 PackageParser.Service service = (PackageParser.Service)label; 7605 out.print(prefix); out.print( 7606 Integer.toHexString(System.identityHashCode(service))); 7607 out.print(' '); 7608 service.printComponentShortName(out); 7609 if (count > 1) { 7610 out.print(" ("); out.print(count); out.print(" filters)"); 7611 } 7612 out.println(); 7613 } 7614 7615// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7616// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7617// final List<ResolveInfo> retList = Lists.newArrayList(); 7618// while (i.hasNext()) { 7619// final ResolveInfo resolveInfo = (ResolveInfo) i; 7620// if (isEnabledLP(resolveInfo.serviceInfo)) { 7621// retList.add(resolveInfo); 7622// } 7623// } 7624// return retList; 7625// } 7626 7627 // Keys are String (activity class name), values are Activity. 7628 private final ArrayMap<ComponentName, PackageParser.Service> mServices 7629 = new ArrayMap<ComponentName, PackageParser.Service>(); 7630 private int mFlags; 7631 }; 7632 7633 private final class ProviderIntentResolver 7634 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7635 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7636 boolean defaultOnly, int userId) { 7637 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7638 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7639 } 7640 7641 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7642 int userId) { 7643 if (!sUserManager.exists(userId)) 7644 return null; 7645 mFlags = flags; 7646 return super.queryIntent(intent, resolvedType, 7647 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7648 } 7649 7650 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7651 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7652 if (!sUserManager.exists(userId)) 7653 return null; 7654 if (packageProviders == null) { 7655 return null; 7656 } 7657 mFlags = flags; 7658 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7659 final int N = packageProviders.size(); 7660 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7661 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7662 7663 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7664 for (int i = 0; i < N; ++i) { 7665 intentFilters = packageProviders.get(i).intents; 7666 if (intentFilters != null && intentFilters.size() > 0) { 7667 PackageParser.ProviderIntentInfo[] array = 7668 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7669 intentFilters.toArray(array); 7670 listCut.add(array); 7671 } 7672 } 7673 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7674 } 7675 7676 public final void addProvider(PackageParser.Provider p) { 7677 if (mProviders.containsKey(p.getComponentName())) { 7678 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7679 return; 7680 } 7681 7682 mProviders.put(p.getComponentName(), p); 7683 if (DEBUG_SHOW_INFO) { 7684 Log.v(TAG, " " 7685 + (p.info.nonLocalizedLabel != null 7686 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7687 Log.v(TAG, " Class=" + p.info.name); 7688 } 7689 final int NI = p.intents.size(); 7690 int j; 7691 for (j = 0; j < NI; j++) { 7692 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7693 if (DEBUG_SHOW_INFO) { 7694 Log.v(TAG, " IntentFilter:"); 7695 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7696 } 7697 if (!intent.debugCheck()) { 7698 Log.w(TAG, "==> For Provider " + p.info.name); 7699 } 7700 addFilter(intent); 7701 } 7702 } 7703 7704 public final void removeProvider(PackageParser.Provider p) { 7705 mProviders.remove(p.getComponentName()); 7706 if (DEBUG_SHOW_INFO) { 7707 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7708 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7709 Log.v(TAG, " Class=" + p.info.name); 7710 } 7711 final int NI = p.intents.size(); 7712 int j; 7713 for (j = 0; j < NI; j++) { 7714 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7715 if (DEBUG_SHOW_INFO) { 7716 Log.v(TAG, " IntentFilter:"); 7717 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7718 } 7719 removeFilter(intent); 7720 } 7721 } 7722 7723 @Override 7724 protected boolean allowFilterResult( 7725 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7726 ProviderInfo filterPi = filter.provider.info; 7727 for (int i = dest.size() - 1; i >= 0; i--) { 7728 ProviderInfo destPi = dest.get(i).providerInfo; 7729 if (destPi.name == filterPi.name 7730 && destPi.packageName == filterPi.packageName) { 7731 return false; 7732 } 7733 } 7734 return true; 7735 } 7736 7737 @Override 7738 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7739 return new PackageParser.ProviderIntentInfo[size]; 7740 } 7741 7742 @Override 7743 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7744 if (!sUserManager.exists(userId)) 7745 return true; 7746 PackageParser.Package p = filter.provider.owner; 7747 if (p != null) { 7748 PackageSetting ps = (PackageSetting) p.mExtras; 7749 if (ps != null) { 7750 // System apps are never considered stopped for purposes of 7751 // filtering, because there may be no way for the user to 7752 // actually re-launch them. 7753 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7754 && ps.getStopped(userId); 7755 } 7756 } 7757 return false; 7758 } 7759 7760 @Override 7761 protected boolean isPackageForFilter(String packageName, 7762 PackageParser.ProviderIntentInfo info) { 7763 return packageName.equals(info.provider.owner.packageName); 7764 } 7765 7766 @Override 7767 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7768 int match, int userId) { 7769 if (!sUserManager.exists(userId)) 7770 return null; 7771 final PackageParser.ProviderIntentInfo info = filter; 7772 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7773 return null; 7774 } 7775 final PackageParser.Provider provider = info.provider; 7776 if (mSafeMode && (provider.info.applicationInfo.flags 7777 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7778 return null; 7779 } 7780 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7781 if (ps == null) { 7782 return null; 7783 } 7784 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7785 ps.readUserState(userId), userId); 7786 if (pi == null) { 7787 return null; 7788 } 7789 final ResolveInfo res = new ResolveInfo(); 7790 res.providerInfo = pi; 7791 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7792 res.filter = filter; 7793 } 7794 res.priority = info.getPriority(); 7795 res.preferredOrder = provider.owner.mPreferredOrder; 7796 res.match = match; 7797 res.isDefault = info.hasDefault; 7798 res.labelRes = info.labelRes; 7799 res.nonLocalizedLabel = info.nonLocalizedLabel; 7800 res.icon = info.icon; 7801 res.system = isSystemApp(res.providerInfo.applicationInfo); 7802 return res; 7803 } 7804 7805 @Override 7806 protected void sortResults(List<ResolveInfo> results) { 7807 Collections.sort(results, mResolvePrioritySorter); 7808 } 7809 7810 @Override 7811 protected void dumpFilter(PrintWriter out, String prefix, 7812 PackageParser.ProviderIntentInfo filter) { 7813 out.print(prefix); 7814 out.print( 7815 Integer.toHexString(System.identityHashCode(filter.provider))); 7816 out.print(' '); 7817 filter.provider.printComponentShortName(out); 7818 out.print(" filter "); 7819 out.println(Integer.toHexString(System.identityHashCode(filter))); 7820 } 7821 7822 @Override 7823 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 7824 return filter.provider; 7825 } 7826 7827 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7828 PackageParser.Provider provider = (PackageParser.Provider)label; 7829 out.print(prefix); out.print( 7830 Integer.toHexString(System.identityHashCode(provider))); 7831 out.print(' '); 7832 provider.printComponentShortName(out); 7833 if (count > 1) { 7834 out.print(" ("); out.print(count); out.print(" filters)"); 7835 } 7836 out.println(); 7837 } 7838 7839 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 7840 = new ArrayMap<ComponentName, PackageParser.Provider>(); 7841 private int mFlags; 7842 }; 7843 7844 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7845 new Comparator<ResolveInfo>() { 7846 public int compare(ResolveInfo r1, ResolveInfo r2) { 7847 int v1 = r1.priority; 7848 int v2 = r2.priority; 7849 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7850 if (v1 != v2) { 7851 return (v1 > v2) ? -1 : 1; 7852 } 7853 v1 = r1.preferredOrder; 7854 v2 = r2.preferredOrder; 7855 if (v1 != v2) { 7856 return (v1 > v2) ? -1 : 1; 7857 } 7858 if (r1.isDefault != r2.isDefault) { 7859 return r1.isDefault ? -1 : 1; 7860 } 7861 v1 = r1.match; 7862 v2 = r2.match; 7863 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7864 if (v1 != v2) { 7865 return (v1 > v2) ? -1 : 1; 7866 } 7867 if (r1.system != r2.system) { 7868 return r1.system ? -1 : 1; 7869 } 7870 return 0; 7871 } 7872 }; 7873 7874 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7875 new Comparator<ProviderInfo>() { 7876 public int compare(ProviderInfo p1, ProviderInfo p2) { 7877 final int v1 = p1.initOrder; 7878 final int v2 = p2.initOrder; 7879 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7880 } 7881 }; 7882 7883 static final void sendPackageBroadcast(String action, String pkg, 7884 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7885 int[] userIds) { 7886 IActivityManager am = ActivityManagerNative.getDefault(); 7887 if (am != null) { 7888 try { 7889 if (userIds == null) { 7890 userIds = am.getRunningUserIds(); 7891 } 7892 for (int id : userIds) { 7893 final Intent intent = new Intent(action, 7894 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7895 if (extras != null) { 7896 intent.putExtras(extras); 7897 } 7898 if (targetPkg != null) { 7899 intent.setPackage(targetPkg); 7900 } 7901 // Modify the UID when posting to other users 7902 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7903 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7904 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7905 intent.putExtra(Intent.EXTRA_UID, uid); 7906 } 7907 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7908 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7909 if (DEBUG_BROADCASTS) { 7910 RuntimeException here = new RuntimeException("here"); 7911 here.fillInStackTrace(); 7912 Slog.d(TAG, "Sending to user " + id + ": " 7913 + intent.toShortString(false, true, false, false) 7914 + " " + intent.getExtras(), here); 7915 } 7916 am.broadcastIntent(null, intent, null, finishedReceiver, 7917 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7918 finishedReceiver != null, false, id); 7919 } 7920 } catch (RemoteException ex) { 7921 } 7922 } 7923 } 7924 7925 /** 7926 * Check if the external storage media is available. This is true if there 7927 * is a mounted external storage medium or if the external storage is 7928 * emulated. 7929 */ 7930 private boolean isExternalMediaAvailable() { 7931 return mMediaMounted || Environment.isExternalStorageEmulated(); 7932 } 7933 7934 @Override 7935 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7936 // writer 7937 synchronized (mPackages) { 7938 if (!isExternalMediaAvailable()) { 7939 // If the external storage is no longer mounted at this point, 7940 // the caller may not have been able to delete all of this 7941 // packages files and can not delete any more. Bail. 7942 return null; 7943 } 7944 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7945 if (lastPackage != null) { 7946 pkgs.remove(lastPackage); 7947 } 7948 if (pkgs.size() > 0) { 7949 return pkgs.get(0); 7950 } 7951 } 7952 return null; 7953 } 7954 7955 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7956 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 7957 userId, andCode ? 1 : 0, packageName); 7958 if (mSystemReady) { 7959 msg.sendToTarget(); 7960 } else { 7961 if (mPostSystemReadyMessages == null) { 7962 mPostSystemReadyMessages = new ArrayList<>(); 7963 } 7964 mPostSystemReadyMessages.add(msg); 7965 } 7966 } 7967 7968 void startCleaningPackages() { 7969 // reader 7970 synchronized (mPackages) { 7971 if (!isExternalMediaAvailable()) { 7972 return; 7973 } 7974 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7975 return; 7976 } 7977 } 7978 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7979 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7980 IActivityManager am = ActivityManagerNative.getDefault(); 7981 if (am != null) { 7982 try { 7983 am.startService(null, intent, null, UserHandle.USER_OWNER); 7984 } catch (RemoteException e) { 7985 } 7986 } 7987 } 7988 7989 @Override 7990 public void installPackage(String originPath, IPackageInstallObserver2 observer, 7991 int installFlags, String installerPackageName, VerificationParams verificationParams, 7992 String packageAbiOverride) { 7993 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 7994 packageAbiOverride, UserHandle.getCallingUserId()); 7995 } 7996 7997 @Override 7998 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 7999 int installFlags, String installerPackageName, VerificationParams verificationParams, 8000 String packageAbiOverride, int userId) { 8001 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8002 8003 final int callingUid = Binder.getCallingUid(); 8004 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8005 8006 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8007 try { 8008 if (observer != null) { 8009 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8010 } 8011 } catch (RemoteException re) { 8012 } 8013 return; 8014 } 8015 8016 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8017 installFlags |= PackageManager.INSTALL_FROM_ADB; 8018 8019 } else { 8020 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8021 // about installerPackageName. 8022 8023 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8024 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8025 } 8026 8027 UserHandle user; 8028 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8029 user = UserHandle.ALL; 8030 } else { 8031 user = new UserHandle(userId); 8032 } 8033 8034 verificationParams.setInstallerUid(callingUid); 8035 8036 final File originFile = new File(originPath); 8037 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8038 8039 final Message msg = mHandler.obtainMessage(INIT_COPY); 8040 msg.obj = new InstallParams(origin, observer, installFlags, 8041 installerPackageName, verificationParams, user, packageAbiOverride); 8042 mHandler.sendMessage(msg); 8043 } 8044 8045 void installStage(String packageName, File stagedDir, String stagedCid, 8046 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8047 String installerPackageName, int installerUid, UserHandle user) { 8048 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8049 params.referrerUri, installerUid, null); 8050 8051 final OriginInfo origin; 8052 if (stagedDir != null) { 8053 origin = OriginInfo.fromStagedFile(stagedDir); 8054 } else { 8055 origin = OriginInfo.fromStagedContainer(stagedCid); 8056 } 8057 8058 final Message msg = mHandler.obtainMessage(INIT_COPY); 8059 msg.obj = new InstallParams(origin, observer, params.installFlags, 8060 installerPackageName, verifParams, user, params.abiOverride); 8061 mHandler.sendMessage(msg); 8062 } 8063 8064 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8065 Bundle extras = new Bundle(1); 8066 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8067 8068 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8069 packageName, extras, null, null, new int[] {userId}); 8070 try { 8071 IActivityManager am = ActivityManagerNative.getDefault(); 8072 final boolean isSystem = 8073 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8074 if (isSystem && am.isUserRunning(userId, false)) { 8075 // The just-installed/enabled app is bundled on the system, so presumed 8076 // to be able to run automatically without needing an explicit launch. 8077 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8078 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8079 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8080 .setPackage(packageName); 8081 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8082 android.app.AppOpsManager.OP_NONE, false, false, userId); 8083 } 8084 } catch (RemoteException e) { 8085 // shouldn't happen 8086 Slog.w(TAG, "Unable to bootstrap installed package", e); 8087 } 8088 } 8089 8090 @Override 8091 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8092 int userId) { 8093 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8094 PackageSetting pkgSetting; 8095 final int uid = Binder.getCallingUid(); 8096 enforceCrossUserPermission(uid, userId, true, true, 8097 "setApplicationHiddenSetting for user " + userId); 8098 8099 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8100 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8101 return false; 8102 } 8103 8104 long callingId = Binder.clearCallingIdentity(); 8105 try { 8106 boolean sendAdded = false; 8107 boolean sendRemoved = false; 8108 // writer 8109 synchronized (mPackages) { 8110 pkgSetting = mSettings.mPackages.get(packageName); 8111 if (pkgSetting == null) { 8112 return false; 8113 } 8114 if (pkgSetting.getHidden(userId) != hidden) { 8115 pkgSetting.setHidden(hidden, userId); 8116 mSettings.writePackageRestrictionsLPr(userId); 8117 if (hidden) { 8118 sendRemoved = true; 8119 } else { 8120 sendAdded = true; 8121 } 8122 } 8123 } 8124 if (sendAdded) { 8125 sendPackageAddedForUser(packageName, pkgSetting, userId); 8126 return true; 8127 } 8128 if (sendRemoved) { 8129 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8130 "hiding pkg"); 8131 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8132 } 8133 } finally { 8134 Binder.restoreCallingIdentity(callingId); 8135 } 8136 return false; 8137 } 8138 8139 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8140 int userId) { 8141 final PackageRemovedInfo info = new PackageRemovedInfo(); 8142 info.removedPackage = packageName; 8143 info.removedUsers = new int[] {userId}; 8144 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8145 info.sendBroadcast(false, false, false); 8146 } 8147 8148 /** 8149 * Returns true if application is not found or there was an error. Otherwise it returns 8150 * the hidden state of the package for the given user. 8151 */ 8152 @Override 8153 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8154 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8155 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8156 false, "getApplicationHidden for user " + userId); 8157 PackageSetting pkgSetting; 8158 long callingId = Binder.clearCallingIdentity(); 8159 try { 8160 // writer 8161 synchronized (mPackages) { 8162 pkgSetting = mSettings.mPackages.get(packageName); 8163 if (pkgSetting == null) { 8164 return true; 8165 } 8166 return pkgSetting.getHidden(userId); 8167 } 8168 } finally { 8169 Binder.restoreCallingIdentity(callingId); 8170 } 8171 } 8172 8173 /** 8174 * @hide 8175 */ 8176 @Override 8177 public int installExistingPackageAsUser(String packageName, int userId) { 8178 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8179 null); 8180 PackageSetting pkgSetting; 8181 final int uid = Binder.getCallingUid(); 8182 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8183 + userId); 8184 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8185 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8186 } 8187 8188 long callingId = Binder.clearCallingIdentity(); 8189 try { 8190 boolean sendAdded = false; 8191 Bundle extras = new Bundle(1); 8192 8193 // writer 8194 synchronized (mPackages) { 8195 pkgSetting = mSettings.mPackages.get(packageName); 8196 if (pkgSetting == null) { 8197 return PackageManager.INSTALL_FAILED_INVALID_URI; 8198 } 8199 if (!pkgSetting.getInstalled(userId)) { 8200 pkgSetting.setInstalled(true, userId); 8201 pkgSetting.setHidden(false, userId); 8202 mSettings.writePackageRestrictionsLPr(userId); 8203 sendAdded = true; 8204 } 8205 } 8206 8207 if (sendAdded) { 8208 sendPackageAddedForUser(packageName, pkgSetting, userId); 8209 } 8210 } finally { 8211 Binder.restoreCallingIdentity(callingId); 8212 } 8213 8214 return PackageManager.INSTALL_SUCCEEDED; 8215 } 8216 8217 boolean isUserRestricted(int userId, String restrictionKey) { 8218 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8219 if (restrictions.getBoolean(restrictionKey, false)) { 8220 Log.w(TAG, "User is restricted: " + restrictionKey); 8221 return true; 8222 } 8223 return false; 8224 } 8225 8226 @Override 8227 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8228 mContext.enforceCallingOrSelfPermission( 8229 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8230 "Only package verification agents can verify applications"); 8231 8232 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8233 final PackageVerificationResponse response = new PackageVerificationResponse( 8234 verificationCode, Binder.getCallingUid()); 8235 msg.arg1 = id; 8236 msg.obj = response; 8237 mHandler.sendMessage(msg); 8238 } 8239 8240 @Override 8241 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8242 long millisecondsToDelay) { 8243 mContext.enforceCallingOrSelfPermission( 8244 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8245 "Only package verification agents can extend verification timeouts"); 8246 8247 final PackageVerificationState state = mPendingVerification.get(id); 8248 final PackageVerificationResponse response = new PackageVerificationResponse( 8249 verificationCodeAtTimeout, Binder.getCallingUid()); 8250 8251 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8252 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8253 } 8254 if (millisecondsToDelay < 0) { 8255 millisecondsToDelay = 0; 8256 } 8257 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8258 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8259 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8260 } 8261 8262 if ((state != null) && !state.timeoutExtended()) { 8263 state.extendTimeout(); 8264 8265 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8266 msg.arg1 = id; 8267 msg.obj = response; 8268 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8269 } 8270 } 8271 8272 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8273 int verificationCode, UserHandle user) { 8274 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8275 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8276 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8277 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8278 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8279 8280 mContext.sendBroadcastAsUser(intent, user, 8281 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8282 } 8283 8284 private ComponentName matchComponentForVerifier(String packageName, 8285 List<ResolveInfo> receivers) { 8286 ActivityInfo targetReceiver = null; 8287 8288 final int NR = receivers.size(); 8289 for (int i = 0; i < NR; i++) { 8290 final ResolveInfo info = receivers.get(i); 8291 if (info.activityInfo == null) { 8292 continue; 8293 } 8294 8295 if (packageName.equals(info.activityInfo.packageName)) { 8296 targetReceiver = info.activityInfo; 8297 break; 8298 } 8299 } 8300 8301 if (targetReceiver == null) { 8302 return null; 8303 } 8304 8305 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8306 } 8307 8308 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8309 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8310 if (pkgInfo.verifiers.length == 0) { 8311 return null; 8312 } 8313 8314 final int N = pkgInfo.verifiers.length; 8315 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8316 for (int i = 0; i < N; i++) { 8317 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8318 8319 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8320 receivers); 8321 if (comp == null) { 8322 continue; 8323 } 8324 8325 final int verifierUid = getUidForVerifier(verifierInfo); 8326 if (verifierUid == -1) { 8327 continue; 8328 } 8329 8330 if (DEBUG_VERIFY) { 8331 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8332 + " with the correct signature"); 8333 } 8334 sufficientVerifiers.add(comp); 8335 verificationState.addSufficientVerifier(verifierUid); 8336 } 8337 8338 return sufficientVerifiers; 8339 } 8340 8341 private int getUidForVerifier(VerifierInfo verifierInfo) { 8342 synchronized (mPackages) { 8343 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8344 if (pkg == null) { 8345 return -1; 8346 } else if (pkg.mSignatures.length != 1) { 8347 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8348 + " has more than one signature; ignoring"); 8349 return -1; 8350 } 8351 8352 /* 8353 * If the public key of the package's signature does not match 8354 * our expected public key, then this is a different package and 8355 * we should skip. 8356 */ 8357 8358 final byte[] expectedPublicKey; 8359 try { 8360 final Signature verifierSig = pkg.mSignatures[0]; 8361 final PublicKey publicKey = verifierSig.getPublicKey(); 8362 expectedPublicKey = publicKey.getEncoded(); 8363 } catch (CertificateException e) { 8364 return -1; 8365 } 8366 8367 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8368 8369 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8370 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8371 + " does not have the expected public key; ignoring"); 8372 return -1; 8373 } 8374 8375 return pkg.applicationInfo.uid; 8376 } 8377 } 8378 8379 @Override 8380 public void finishPackageInstall(int token) { 8381 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8382 8383 if (DEBUG_INSTALL) { 8384 Slog.v(TAG, "BM finishing package install for " + token); 8385 } 8386 8387 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8388 mHandler.sendMessage(msg); 8389 } 8390 8391 /** 8392 * Get the verification agent timeout. 8393 * 8394 * @return verification timeout in milliseconds 8395 */ 8396 private long getVerificationTimeout() { 8397 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8398 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8399 DEFAULT_VERIFICATION_TIMEOUT); 8400 } 8401 8402 /** 8403 * Get the default verification agent response code. 8404 * 8405 * @return default verification response code 8406 */ 8407 private int getDefaultVerificationResponse() { 8408 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8409 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8410 DEFAULT_VERIFICATION_RESPONSE); 8411 } 8412 8413 /** 8414 * Check whether or not package verification has been enabled. 8415 * 8416 * @return true if verification should be performed 8417 */ 8418 private boolean isVerificationEnabled(int userId, int installFlags) { 8419 if (!DEFAULT_VERIFY_ENABLE) { 8420 return false; 8421 } 8422 8423 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8424 8425 // Check if installing from ADB 8426 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8427 // Do not run verification in a test harness environment 8428 if (ActivityManager.isRunningInTestHarness()) { 8429 return false; 8430 } 8431 if (ensureVerifyAppsEnabled) { 8432 return true; 8433 } 8434 // Check if the developer does not want package verification for ADB installs 8435 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8436 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8437 return false; 8438 } 8439 } 8440 8441 if (ensureVerifyAppsEnabled) { 8442 return true; 8443 } 8444 8445 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8446 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8447 } 8448 8449 /** 8450 * Get the "allow unknown sources" setting. 8451 * 8452 * @return the current "allow unknown sources" setting 8453 */ 8454 private int getUnknownSourcesSettings() { 8455 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8456 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8457 -1); 8458 } 8459 8460 @Override 8461 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8462 final int uid = Binder.getCallingUid(); 8463 // writer 8464 synchronized (mPackages) { 8465 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8466 if (targetPackageSetting == null) { 8467 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8468 } 8469 8470 PackageSetting installerPackageSetting; 8471 if (installerPackageName != null) { 8472 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8473 if (installerPackageSetting == null) { 8474 throw new IllegalArgumentException("Unknown installer package: " 8475 + installerPackageName); 8476 } 8477 } else { 8478 installerPackageSetting = null; 8479 } 8480 8481 Signature[] callerSignature; 8482 Object obj = mSettings.getUserIdLPr(uid); 8483 if (obj != null) { 8484 if (obj instanceof SharedUserSetting) { 8485 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8486 } else if (obj instanceof PackageSetting) { 8487 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8488 } else { 8489 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8490 } 8491 } else { 8492 throw new SecurityException("Unknown calling uid " + uid); 8493 } 8494 8495 // Verify: can't set installerPackageName to a package that is 8496 // not signed with the same cert as the caller. 8497 if (installerPackageSetting != null) { 8498 if (compareSignatures(callerSignature, 8499 installerPackageSetting.signatures.mSignatures) 8500 != PackageManager.SIGNATURE_MATCH) { 8501 throw new SecurityException( 8502 "Caller does not have same cert as new installer package " 8503 + installerPackageName); 8504 } 8505 } 8506 8507 // Verify: if target already has an installer package, it must 8508 // be signed with the same cert as the caller. 8509 if (targetPackageSetting.installerPackageName != null) { 8510 PackageSetting setting = mSettings.mPackages.get( 8511 targetPackageSetting.installerPackageName); 8512 // If the currently set package isn't valid, then it's always 8513 // okay to change it. 8514 if (setting != null) { 8515 if (compareSignatures(callerSignature, 8516 setting.signatures.mSignatures) 8517 != PackageManager.SIGNATURE_MATCH) { 8518 throw new SecurityException( 8519 "Caller does not have same cert as old installer package " 8520 + targetPackageSetting.installerPackageName); 8521 } 8522 } 8523 } 8524 8525 // Okay! 8526 targetPackageSetting.installerPackageName = installerPackageName; 8527 scheduleWriteSettingsLocked(); 8528 } 8529 } 8530 8531 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8532 // Queue up an async operation since the package installation may take a little while. 8533 mHandler.post(new Runnable() { 8534 public void run() { 8535 mHandler.removeCallbacks(this); 8536 // Result object to be returned 8537 PackageInstalledInfo res = new PackageInstalledInfo(); 8538 res.returnCode = currentStatus; 8539 res.uid = -1; 8540 res.pkg = null; 8541 res.removedInfo = new PackageRemovedInfo(); 8542 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8543 args.doPreInstall(res.returnCode); 8544 synchronized (mInstallLock) { 8545 installPackageLI(args, res); 8546 } 8547 args.doPostInstall(res.returnCode, res.uid); 8548 } 8549 8550 // A restore should be performed at this point if (a) the install 8551 // succeeded, (b) the operation is not an update, and (c) the new 8552 // package has not opted out of backup participation. 8553 final boolean update = res.removedInfo.removedPackage != null; 8554 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8555 boolean doRestore = !update 8556 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8557 8558 // Set up the post-install work request bookkeeping. This will be used 8559 // and cleaned up by the post-install event handling regardless of whether 8560 // there's a restore pass performed. Token values are >= 1. 8561 int token; 8562 if (mNextInstallToken < 0) mNextInstallToken = 1; 8563 token = mNextInstallToken++; 8564 8565 PostInstallData data = new PostInstallData(args, res); 8566 mRunningInstalls.put(token, data); 8567 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8568 8569 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8570 // Pass responsibility to the Backup Manager. It will perform a 8571 // restore if appropriate, then pass responsibility back to the 8572 // Package Manager to run the post-install observer callbacks 8573 // and broadcasts. 8574 IBackupManager bm = IBackupManager.Stub.asInterface( 8575 ServiceManager.getService(Context.BACKUP_SERVICE)); 8576 if (bm != null) { 8577 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8578 + " to BM for possible restore"); 8579 try { 8580 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8581 } catch (RemoteException e) { 8582 // can't happen; the backup manager is local 8583 } catch (Exception e) { 8584 Slog.e(TAG, "Exception trying to enqueue restore", e); 8585 doRestore = false; 8586 } 8587 } else { 8588 Slog.e(TAG, "Backup Manager not found!"); 8589 doRestore = false; 8590 } 8591 } 8592 8593 if (!doRestore) { 8594 // No restore possible, or the Backup Manager was mysteriously not 8595 // available -- just fire the post-install work request directly. 8596 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8597 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8598 mHandler.sendMessage(msg); 8599 } 8600 } 8601 }); 8602 } 8603 8604 private abstract class HandlerParams { 8605 private static final int MAX_RETRIES = 4; 8606 8607 /** 8608 * Number of times startCopy() has been attempted and had a non-fatal 8609 * error. 8610 */ 8611 private int mRetries = 0; 8612 8613 /** User handle for the user requesting the information or installation. */ 8614 private final UserHandle mUser; 8615 8616 HandlerParams(UserHandle user) { 8617 mUser = user; 8618 } 8619 8620 UserHandle getUser() { 8621 return mUser; 8622 } 8623 8624 final boolean startCopy() { 8625 boolean res; 8626 try { 8627 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8628 8629 if (++mRetries > MAX_RETRIES) { 8630 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8631 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8632 handleServiceError(); 8633 return false; 8634 } else { 8635 handleStartCopy(); 8636 res = true; 8637 } 8638 } catch (RemoteException e) { 8639 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8640 mHandler.sendEmptyMessage(MCS_RECONNECT); 8641 res = false; 8642 } 8643 handleReturnCode(); 8644 return res; 8645 } 8646 8647 final void serviceError() { 8648 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8649 handleServiceError(); 8650 handleReturnCode(); 8651 } 8652 8653 abstract void handleStartCopy() throws RemoteException; 8654 abstract void handleServiceError(); 8655 abstract void handleReturnCode(); 8656 } 8657 8658 class MeasureParams extends HandlerParams { 8659 private final PackageStats mStats; 8660 private boolean mSuccess; 8661 8662 private final IPackageStatsObserver mObserver; 8663 8664 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8665 super(new UserHandle(stats.userHandle)); 8666 mObserver = observer; 8667 mStats = stats; 8668 } 8669 8670 @Override 8671 public String toString() { 8672 return "MeasureParams{" 8673 + Integer.toHexString(System.identityHashCode(this)) 8674 + " " + mStats.packageName + "}"; 8675 } 8676 8677 @Override 8678 void handleStartCopy() throws RemoteException { 8679 synchronized (mInstallLock) { 8680 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8681 } 8682 8683 if (mSuccess) { 8684 final boolean mounted; 8685 if (Environment.isExternalStorageEmulated()) { 8686 mounted = true; 8687 } else { 8688 final String status = Environment.getExternalStorageState(); 8689 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8690 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8691 } 8692 8693 if (mounted) { 8694 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8695 8696 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8697 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8698 8699 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8700 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8701 8702 // Always subtract cache size, since it's a subdirectory 8703 mStats.externalDataSize -= mStats.externalCacheSize; 8704 8705 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8706 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8707 8708 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8709 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8710 } 8711 } 8712 } 8713 8714 @Override 8715 void handleReturnCode() { 8716 if (mObserver != null) { 8717 try { 8718 mObserver.onGetStatsCompleted(mStats, mSuccess); 8719 } catch (RemoteException e) { 8720 Slog.i(TAG, "Observer no longer exists."); 8721 } 8722 } 8723 } 8724 8725 @Override 8726 void handleServiceError() { 8727 Slog.e(TAG, "Could not measure application " + mStats.packageName 8728 + " external storage"); 8729 } 8730 } 8731 8732 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8733 throws RemoteException { 8734 long result = 0; 8735 for (File path : paths) { 8736 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8737 } 8738 return result; 8739 } 8740 8741 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8742 for (File path : paths) { 8743 try { 8744 mcs.clearDirectory(path.getAbsolutePath()); 8745 } catch (RemoteException e) { 8746 } 8747 } 8748 } 8749 8750 static class OriginInfo { 8751 /** 8752 * Location where install is coming from, before it has been 8753 * copied/renamed into place. This could be a single monolithic APK 8754 * file, or a cluster directory. This location may be untrusted. 8755 */ 8756 final File file; 8757 final String cid; 8758 8759 /** 8760 * Flag indicating that {@link #file} or {@link #cid} has already been 8761 * staged, meaning downstream users don't need to defensively copy the 8762 * contents. 8763 */ 8764 final boolean staged; 8765 8766 /** 8767 * Flag indicating that {@link #file} or {@link #cid} is an already 8768 * installed app that is being moved. 8769 */ 8770 final boolean existing; 8771 8772 final String resolvedPath; 8773 final File resolvedFile; 8774 8775 static OriginInfo fromNothing() { 8776 return new OriginInfo(null, null, false, false); 8777 } 8778 8779 static OriginInfo fromUntrustedFile(File file) { 8780 return new OriginInfo(file, null, false, false); 8781 } 8782 8783 static OriginInfo fromExistingFile(File file) { 8784 return new OriginInfo(file, null, false, true); 8785 } 8786 8787 static OriginInfo fromStagedFile(File file) { 8788 return new OriginInfo(file, null, true, false); 8789 } 8790 8791 static OriginInfo fromStagedContainer(String cid) { 8792 return new OriginInfo(null, cid, true, false); 8793 } 8794 8795 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8796 this.file = file; 8797 this.cid = cid; 8798 this.staged = staged; 8799 this.existing = existing; 8800 8801 if (cid != null) { 8802 resolvedPath = PackageHelper.getSdDir(cid); 8803 resolvedFile = new File(resolvedPath); 8804 } else if (file != null) { 8805 resolvedPath = file.getAbsolutePath(); 8806 resolvedFile = file; 8807 } else { 8808 resolvedPath = null; 8809 resolvedFile = null; 8810 } 8811 } 8812 } 8813 8814 class InstallParams extends HandlerParams { 8815 final OriginInfo origin; 8816 final IPackageInstallObserver2 observer; 8817 int installFlags; 8818 final String installerPackageName; 8819 final VerificationParams verificationParams; 8820 private InstallArgs mArgs; 8821 private int mRet; 8822 final String packageAbiOverride; 8823 8824 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8825 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8826 String packageAbiOverride) { 8827 super(user); 8828 this.origin = origin; 8829 this.observer = observer; 8830 this.installFlags = installFlags; 8831 this.installerPackageName = installerPackageName; 8832 this.verificationParams = verificationParams; 8833 this.packageAbiOverride = packageAbiOverride; 8834 } 8835 8836 @Override 8837 public String toString() { 8838 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8839 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8840 } 8841 8842 public ManifestDigest getManifestDigest() { 8843 if (verificationParams == null) { 8844 return null; 8845 } 8846 return verificationParams.getManifestDigest(); 8847 } 8848 8849 private int installLocationPolicy(PackageInfoLite pkgLite) { 8850 String packageName = pkgLite.packageName; 8851 int installLocation = pkgLite.installLocation; 8852 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8853 // reader 8854 synchronized (mPackages) { 8855 PackageParser.Package pkg = mPackages.get(packageName); 8856 if (pkg != null) { 8857 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8858 // Check for downgrading. 8859 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8860 if (pkgLite.versionCode < pkg.mVersionCode) { 8861 Slog.w(TAG, "Can't install update of " + packageName 8862 + " update version " + pkgLite.versionCode 8863 + " is older than installed version " 8864 + pkg.mVersionCode); 8865 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8866 } 8867 } 8868 // Check for updated system application. 8869 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8870 if (onSd) { 8871 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8872 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8873 } 8874 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8875 } else { 8876 if (onSd) { 8877 // Install flag overrides everything. 8878 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8879 } 8880 // If current upgrade specifies particular preference 8881 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8882 // Application explicitly specified internal. 8883 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8884 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8885 // App explictly prefers external. Let policy decide 8886 } else { 8887 // Prefer previous location 8888 if (isExternal(pkg)) { 8889 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8890 } 8891 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8892 } 8893 } 8894 } else { 8895 // Invalid install. Return error code 8896 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8897 } 8898 } 8899 } 8900 // All the special cases have been taken care of. 8901 // Return result based on recommended install location. 8902 if (onSd) { 8903 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8904 } 8905 return pkgLite.recommendedInstallLocation; 8906 } 8907 8908 /* 8909 * Invoke remote method to get package information and install 8910 * location values. Override install location based on default 8911 * policy if needed and then create install arguments based 8912 * on the install location. 8913 */ 8914 public void handleStartCopy() throws RemoteException { 8915 int ret = PackageManager.INSTALL_SUCCEEDED; 8916 8917 // If we're already staged, we've firmly committed to an install location 8918 if (origin.staged) { 8919 if (origin.file != null) { 8920 installFlags |= PackageManager.INSTALL_INTERNAL; 8921 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8922 } else if (origin.cid != null) { 8923 installFlags |= PackageManager.INSTALL_EXTERNAL; 8924 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8925 } else { 8926 throw new IllegalStateException("Invalid stage location"); 8927 } 8928 } 8929 8930 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8931 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8932 8933 PackageInfoLite pkgLite = null; 8934 8935 if (onInt && onSd) { 8936 // Check if both bits are set. 8937 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8938 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8939 } else { 8940 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8941 packageAbiOverride); 8942 8943 /* 8944 * If we have too little free space, try to free cache 8945 * before giving up. 8946 */ 8947 if (!origin.staged && pkgLite.recommendedInstallLocation 8948 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8949 // TODO: focus freeing disk space on the target device 8950 final StorageManager storage = StorageManager.from(mContext); 8951 final long lowThreshold = storage.getStorageLowBytes( 8952 Environment.getDataDirectory()); 8953 8954 final long sizeBytes = mContainerService.calculateInstalledSize( 8955 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8956 8957 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8958 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8959 installFlags, packageAbiOverride); 8960 } 8961 8962 /* 8963 * The cache free must have deleted the file we 8964 * downloaded to install. 8965 * 8966 * TODO: fix the "freeCache" call to not delete 8967 * the file we care about. 8968 */ 8969 if (pkgLite.recommendedInstallLocation 8970 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8971 pkgLite.recommendedInstallLocation 8972 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8973 } 8974 } 8975 } 8976 8977 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8978 int loc = pkgLite.recommendedInstallLocation; 8979 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8980 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8981 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8982 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8983 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8984 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8985 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8986 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8987 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8988 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8989 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8990 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8991 } else { 8992 // Override with defaults if needed. 8993 loc = installLocationPolicy(pkgLite); 8994 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8995 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8996 } else if (!onSd && !onInt) { 8997 // Override install location with flags 8998 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8999 // Set the flag to install on external media. 9000 installFlags |= PackageManager.INSTALL_EXTERNAL; 9001 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9002 } else { 9003 // Make sure the flag for installing on external 9004 // media is unset 9005 installFlags |= PackageManager.INSTALL_INTERNAL; 9006 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9007 } 9008 } 9009 } 9010 } 9011 9012 final InstallArgs args = createInstallArgs(this); 9013 mArgs = args; 9014 9015 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9016 /* 9017 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9018 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9019 */ 9020 int userIdentifier = getUser().getIdentifier(); 9021 if (userIdentifier == UserHandle.USER_ALL 9022 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9023 userIdentifier = UserHandle.USER_OWNER; 9024 } 9025 9026 /* 9027 * Determine if we have any installed package verifiers. If we 9028 * do, then we'll defer to them to verify the packages. 9029 */ 9030 final int requiredUid = mRequiredVerifierPackage == null ? -1 9031 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9032 if (!origin.existing && requiredUid != -1 9033 && isVerificationEnabled(userIdentifier, installFlags)) { 9034 final Intent verification = new Intent( 9035 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9036 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9037 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9038 PACKAGE_MIME_TYPE); 9039 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9040 9041 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9042 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9043 0 /* TODO: Which userId? */); 9044 9045 if (DEBUG_VERIFY) { 9046 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9047 + verification.toString() + " with " + pkgLite.verifiers.length 9048 + " optional verifiers"); 9049 } 9050 9051 final int verificationId = mPendingVerificationToken++; 9052 9053 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9054 9055 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9056 installerPackageName); 9057 9058 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9059 installFlags); 9060 9061 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9062 pkgLite.packageName); 9063 9064 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9065 pkgLite.versionCode); 9066 9067 if (verificationParams != null) { 9068 if (verificationParams.getVerificationURI() != null) { 9069 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9070 verificationParams.getVerificationURI()); 9071 } 9072 if (verificationParams.getOriginatingURI() != null) { 9073 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9074 verificationParams.getOriginatingURI()); 9075 } 9076 if (verificationParams.getReferrer() != null) { 9077 verification.putExtra(Intent.EXTRA_REFERRER, 9078 verificationParams.getReferrer()); 9079 } 9080 if (verificationParams.getOriginatingUid() >= 0) { 9081 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9082 verificationParams.getOriginatingUid()); 9083 } 9084 if (verificationParams.getInstallerUid() >= 0) { 9085 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9086 verificationParams.getInstallerUid()); 9087 } 9088 } 9089 9090 final PackageVerificationState verificationState = new PackageVerificationState( 9091 requiredUid, args); 9092 9093 mPendingVerification.append(verificationId, verificationState); 9094 9095 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9096 receivers, verificationState); 9097 9098 /* 9099 * If any sufficient verifiers were listed in the package 9100 * manifest, attempt to ask them. 9101 */ 9102 if (sufficientVerifiers != null) { 9103 final int N = sufficientVerifiers.size(); 9104 if (N == 0) { 9105 Slog.i(TAG, "Additional verifiers required, but none installed."); 9106 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9107 } else { 9108 for (int i = 0; i < N; i++) { 9109 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9110 9111 final Intent sufficientIntent = new Intent(verification); 9112 sufficientIntent.setComponent(verifierComponent); 9113 9114 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9115 } 9116 } 9117 } 9118 9119 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9120 mRequiredVerifierPackage, receivers); 9121 if (ret == PackageManager.INSTALL_SUCCEEDED 9122 && mRequiredVerifierPackage != null) { 9123 /* 9124 * Send the intent to the required verification agent, 9125 * but only start the verification timeout after the 9126 * target BroadcastReceivers have run. 9127 */ 9128 verification.setComponent(requiredVerifierComponent); 9129 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9130 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9131 new BroadcastReceiver() { 9132 @Override 9133 public void onReceive(Context context, Intent intent) { 9134 final Message msg = mHandler 9135 .obtainMessage(CHECK_PENDING_VERIFICATION); 9136 msg.arg1 = verificationId; 9137 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9138 } 9139 }, null, 0, null, null); 9140 9141 /* 9142 * We don't want the copy to proceed until verification 9143 * succeeds, so null out this field. 9144 */ 9145 mArgs = null; 9146 } 9147 } else { 9148 /* 9149 * No package verification is enabled, so immediately start 9150 * the remote call to initiate copy using temporary file. 9151 */ 9152 ret = args.copyApk(mContainerService, true); 9153 } 9154 } 9155 9156 mRet = ret; 9157 } 9158 9159 @Override 9160 void handleReturnCode() { 9161 // If mArgs is null, then MCS couldn't be reached. When it 9162 // reconnects, it will try again to install. At that point, this 9163 // will succeed. 9164 if (mArgs != null) { 9165 processPendingInstall(mArgs, mRet); 9166 } 9167 } 9168 9169 @Override 9170 void handleServiceError() { 9171 mArgs = createInstallArgs(this); 9172 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9173 } 9174 9175 public boolean isForwardLocked() { 9176 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9177 } 9178 } 9179 9180 /** 9181 * Used during creation of InstallArgs 9182 * 9183 * @param installFlags package installation flags 9184 * @return true if should be installed on external storage 9185 */ 9186 private static boolean installOnSd(int installFlags) { 9187 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9188 return false; 9189 } 9190 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9191 return true; 9192 } 9193 return false; 9194 } 9195 9196 /** 9197 * Used during creation of InstallArgs 9198 * 9199 * @param installFlags package installation flags 9200 * @return true if should be installed as forward locked 9201 */ 9202 private static boolean installForwardLocked(int installFlags) { 9203 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9204 } 9205 9206 private InstallArgs createInstallArgs(InstallParams params) { 9207 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 9208 return new AsecInstallArgs(params); 9209 } else { 9210 return new FileInstallArgs(params); 9211 } 9212 } 9213 9214 /** 9215 * Create args that describe an existing installed package. Typically used 9216 * when cleaning up old installs, or used as a move source. 9217 */ 9218 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9219 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9220 final boolean isInAsec; 9221 if (installOnSd(installFlags)) { 9222 /* Apps on SD card are always in ASEC containers. */ 9223 isInAsec = true; 9224 } else if (installForwardLocked(installFlags) 9225 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9226 /* 9227 * Forward-locked apps are only in ASEC containers if they're the 9228 * new style 9229 */ 9230 isInAsec = true; 9231 } else { 9232 isInAsec = false; 9233 } 9234 9235 if (isInAsec) { 9236 return new AsecInstallArgs(codePath, instructionSets, 9237 installOnSd(installFlags), installForwardLocked(installFlags)); 9238 } else { 9239 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9240 instructionSets); 9241 } 9242 } 9243 9244 static abstract class InstallArgs { 9245 /** @see InstallParams#origin */ 9246 final OriginInfo origin; 9247 9248 final IPackageInstallObserver2 observer; 9249 // Always refers to PackageManager flags only 9250 final int installFlags; 9251 final String installerPackageName; 9252 final ManifestDigest manifestDigest; 9253 final UserHandle user; 9254 final String abiOverride; 9255 9256 // The list of instruction sets supported by this app. This is currently 9257 // only used during the rmdex() phase to clean up resources. We can get rid of this 9258 // if we move dex files under the common app path. 9259 /* nullable */ String[] instructionSets; 9260 9261 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9262 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 9263 String[] instructionSets, String abiOverride) { 9264 this.origin = origin; 9265 this.installFlags = installFlags; 9266 this.observer = observer; 9267 this.installerPackageName = installerPackageName; 9268 this.manifestDigest = manifestDigest; 9269 this.user = user; 9270 this.instructionSets = instructionSets; 9271 this.abiOverride = abiOverride; 9272 } 9273 9274 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9275 abstract int doPreInstall(int status); 9276 9277 /** 9278 * Rename package into final resting place. All paths on the given 9279 * scanned package should be updated to reflect the rename. 9280 */ 9281 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9282 abstract int doPostInstall(int status, int uid); 9283 9284 /** @see PackageSettingBase#codePathString */ 9285 abstract String getCodePath(); 9286 /** @see PackageSettingBase#resourcePathString */ 9287 abstract String getResourcePath(); 9288 abstract String getLegacyNativeLibraryPath(); 9289 9290 // Need installer lock especially for dex file removal. 9291 abstract void cleanUpResourcesLI(); 9292 abstract boolean doPostDeleteLI(boolean delete); 9293 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9294 9295 /** 9296 * Called before the source arguments are copied. This is used mostly 9297 * for MoveParams when it needs to read the source file to put it in the 9298 * destination. 9299 */ 9300 int doPreCopy() { 9301 return PackageManager.INSTALL_SUCCEEDED; 9302 } 9303 9304 /** 9305 * Called after the source arguments are copied. This is used mostly for 9306 * MoveParams when it needs to read the source file to put it in the 9307 * destination. 9308 * 9309 * @return 9310 */ 9311 int doPostCopy(int uid) { 9312 return PackageManager.INSTALL_SUCCEEDED; 9313 } 9314 9315 protected boolean isFwdLocked() { 9316 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9317 } 9318 9319 protected boolean isExternal() { 9320 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9321 } 9322 9323 UserHandle getUser() { 9324 return user; 9325 } 9326 } 9327 9328 /** 9329 * Logic to handle installation of non-ASEC applications, including copying 9330 * and renaming logic. 9331 */ 9332 class FileInstallArgs extends InstallArgs { 9333 private File codeFile; 9334 private File resourceFile; 9335 private File legacyNativeLibraryPath; 9336 9337 // Example topology: 9338 // /data/app/com.example/base.apk 9339 // /data/app/com.example/split_foo.apk 9340 // /data/app/com.example/lib/arm/libfoo.so 9341 // /data/app/com.example/lib/arm64/libfoo.so 9342 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9343 9344 /** New install */ 9345 FileInstallArgs(InstallParams params) { 9346 super(params.origin, params.observer, params.installFlags, 9347 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9348 null /* instruction sets */, params.packageAbiOverride); 9349 if (isFwdLocked()) { 9350 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9351 } 9352 } 9353 9354 /** Existing install */ 9355 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9356 String[] instructionSets) { 9357 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9358 this.codeFile = (codePath != null) ? new File(codePath) : null; 9359 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9360 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9361 new File(legacyNativeLibraryPath) : null; 9362 } 9363 9364 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9365 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9366 isFwdLocked(), abiOverride); 9367 9368 final StorageManager storage = StorageManager.from(mContext); 9369 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9370 } 9371 9372 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9373 if (origin.staged) { 9374 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9375 codeFile = origin.file; 9376 resourceFile = origin.file; 9377 return PackageManager.INSTALL_SUCCEEDED; 9378 } 9379 9380 try { 9381 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9382 codeFile = tempDir; 9383 resourceFile = tempDir; 9384 } catch (IOException e) { 9385 Slog.w(TAG, "Failed to create copy file: " + e); 9386 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9387 } 9388 9389 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9390 @Override 9391 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9392 if (!FileUtils.isValidExtFilename(name)) { 9393 throw new IllegalArgumentException("Invalid filename: " + name); 9394 } 9395 try { 9396 final File file = new File(codeFile, name); 9397 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9398 O_RDWR | O_CREAT, 0644); 9399 Os.chmod(file.getAbsolutePath(), 0644); 9400 return new ParcelFileDescriptor(fd); 9401 } catch (ErrnoException e) { 9402 throw new RemoteException("Failed to open: " + e.getMessage()); 9403 } 9404 } 9405 }; 9406 9407 int ret = PackageManager.INSTALL_SUCCEEDED; 9408 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9409 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9410 Slog.e(TAG, "Failed to copy package"); 9411 return ret; 9412 } 9413 9414 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9415 NativeLibraryHelper.Handle handle = null; 9416 try { 9417 handle = NativeLibraryHelper.Handle.create(codeFile); 9418 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9419 abiOverride); 9420 } catch (IOException e) { 9421 Slog.e(TAG, "Copying native libraries failed", e); 9422 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9423 } finally { 9424 IoUtils.closeQuietly(handle); 9425 } 9426 9427 return ret; 9428 } 9429 9430 int doPreInstall(int status) { 9431 if (status != PackageManager.INSTALL_SUCCEEDED) { 9432 cleanUp(); 9433 } 9434 return status; 9435 } 9436 9437 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9438 if (status != PackageManager.INSTALL_SUCCEEDED) { 9439 cleanUp(); 9440 return false; 9441 } else { 9442 final File beforeCodeFile = codeFile; 9443 final File afterCodeFile = getNextCodePath(pkg.packageName); 9444 9445 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9446 try { 9447 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9448 } catch (ErrnoException e) { 9449 Slog.d(TAG, "Failed to rename", e); 9450 return false; 9451 } 9452 9453 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9454 Slog.d(TAG, "Failed to restorecon"); 9455 return false; 9456 } 9457 9458 // Reflect the rename internally 9459 codeFile = afterCodeFile; 9460 resourceFile = afterCodeFile; 9461 9462 // Reflect the rename in scanned details 9463 pkg.codePath = afterCodeFile.getAbsolutePath(); 9464 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9465 pkg.baseCodePath); 9466 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9467 pkg.splitCodePaths); 9468 9469 // Reflect the rename in app info 9470 pkg.applicationInfo.setCodePath(pkg.codePath); 9471 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9472 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9473 pkg.applicationInfo.setResourcePath(pkg.codePath); 9474 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9475 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9476 9477 return true; 9478 } 9479 } 9480 9481 int doPostInstall(int status, int uid) { 9482 if (status != PackageManager.INSTALL_SUCCEEDED) { 9483 cleanUp(); 9484 } 9485 return status; 9486 } 9487 9488 @Override 9489 String getCodePath() { 9490 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9491 } 9492 9493 @Override 9494 String getResourcePath() { 9495 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9496 } 9497 9498 @Override 9499 String getLegacyNativeLibraryPath() { 9500 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9501 } 9502 9503 private boolean cleanUp() { 9504 if (codeFile == null || !codeFile.exists()) { 9505 return false; 9506 } 9507 9508 if (codeFile.isDirectory()) { 9509 FileUtils.deleteContents(codeFile); 9510 } 9511 codeFile.delete(); 9512 9513 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9514 resourceFile.delete(); 9515 } 9516 9517 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9518 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9519 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9520 } 9521 legacyNativeLibraryPath.delete(); 9522 } 9523 9524 return true; 9525 } 9526 9527 void cleanUpResourcesLI() { 9528 // Try enumerating all code paths before deleting 9529 List<String> allCodePaths = Collections.EMPTY_LIST; 9530 if (codeFile != null && codeFile.exists()) { 9531 try { 9532 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9533 allCodePaths = pkg.getAllCodePaths(); 9534 } catch (PackageParserException e) { 9535 // Ignored; we tried our best 9536 } 9537 } 9538 9539 cleanUp(); 9540 9541 if (!allCodePaths.isEmpty()) { 9542 if (instructionSets == null) { 9543 throw new IllegalStateException("instructionSet == null"); 9544 } 9545 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9546 for (String codePath : allCodePaths) { 9547 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9548 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9549 if (retCode < 0) { 9550 Slog.w(TAG, "Couldn't remove dex file for package: " 9551 + " at location " + codePath + ", retcode=" + retCode); 9552 // we don't consider this to be a failure of the core package deletion 9553 } 9554 } 9555 } 9556 } 9557 } 9558 9559 boolean doPostDeleteLI(boolean delete) { 9560 // XXX err, shouldn't we respect the delete flag? 9561 cleanUpResourcesLI(); 9562 return true; 9563 } 9564 } 9565 9566 private boolean isAsecExternal(String cid) { 9567 final String asecPath = PackageHelper.getSdFilesystem(cid); 9568 return !asecPath.startsWith(mAsecInternalPath); 9569 } 9570 9571 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9572 PackageManagerException { 9573 if (copyRet < 0) { 9574 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9575 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9576 throw new PackageManagerException(copyRet, message); 9577 } 9578 } 9579 } 9580 9581 /** 9582 * Extract the MountService "container ID" from the full code path of an 9583 * .apk. 9584 */ 9585 static String cidFromCodePath(String fullCodePath) { 9586 int eidx = fullCodePath.lastIndexOf("/"); 9587 String subStr1 = fullCodePath.substring(0, eidx); 9588 int sidx = subStr1.lastIndexOf("/"); 9589 return subStr1.substring(sidx+1, eidx); 9590 } 9591 9592 /** 9593 * Logic to handle installation of ASEC applications, including copying and 9594 * renaming logic. 9595 */ 9596 class AsecInstallArgs extends InstallArgs { 9597 static final String RES_FILE_NAME = "pkg.apk"; 9598 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9599 9600 String cid; 9601 String packagePath; 9602 String resourcePath; 9603 String legacyNativeLibraryDir; 9604 9605 /** New install */ 9606 AsecInstallArgs(InstallParams params) { 9607 super(params.origin, params.observer, params.installFlags, 9608 params.installerPackageName, params.getManifestDigest(), 9609 params.getUser(), null /* instruction sets */, 9610 params.packageAbiOverride); 9611 } 9612 9613 /** Existing install */ 9614 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9615 boolean isExternal, boolean isForwardLocked) { 9616 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9617 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9618 instructionSets, null); 9619 // Hackily pretend we're still looking at a full code path 9620 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9621 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9622 } 9623 9624 // Extract cid from fullCodePath 9625 int eidx = fullCodePath.lastIndexOf("/"); 9626 String subStr1 = fullCodePath.substring(0, eidx); 9627 int sidx = subStr1.lastIndexOf("/"); 9628 cid = subStr1.substring(sidx+1, eidx); 9629 setMountPath(subStr1); 9630 } 9631 9632 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9633 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9634 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9635 instructionSets, null); 9636 this.cid = cid; 9637 setMountPath(PackageHelper.getSdDir(cid)); 9638 } 9639 9640 void createCopyFile() { 9641 cid = mInstallerService.allocateExternalStageCidLegacy(); 9642 } 9643 9644 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9645 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9646 abiOverride); 9647 9648 final File target; 9649 if (isExternal()) { 9650 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9651 } else { 9652 target = Environment.getDataDirectory(); 9653 } 9654 9655 final StorageManager storage = StorageManager.from(mContext); 9656 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9657 } 9658 9659 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9660 if (origin.staged) { 9661 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9662 cid = origin.cid; 9663 setMountPath(PackageHelper.getSdDir(cid)); 9664 return PackageManager.INSTALL_SUCCEEDED; 9665 } 9666 9667 if (temp) { 9668 createCopyFile(); 9669 } else { 9670 /* 9671 * Pre-emptively destroy the container since it's destroyed if 9672 * copying fails due to it existing anyway. 9673 */ 9674 PackageHelper.destroySdDir(cid); 9675 } 9676 9677 final String newMountPath = imcs.copyPackageToContainer( 9678 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9679 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9680 9681 if (newMountPath != null) { 9682 setMountPath(newMountPath); 9683 return PackageManager.INSTALL_SUCCEEDED; 9684 } else { 9685 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9686 } 9687 } 9688 9689 @Override 9690 String getCodePath() { 9691 return packagePath; 9692 } 9693 9694 @Override 9695 String getResourcePath() { 9696 return resourcePath; 9697 } 9698 9699 @Override 9700 String getLegacyNativeLibraryPath() { 9701 return legacyNativeLibraryDir; 9702 } 9703 9704 int doPreInstall(int status) { 9705 if (status != PackageManager.INSTALL_SUCCEEDED) { 9706 // Destroy container 9707 PackageHelper.destroySdDir(cid); 9708 } else { 9709 boolean mounted = PackageHelper.isContainerMounted(cid); 9710 if (!mounted) { 9711 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9712 Process.SYSTEM_UID); 9713 if (newMountPath != null) { 9714 setMountPath(newMountPath); 9715 } else { 9716 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9717 } 9718 } 9719 } 9720 return status; 9721 } 9722 9723 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9724 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9725 String newMountPath = null; 9726 if (PackageHelper.isContainerMounted(cid)) { 9727 // Unmount the container 9728 if (!PackageHelper.unMountSdDir(cid)) { 9729 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9730 return false; 9731 } 9732 } 9733 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9734 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9735 " which might be stale. Will try to clean up."); 9736 // Clean up the stale container and proceed to recreate. 9737 if (!PackageHelper.destroySdDir(newCacheId)) { 9738 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9739 return false; 9740 } 9741 // Successfully cleaned up stale container. Try to rename again. 9742 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9743 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9744 + " inspite of cleaning it up."); 9745 return false; 9746 } 9747 } 9748 if (!PackageHelper.isContainerMounted(newCacheId)) { 9749 Slog.w(TAG, "Mounting container " + newCacheId); 9750 newMountPath = PackageHelper.mountSdDir(newCacheId, 9751 getEncryptKey(), Process.SYSTEM_UID); 9752 } else { 9753 newMountPath = PackageHelper.getSdDir(newCacheId); 9754 } 9755 if (newMountPath == null) { 9756 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9757 return false; 9758 } 9759 Log.i(TAG, "Succesfully renamed " + cid + 9760 " to " + newCacheId + 9761 " at new path: " + newMountPath); 9762 cid = newCacheId; 9763 9764 final File beforeCodeFile = new File(packagePath); 9765 setMountPath(newMountPath); 9766 final File afterCodeFile = new File(packagePath); 9767 9768 // Reflect the rename in scanned details 9769 pkg.codePath = afterCodeFile.getAbsolutePath(); 9770 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9771 pkg.baseCodePath); 9772 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9773 pkg.splitCodePaths); 9774 9775 // Reflect the rename in app info 9776 pkg.applicationInfo.setCodePath(pkg.codePath); 9777 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9778 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9779 pkg.applicationInfo.setResourcePath(pkg.codePath); 9780 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9781 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9782 9783 return true; 9784 } 9785 9786 private void setMountPath(String mountPath) { 9787 final File mountFile = new File(mountPath); 9788 9789 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9790 if (monolithicFile.exists()) { 9791 packagePath = monolithicFile.getAbsolutePath(); 9792 if (isFwdLocked()) { 9793 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9794 } else { 9795 resourcePath = packagePath; 9796 } 9797 } else { 9798 packagePath = mountFile.getAbsolutePath(); 9799 resourcePath = packagePath; 9800 } 9801 9802 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9803 } 9804 9805 int doPostInstall(int status, int uid) { 9806 if (status != PackageManager.INSTALL_SUCCEEDED) { 9807 cleanUp(); 9808 } else { 9809 final int groupOwner; 9810 final String protectedFile; 9811 if (isFwdLocked()) { 9812 groupOwner = UserHandle.getSharedAppGid(uid); 9813 protectedFile = RES_FILE_NAME; 9814 } else { 9815 groupOwner = -1; 9816 protectedFile = null; 9817 } 9818 9819 if (uid < Process.FIRST_APPLICATION_UID 9820 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9821 Slog.e(TAG, "Failed to finalize " + cid); 9822 PackageHelper.destroySdDir(cid); 9823 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9824 } 9825 9826 boolean mounted = PackageHelper.isContainerMounted(cid); 9827 if (!mounted) { 9828 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9829 } 9830 } 9831 return status; 9832 } 9833 9834 private void cleanUp() { 9835 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9836 9837 // Destroy secure container 9838 PackageHelper.destroySdDir(cid); 9839 } 9840 9841 private List<String> getAllCodePaths() { 9842 final File codeFile = new File(getCodePath()); 9843 if (codeFile != null && codeFile.exists()) { 9844 try { 9845 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9846 return pkg.getAllCodePaths(); 9847 } catch (PackageParserException e) { 9848 // Ignored; we tried our best 9849 } 9850 } 9851 return Collections.EMPTY_LIST; 9852 } 9853 9854 void cleanUpResourcesLI() { 9855 // Enumerate all code paths before deleting 9856 cleanUpResourcesLI(getAllCodePaths()); 9857 } 9858 9859 private void cleanUpResourcesLI(List<String> allCodePaths) { 9860 cleanUp(); 9861 9862 if (!allCodePaths.isEmpty()) { 9863 if (instructionSets == null) { 9864 throw new IllegalStateException("instructionSet == null"); 9865 } 9866 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9867 for (String codePath : allCodePaths) { 9868 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9869 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9870 if (retCode < 0) { 9871 Slog.w(TAG, "Couldn't remove dex file for package: " 9872 + " at location " + codePath + ", retcode=" + retCode); 9873 // we don't consider this to be a failure of the core package deletion 9874 } 9875 } 9876 } 9877 } 9878 } 9879 9880 boolean matchContainer(String app) { 9881 if (cid.startsWith(app)) { 9882 return true; 9883 } 9884 return false; 9885 } 9886 9887 String getPackageName() { 9888 return getAsecPackageName(cid); 9889 } 9890 9891 boolean doPostDeleteLI(boolean delete) { 9892 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9893 final List<String> allCodePaths = getAllCodePaths(); 9894 boolean mounted = PackageHelper.isContainerMounted(cid); 9895 if (mounted) { 9896 // Unmount first 9897 if (PackageHelper.unMountSdDir(cid)) { 9898 mounted = false; 9899 } 9900 } 9901 if (!mounted && delete) { 9902 cleanUpResourcesLI(allCodePaths); 9903 } 9904 return !mounted; 9905 } 9906 9907 @Override 9908 int doPreCopy() { 9909 if (isFwdLocked()) { 9910 if (!PackageHelper.fixSdPermissions(cid, 9911 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9912 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9913 } 9914 } 9915 9916 return PackageManager.INSTALL_SUCCEEDED; 9917 } 9918 9919 @Override 9920 int doPostCopy(int uid) { 9921 if (isFwdLocked()) { 9922 if (uid < Process.FIRST_APPLICATION_UID 9923 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9924 RES_FILE_NAME)) { 9925 Slog.e(TAG, "Failed to finalize " + cid); 9926 PackageHelper.destroySdDir(cid); 9927 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9928 } 9929 } 9930 9931 return PackageManager.INSTALL_SUCCEEDED; 9932 } 9933 } 9934 9935 static String getAsecPackageName(String packageCid) { 9936 int idx = packageCid.lastIndexOf("-"); 9937 if (idx == -1) { 9938 return packageCid; 9939 } 9940 return packageCid.substring(0, idx); 9941 } 9942 9943 // Utility method used to create code paths based on package name and available index. 9944 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9945 String idxStr = ""; 9946 int idx = 1; 9947 // Fall back to default value of idx=1 if prefix is not 9948 // part of oldCodePath 9949 if (oldCodePath != null) { 9950 String subStr = oldCodePath; 9951 // Drop the suffix right away 9952 if (suffix != null && subStr.endsWith(suffix)) { 9953 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9954 } 9955 // If oldCodePath already contains prefix find out the 9956 // ending index to either increment or decrement. 9957 int sidx = subStr.lastIndexOf(prefix); 9958 if (sidx != -1) { 9959 subStr = subStr.substring(sidx + prefix.length()); 9960 if (subStr != null) { 9961 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9962 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9963 } 9964 try { 9965 idx = Integer.parseInt(subStr); 9966 if (idx <= 1) { 9967 idx++; 9968 } else { 9969 idx--; 9970 } 9971 } catch(NumberFormatException e) { 9972 } 9973 } 9974 } 9975 } 9976 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9977 return prefix + idxStr; 9978 } 9979 9980 private File getNextCodePath(String packageName) { 9981 int suffix = 1; 9982 File result; 9983 do { 9984 result = new File(mAppInstallDir, packageName + "-" + suffix); 9985 suffix++; 9986 } while (result.exists()); 9987 return result; 9988 } 9989 9990 // Utility method used to ignore ADD/REMOVE events 9991 // by directory observer. 9992 private static boolean ignoreCodePath(String fullPathStr) { 9993 String apkName = deriveCodePathName(fullPathStr); 9994 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9995 if (idx != -1 && ((idx+1) < apkName.length())) { 9996 // Make sure the package ends with a numeral 9997 String version = apkName.substring(idx+1); 9998 try { 9999 Integer.parseInt(version); 10000 return true; 10001 } catch (NumberFormatException e) {} 10002 } 10003 return false; 10004 } 10005 10006 // Utility method that returns the relative package path with respect 10007 // to the installation directory. Like say for /data/data/com.test-1.apk 10008 // string com.test-1 is returned. 10009 static String deriveCodePathName(String codePath) { 10010 if (codePath == null) { 10011 return null; 10012 } 10013 final File codeFile = new File(codePath); 10014 final String name = codeFile.getName(); 10015 if (codeFile.isDirectory()) { 10016 return name; 10017 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10018 final int lastDot = name.lastIndexOf('.'); 10019 return name.substring(0, lastDot); 10020 } else { 10021 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10022 return null; 10023 } 10024 } 10025 10026 class PackageInstalledInfo { 10027 String name; 10028 int uid; 10029 // The set of users that originally had this package installed. 10030 int[] origUsers; 10031 // The set of users that now have this package installed. 10032 int[] newUsers; 10033 PackageParser.Package pkg; 10034 int returnCode; 10035 String returnMsg; 10036 PackageRemovedInfo removedInfo; 10037 10038 public void setError(int code, String msg) { 10039 returnCode = code; 10040 returnMsg = msg; 10041 Slog.w(TAG, msg); 10042 } 10043 10044 public void setError(String msg, PackageParserException e) { 10045 returnCode = e.error; 10046 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10047 Slog.w(TAG, msg, e); 10048 } 10049 10050 public void setError(String msg, PackageManagerException e) { 10051 returnCode = e.error; 10052 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10053 Slog.w(TAG, msg, e); 10054 } 10055 10056 // In some error cases we want to convey more info back to the observer 10057 String origPackage; 10058 String origPermission; 10059 } 10060 10061 /* 10062 * Install a non-existing package. 10063 */ 10064 private void installNewPackageLI(PackageParser.Package pkg, 10065 int parseFlags, int scanFlags, UserHandle user, 10066 String installerPackageName, PackageInstalledInfo res) { 10067 // Remember this for later, in case we need to rollback this install 10068 String pkgName = pkg.packageName; 10069 10070 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10071 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 10072 synchronized(mPackages) { 10073 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10074 // A package with the same name is already installed, though 10075 // it has been renamed to an older name. The package we 10076 // are trying to install should be installed as an update to 10077 // the existing one, but that has not been requested, so bail. 10078 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10079 + " without first uninstalling package running as " 10080 + mSettings.mRenamedPackages.get(pkgName)); 10081 return; 10082 } 10083 if (mPackages.containsKey(pkgName)) { 10084 // Don't allow installation over an existing package with the same name. 10085 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10086 + " without first uninstalling."); 10087 return; 10088 } 10089 } 10090 10091 try { 10092 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10093 System.currentTimeMillis(), user); 10094 10095 updateSettingsLI(newPackage, installerPackageName, null, null, res); 10096 // delete the partially installed application. the data directory will have to be 10097 // restored if it was already existing 10098 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10099 // remove package from internal structures. Note that we want deletePackageX to 10100 // delete the package data and cache directories that it created in 10101 // scanPackageLocked, unless those directories existed before we even tried to 10102 // install. 10103 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10104 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10105 res.removedInfo, true); 10106 } 10107 10108 } catch (PackageManagerException e) { 10109 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10110 } 10111 } 10112 10113 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10114 // Upgrade keysets are being used. Determine if new package has a superset of the 10115 // required keys. 10116 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10117 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10118 for (int i = 0; i < upgradeKeySets.length; i++) { 10119 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10120 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10121 return true; 10122 } 10123 } 10124 return false; 10125 } 10126 10127 private void replacePackageLI(PackageParser.Package pkg, 10128 int parseFlags, int scanFlags, UserHandle user, 10129 String installerPackageName, PackageInstalledInfo res) { 10130 PackageParser.Package oldPackage; 10131 String pkgName = pkg.packageName; 10132 int[] allUsers; 10133 boolean[] perUserInstalled; 10134 10135 // First find the old package info and check signatures 10136 synchronized(mPackages) { 10137 oldPackage = mPackages.get(pkgName); 10138 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10139 PackageSetting ps = mSettings.mPackages.get(pkgName); 10140 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10141 // default to original signature matching 10142 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10143 != PackageManager.SIGNATURE_MATCH) { 10144 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10145 "New package has a different signature: " + pkgName); 10146 return; 10147 } 10148 } else { 10149 if(!checkUpgradeKeySetLP(ps, pkg)) { 10150 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10151 "New package not signed by keys specified by upgrade-keysets: " 10152 + pkgName); 10153 return; 10154 } 10155 } 10156 10157 // In case of rollback, remember per-user/profile install state 10158 allUsers = sUserManager.getUserIds(); 10159 perUserInstalled = new boolean[allUsers.length]; 10160 for (int i = 0; i < allUsers.length; i++) { 10161 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10162 } 10163 } 10164 10165 boolean sysPkg = (isSystemApp(oldPackage)); 10166 if (sysPkg) { 10167 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10168 user, allUsers, perUserInstalled, installerPackageName, res); 10169 } else { 10170 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10171 user, allUsers, perUserInstalled, installerPackageName, res); 10172 } 10173 } 10174 10175 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10176 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10177 int[] allUsers, boolean[] perUserInstalled, 10178 String installerPackageName, PackageInstalledInfo res) { 10179 String pkgName = deletedPackage.packageName; 10180 boolean deletedPkg = true; 10181 boolean updatedSettings = false; 10182 10183 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10184 + deletedPackage); 10185 long origUpdateTime; 10186 if (pkg.mExtras != null) { 10187 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10188 } else { 10189 origUpdateTime = 0; 10190 } 10191 10192 // First delete the existing package while retaining the data directory 10193 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10194 res.removedInfo, true)) { 10195 // If the existing package wasn't successfully deleted 10196 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10197 deletedPkg = false; 10198 } else { 10199 // Successfully deleted the old package; proceed with replace. 10200 10201 // If deleted package lived in a container, give users a chance to 10202 // relinquish resources before killing. 10203 if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) { 10204 if (DEBUG_INSTALL) { 10205 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10206 } 10207 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10208 final ArrayList<String> pkgList = new ArrayList<String>(1); 10209 pkgList.add(deletedPackage.applicationInfo.packageName); 10210 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10211 } 10212 10213 deleteCodeCacheDirsLI(pkgName); 10214 try { 10215 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10216 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10217 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10218 updatedSettings = true; 10219 } catch (PackageManagerException e) { 10220 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10221 } 10222 } 10223 10224 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10225 // remove package from internal structures. Note that we want deletePackageX to 10226 // delete the package data and cache directories that it created in 10227 // scanPackageLocked, unless those directories existed before we even tried to 10228 // install. 10229 if(updatedSettings) { 10230 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10231 deletePackageLI( 10232 pkgName, null, true, allUsers, perUserInstalled, 10233 PackageManager.DELETE_KEEP_DATA, 10234 res.removedInfo, true); 10235 } 10236 // Since we failed to install the new package we need to restore the old 10237 // package that we deleted. 10238 if (deletedPkg) { 10239 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10240 File restoreFile = new File(deletedPackage.codePath); 10241 // Parse old package 10242 boolean oldOnSd = isExternal(deletedPackage); 10243 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10244 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10245 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10246 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10247 try { 10248 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10249 } catch (PackageManagerException e) { 10250 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10251 + e.getMessage()); 10252 return; 10253 } 10254 // Restore of old package succeeded. Update permissions. 10255 // writer 10256 synchronized (mPackages) { 10257 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10258 UPDATE_PERMISSIONS_ALL); 10259 // can downgrade to reader 10260 mSettings.writeLPr(); 10261 } 10262 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10263 } 10264 } 10265 } 10266 10267 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10268 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10269 int[] allUsers, boolean[] perUserInstalled, 10270 String installerPackageName, PackageInstalledInfo res) { 10271 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10272 + ", old=" + deletedPackage); 10273 boolean disabledSystem = false; 10274 boolean updatedSettings = false; 10275 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10276 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10277 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10278 } 10279 String packageName = deletedPackage.packageName; 10280 if (packageName == null) { 10281 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10282 "Attempt to delete null packageName."); 10283 return; 10284 } 10285 PackageParser.Package oldPkg; 10286 PackageSetting oldPkgSetting; 10287 // reader 10288 synchronized (mPackages) { 10289 oldPkg = mPackages.get(packageName); 10290 oldPkgSetting = mSettings.mPackages.get(packageName); 10291 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10292 (oldPkgSetting == null)) { 10293 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10294 "Couldn't find package:" + packageName + " information"); 10295 return; 10296 } 10297 } 10298 10299 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10300 10301 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10302 res.removedInfo.removedPackage = packageName; 10303 // Remove existing system package 10304 removePackageLI(oldPkgSetting, true); 10305 // writer 10306 synchronized (mPackages) { 10307 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10308 if (!disabledSystem && deletedPackage != null) { 10309 // We didn't need to disable the .apk as a current system package, 10310 // which means we are replacing another update that is already 10311 // installed. We need to make sure to delete the older one's .apk. 10312 res.removedInfo.args = createInstallArgsForExisting(0, 10313 deletedPackage.applicationInfo.getCodePath(), 10314 deletedPackage.applicationInfo.getResourcePath(), 10315 deletedPackage.applicationInfo.nativeLibraryRootDir, 10316 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10317 } else { 10318 res.removedInfo.args = null; 10319 } 10320 } 10321 10322 // Successfully disabled the old package. Now proceed with re-installation 10323 deleteCodeCacheDirsLI(packageName); 10324 10325 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10326 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10327 10328 PackageParser.Package newPackage = null; 10329 try { 10330 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10331 if (newPackage.mExtras != null) { 10332 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10333 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10334 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10335 10336 // is the update attempting to change shared user? that isn't going to work... 10337 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10338 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10339 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10340 + " to " + newPkgSetting.sharedUser); 10341 updatedSettings = true; 10342 } 10343 } 10344 10345 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10346 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10347 updatedSettings = true; 10348 } 10349 10350 } catch (PackageManagerException e) { 10351 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10352 } 10353 10354 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10355 // Re installation failed. Restore old information 10356 // Remove new pkg information 10357 if (newPackage != null) { 10358 removeInstalledPackageLI(newPackage, true); 10359 } 10360 // Add back the old system package 10361 try { 10362 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10363 } catch (PackageManagerException e) { 10364 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10365 } 10366 // Restore the old system information in Settings 10367 synchronized (mPackages) { 10368 if (disabledSystem) { 10369 mSettings.enableSystemPackageLPw(packageName); 10370 } 10371 if (updatedSettings) { 10372 mSettings.setInstallerPackageName(packageName, 10373 oldPkgSetting.installerPackageName); 10374 } 10375 mSettings.writeLPr(); 10376 } 10377 } 10378 } 10379 10380 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10381 int[] allUsers, boolean[] perUserInstalled, 10382 PackageInstalledInfo res) { 10383 String pkgName = newPackage.packageName; 10384 synchronized (mPackages) { 10385 //write settings. the installStatus will be incomplete at this stage. 10386 //note that the new package setting would have already been 10387 //added to mPackages. It hasn't been persisted yet. 10388 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10389 mSettings.writeLPr(); 10390 } 10391 10392 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10393 10394 synchronized (mPackages) { 10395 updatePermissionsLPw(newPackage.packageName, newPackage, 10396 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10397 ? UPDATE_PERMISSIONS_ALL : 0)); 10398 // For system-bundled packages, we assume that installing an upgraded version 10399 // of the package implies that the user actually wants to run that new code, 10400 // so we enable the package. 10401 if (isSystemApp(newPackage)) { 10402 // NB: implicit assumption that system package upgrades apply to all users 10403 if (DEBUG_INSTALL) { 10404 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10405 } 10406 PackageSetting ps = mSettings.mPackages.get(pkgName); 10407 if (ps != null) { 10408 if (res.origUsers != null) { 10409 for (int userHandle : res.origUsers) { 10410 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10411 userHandle, installerPackageName); 10412 } 10413 } 10414 // Also convey the prior install/uninstall state 10415 if (allUsers != null && perUserInstalled != null) { 10416 for (int i = 0; i < allUsers.length; i++) { 10417 if (DEBUG_INSTALL) { 10418 Slog.d(TAG, " user " + allUsers[i] 10419 + " => " + perUserInstalled[i]); 10420 } 10421 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10422 } 10423 // these install state changes will be persisted in the 10424 // upcoming call to mSettings.writeLPr(). 10425 } 10426 } 10427 } 10428 res.name = pkgName; 10429 res.uid = newPackage.applicationInfo.uid; 10430 res.pkg = newPackage; 10431 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10432 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10433 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10434 //to update install status 10435 mSettings.writeLPr(); 10436 } 10437 } 10438 10439 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10440 final int installFlags = args.installFlags; 10441 String installerPackageName = args.installerPackageName; 10442 File tmpPackageFile = new File(args.getCodePath()); 10443 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10444 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10445 boolean replace = false; 10446 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10447 // Result object to be returned 10448 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10449 10450 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10451 // Retrieve PackageSettings and parse package 10452 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10453 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10454 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10455 PackageParser pp = new PackageParser(); 10456 pp.setSeparateProcesses(mSeparateProcesses); 10457 pp.setDisplayMetrics(mMetrics); 10458 10459 final PackageParser.Package pkg; 10460 try { 10461 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10462 } catch (PackageParserException e) { 10463 res.setError("Failed parse during installPackageLI", e); 10464 return; 10465 } 10466 10467 // Mark that we have an install time CPU ABI override. 10468 pkg.cpuAbiOverride = args.abiOverride; 10469 10470 String pkgName = res.name = pkg.packageName; 10471 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10472 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10473 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10474 return; 10475 } 10476 } 10477 10478 try { 10479 pp.collectCertificates(pkg, parseFlags); 10480 pp.collectManifestDigest(pkg); 10481 } catch (PackageParserException e) { 10482 res.setError("Failed collect during installPackageLI", e); 10483 return; 10484 } 10485 10486 /* If the installer passed in a manifest digest, compare it now. */ 10487 if (args.manifestDigest != null) { 10488 if (DEBUG_INSTALL) { 10489 final String parsedManifest = pkg.manifestDigest == null ? "null" 10490 : pkg.manifestDigest.toString(); 10491 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10492 + parsedManifest); 10493 } 10494 10495 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10496 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10497 return; 10498 } 10499 } else if (DEBUG_INSTALL) { 10500 final String parsedManifest = pkg.manifestDigest == null 10501 ? "null" : pkg.manifestDigest.toString(); 10502 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10503 } 10504 10505 // Get rid of all references to package scan path via parser. 10506 pp = null; 10507 String oldCodePath = null; 10508 boolean systemApp = false; 10509 synchronized (mPackages) { 10510 // Check if installing already existing package 10511 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10512 String oldName = mSettings.mRenamedPackages.get(pkgName); 10513 if (pkg.mOriginalPackages != null 10514 && pkg.mOriginalPackages.contains(oldName) 10515 && mPackages.containsKey(oldName)) { 10516 // This package is derived from an original package, 10517 // and this device has been updating from that original 10518 // name. We must continue using the original name, so 10519 // rename the new package here. 10520 pkg.setPackageName(oldName); 10521 pkgName = pkg.packageName; 10522 replace = true; 10523 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10524 + oldName + " pkgName=" + pkgName); 10525 } else if (mPackages.containsKey(pkgName)) { 10526 // This package, under its official name, already exists 10527 // on the device; we should replace it. 10528 replace = true; 10529 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10530 } 10531 } 10532 10533 PackageSetting ps = mSettings.mPackages.get(pkgName); 10534 if (ps != null) { 10535 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10536 10537 // Quick sanity check that we're signed correctly if updating; 10538 // we'll check this again later when scanning, but we want to 10539 // bail early here before tripping over redefined permissions. 10540 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10541 try { 10542 verifySignaturesLP(ps, pkg); 10543 } catch (PackageManagerException e) { 10544 res.setError(e.error, e.getMessage()); 10545 return; 10546 } 10547 } else { 10548 if (!checkUpgradeKeySetLP(ps, pkg)) { 10549 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 10550 + pkg.packageName + " upgrade keys do not match the " 10551 + "previously installed version"); 10552 return; 10553 } 10554 } 10555 10556 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10557 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10558 systemApp = (ps.pkg.applicationInfo.flags & 10559 ApplicationInfo.FLAG_SYSTEM) != 0; 10560 } 10561 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10562 } 10563 10564 // Check whether the newly-scanned package wants to define an already-defined perm 10565 int N = pkg.permissions.size(); 10566 for (int i = N-1; i >= 0; i--) { 10567 PackageParser.Permission perm = pkg.permissions.get(i); 10568 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10569 if (bp != null) { 10570 // If the defining package is signed with our cert, it's okay. This 10571 // also includes the "updating the same package" case, of course. 10572 // "updating same package" could also involve key-rotation. 10573 final boolean sigsOk; 10574 if (!bp.sourcePackage.equals(pkg.packageName) 10575 || !(bp.packageSetting instanceof PackageSetting) 10576 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10577 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10578 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10579 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 10580 } else { 10581 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10582 } 10583 if (!sigsOk) { 10584 // If the owning package is the system itself, we log but allow 10585 // install to proceed; we fail the install on all other permission 10586 // redefinitions. 10587 if (!bp.sourcePackage.equals("android")) { 10588 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10589 + pkg.packageName + " attempting to redeclare permission " 10590 + perm.info.name + " already owned by " + bp.sourcePackage); 10591 res.origPermission = perm.info.name; 10592 res.origPackage = bp.sourcePackage; 10593 return; 10594 } else { 10595 Slog.w(TAG, "Package " + pkg.packageName 10596 + " attempting to redeclare system permission " 10597 + perm.info.name + "; ignoring new declaration"); 10598 pkg.permissions.remove(i); 10599 } 10600 } 10601 } 10602 } 10603 10604 } 10605 10606 if (systemApp && onSd) { 10607 // Disable updates to system apps on sdcard 10608 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10609 "Cannot install updates to system apps on sdcard"); 10610 return; 10611 } 10612 10613 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10614 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10615 return; 10616 } 10617 10618 if (replace) { 10619 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10620 installerPackageName, res); 10621 } else { 10622 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10623 args.user, installerPackageName, res); 10624 } 10625 synchronized (mPackages) { 10626 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10627 if (ps != null) { 10628 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10629 } 10630 } 10631 } 10632 10633 private static boolean isForwardLocked(PackageParser.Package pkg) { 10634 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10635 } 10636 10637 private static boolean isForwardLocked(ApplicationInfo info) { 10638 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10639 } 10640 10641 private boolean isForwardLocked(PackageSetting ps) { 10642 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10643 } 10644 10645 private static boolean isMultiArch(PackageSetting ps) { 10646 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10647 } 10648 10649 private static boolean isMultiArch(ApplicationInfo info) { 10650 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10651 } 10652 10653 private static boolean isExternal(PackageParser.Package pkg) { 10654 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10655 } 10656 10657 private static boolean isExternal(PackageSetting ps) { 10658 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10659 } 10660 10661 private static boolean isExternal(ApplicationInfo info) { 10662 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10663 } 10664 10665 private static boolean isSystemApp(PackageParser.Package pkg) { 10666 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10667 } 10668 10669 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10670 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10671 } 10672 10673 private static boolean isSystemApp(ApplicationInfo info) { 10674 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10675 } 10676 10677 private static boolean isSystemApp(PackageSetting ps) { 10678 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10679 } 10680 10681 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10682 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10683 } 10684 10685 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10686 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10687 } 10688 10689 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10690 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10691 } 10692 10693 private int packageFlagsToInstallFlags(PackageSetting ps) { 10694 int installFlags = 0; 10695 if (isExternal(ps)) { 10696 installFlags |= PackageManager.INSTALL_EXTERNAL; 10697 } 10698 if (isForwardLocked(ps)) { 10699 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10700 } 10701 return installFlags; 10702 } 10703 10704 private void deleteTempPackageFiles() { 10705 final FilenameFilter filter = new FilenameFilter() { 10706 public boolean accept(File dir, String name) { 10707 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10708 } 10709 }; 10710 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10711 file.delete(); 10712 } 10713 } 10714 10715 @Override 10716 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10717 int flags) { 10718 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10719 flags); 10720 } 10721 10722 @Override 10723 public void deletePackage(final String packageName, 10724 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10725 mContext.enforceCallingOrSelfPermission( 10726 android.Manifest.permission.DELETE_PACKAGES, null); 10727 final int uid = Binder.getCallingUid(); 10728 if (UserHandle.getUserId(uid) != userId) { 10729 mContext.enforceCallingPermission( 10730 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10731 "deletePackage for user " + userId); 10732 } 10733 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10734 try { 10735 observer.onPackageDeleted(packageName, 10736 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10737 } catch (RemoteException re) { 10738 } 10739 return; 10740 } 10741 10742 boolean uninstallBlocked = false; 10743 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10744 int[] users = sUserManager.getUserIds(); 10745 for (int i = 0; i < users.length; ++i) { 10746 if (getBlockUninstallForUser(packageName, users[i])) { 10747 uninstallBlocked = true; 10748 break; 10749 } 10750 } 10751 } else { 10752 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10753 } 10754 if (uninstallBlocked) { 10755 try { 10756 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10757 null); 10758 } catch (RemoteException re) { 10759 } 10760 return; 10761 } 10762 10763 if (DEBUG_REMOVE) { 10764 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10765 } 10766 // Queue up an async operation since the package deletion may take a little while. 10767 mHandler.post(new Runnable() { 10768 public void run() { 10769 mHandler.removeCallbacks(this); 10770 final int returnCode = deletePackageX(packageName, userId, flags); 10771 if (observer != null) { 10772 try { 10773 observer.onPackageDeleted(packageName, returnCode, null); 10774 } catch (RemoteException e) { 10775 Log.i(TAG, "Observer no longer exists."); 10776 } //end catch 10777 } //end if 10778 } //end run 10779 }); 10780 } 10781 10782 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10783 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10784 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10785 try { 10786 if (dpm != null) { 10787 if (dpm.isDeviceOwner(packageName)) { 10788 return true; 10789 } 10790 int[] users; 10791 if (userId == UserHandle.USER_ALL) { 10792 users = sUserManager.getUserIds(); 10793 } else { 10794 users = new int[]{userId}; 10795 } 10796 for (int i = 0; i < users.length; ++i) { 10797 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 10798 return true; 10799 } 10800 } 10801 } 10802 } catch (RemoteException e) { 10803 } 10804 return false; 10805 } 10806 10807 /** 10808 * This method is an internal method that could be get invoked either 10809 * to delete an installed package or to clean up a failed installation. 10810 * After deleting an installed package, a broadcast is sent to notify any 10811 * listeners that the package has been installed. For cleaning up a failed 10812 * installation, the broadcast is not necessary since the package's 10813 * installation wouldn't have sent the initial broadcast either 10814 * The key steps in deleting a package are 10815 * deleting the package information in internal structures like mPackages, 10816 * deleting the packages base directories through installd 10817 * updating mSettings to reflect current status 10818 * persisting settings for later use 10819 * sending a broadcast if necessary 10820 */ 10821 private int deletePackageX(String packageName, int userId, int flags) { 10822 final PackageRemovedInfo info = new PackageRemovedInfo(); 10823 final boolean res; 10824 10825 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 10826 ? UserHandle.ALL : new UserHandle(userId); 10827 10828 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 10829 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10830 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10831 } 10832 10833 boolean removedForAllUsers = false; 10834 boolean systemUpdate = false; 10835 10836 // for the uninstall-updates case and restricted profiles, remember the per- 10837 // userhandle installed state 10838 int[] allUsers; 10839 boolean[] perUserInstalled; 10840 synchronized (mPackages) { 10841 PackageSetting ps = mSettings.mPackages.get(packageName); 10842 allUsers = sUserManager.getUserIds(); 10843 perUserInstalled = new boolean[allUsers.length]; 10844 for (int i = 0; i < allUsers.length; i++) { 10845 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10846 } 10847 } 10848 10849 synchronized (mInstallLock) { 10850 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10851 res = deletePackageLI(packageName, removeForUser, 10852 true, allUsers, perUserInstalled, 10853 flags | REMOVE_CHATTY, info, true); 10854 systemUpdate = info.isRemovedPackageSystemUpdate; 10855 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10856 removedForAllUsers = true; 10857 } 10858 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10859 + " removedForAllUsers=" + removedForAllUsers); 10860 } 10861 10862 if (res) { 10863 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10864 10865 // If the removed package was a system update, the old system package 10866 // was re-enabled; we need to broadcast this information 10867 if (systemUpdate) { 10868 Bundle extras = new Bundle(1); 10869 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10870 ? info.removedAppId : info.uid); 10871 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10872 10873 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10874 extras, null, null, null); 10875 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10876 extras, null, null, null); 10877 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10878 null, packageName, null, null); 10879 } 10880 } 10881 // Force a gc here. 10882 Runtime.getRuntime().gc(); 10883 // Delete the resources here after sending the broadcast to let 10884 // other processes clean up before deleting resources. 10885 if (info.args != null) { 10886 synchronized (mInstallLock) { 10887 info.args.doPostDeleteLI(true); 10888 } 10889 } 10890 10891 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10892 } 10893 10894 static class PackageRemovedInfo { 10895 String removedPackage; 10896 int uid = -1; 10897 int removedAppId = -1; 10898 int[] removedUsers = null; 10899 boolean isRemovedPackageSystemUpdate = false; 10900 // Clean up resources deleted packages. 10901 InstallArgs args = null; 10902 10903 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10904 Bundle extras = new Bundle(1); 10905 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10906 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10907 if (replacing) { 10908 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10909 } 10910 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10911 if (removedPackage != null) { 10912 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10913 extras, null, null, removedUsers); 10914 if (fullRemove && !replacing) { 10915 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10916 extras, null, null, removedUsers); 10917 } 10918 } 10919 if (removedAppId >= 0) { 10920 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10921 removedUsers); 10922 } 10923 } 10924 } 10925 10926 /* 10927 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10928 * flag is not set, the data directory is removed as well. 10929 * make sure this flag is set for partially installed apps. If not its meaningless to 10930 * delete a partially installed application. 10931 */ 10932 private void removePackageDataLI(PackageSetting ps, 10933 int[] allUserHandles, boolean[] perUserInstalled, 10934 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10935 String packageName = ps.name; 10936 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10937 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10938 // Retrieve object to delete permissions for shared user later on 10939 final PackageSetting deletedPs; 10940 // reader 10941 synchronized (mPackages) { 10942 deletedPs = mSettings.mPackages.get(packageName); 10943 if (outInfo != null) { 10944 outInfo.removedPackage = packageName; 10945 outInfo.removedUsers = deletedPs != null 10946 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10947 : null; 10948 } 10949 } 10950 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10951 removeDataDirsLI(packageName); 10952 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10953 } 10954 // writer 10955 synchronized (mPackages) { 10956 if (deletedPs != null) { 10957 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10958 if (outInfo != null) { 10959 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10960 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10961 } 10962 if (deletedPs != null) { 10963 updatePermissionsLPw(deletedPs.name, null, 0); 10964 if (deletedPs.sharedUser != null) { 10965 // remove permissions associated with package 10966 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10967 } 10968 } 10969 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10970 } 10971 // make sure to preserve per-user disabled state if this removal was just 10972 // a downgrade of a system app to the factory package 10973 if (allUserHandles != null && perUserInstalled != null) { 10974 if (DEBUG_REMOVE) { 10975 Slog.d(TAG, "Propagating install state across downgrade"); 10976 } 10977 for (int i = 0; i < allUserHandles.length; i++) { 10978 if (DEBUG_REMOVE) { 10979 Slog.d(TAG, " user " + allUserHandles[i] 10980 + " => " + perUserInstalled[i]); 10981 } 10982 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10983 } 10984 } 10985 } 10986 // can downgrade to reader 10987 if (writeSettings) { 10988 // Save settings now 10989 mSettings.writeLPr(); 10990 } 10991 } 10992 if (outInfo != null) { 10993 // A user ID was deleted here. Go through all users and remove it 10994 // from KeyStore. 10995 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10996 } 10997 } 10998 10999 static boolean locationIsPrivileged(File path) { 11000 try { 11001 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11002 .getCanonicalPath(); 11003 return path.getCanonicalPath().startsWith(privilegedAppDir); 11004 } catch (IOException e) { 11005 Slog.e(TAG, "Unable to access code path " + path); 11006 } 11007 return false; 11008 } 11009 11010 /* 11011 * Tries to delete system package. 11012 */ 11013 private boolean deleteSystemPackageLI(PackageSetting newPs, 11014 int[] allUserHandles, boolean[] perUserInstalled, 11015 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11016 final boolean applyUserRestrictions 11017 = (allUserHandles != null) && (perUserInstalled != null); 11018 PackageSetting disabledPs = null; 11019 // Confirm if the system package has been updated 11020 // An updated system app can be deleted. This will also have to restore 11021 // the system pkg from system partition 11022 // reader 11023 synchronized (mPackages) { 11024 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11025 } 11026 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11027 + " disabledPs=" + disabledPs); 11028 if (disabledPs == null) { 11029 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11030 return false; 11031 } else if (DEBUG_REMOVE) { 11032 Slog.d(TAG, "Deleting system pkg from data partition"); 11033 } 11034 if (DEBUG_REMOVE) { 11035 if (applyUserRestrictions) { 11036 Slog.d(TAG, "Remembering install states:"); 11037 for (int i = 0; i < allUserHandles.length; i++) { 11038 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11039 } 11040 } 11041 } 11042 // Delete the updated package 11043 outInfo.isRemovedPackageSystemUpdate = true; 11044 if (disabledPs.versionCode < newPs.versionCode) { 11045 // Delete data for downgrades 11046 flags &= ~PackageManager.DELETE_KEEP_DATA; 11047 } else { 11048 // Preserve data by setting flag 11049 flags |= PackageManager.DELETE_KEEP_DATA; 11050 } 11051 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11052 allUserHandles, perUserInstalled, outInfo, writeSettings); 11053 if (!ret) { 11054 return false; 11055 } 11056 // writer 11057 synchronized (mPackages) { 11058 // Reinstate the old system package 11059 mSettings.enableSystemPackageLPw(newPs.name); 11060 // Remove any native libraries from the upgraded package. 11061 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11062 } 11063 // Install the system package 11064 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11065 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11066 if (locationIsPrivileged(disabledPs.codePath)) { 11067 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11068 } 11069 11070 final PackageParser.Package newPkg; 11071 try { 11072 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11073 } catch (PackageManagerException e) { 11074 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11075 return false; 11076 } 11077 11078 // writer 11079 synchronized (mPackages) { 11080 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11081 updatePermissionsLPw(newPkg.packageName, newPkg, 11082 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 11083 if (applyUserRestrictions) { 11084 if (DEBUG_REMOVE) { 11085 Slog.d(TAG, "Propagating install state across reinstall"); 11086 } 11087 for (int i = 0; i < allUserHandles.length; i++) { 11088 if (DEBUG_REMOVE) { 11089 Slog.d(TAG, " user " + allUserHandles[i] 11090 + " => " + perUserInstalled[i]); 11091 } 11092 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11093 } 11094 // Regardless of writeSettings we need to ensure that this restriction 11095 // state propagation is persisted 11096 mSettings.writeAllUsersPackageRestrictionsLPr(); 11097 } 11098 // can downgrade to reader here 11099 if (writeSettings) { 11100 mSettings.writeLPr(); 11101 } 11102 } 11103 return true; 11104 } 11105 11106 private boolean deleteInstalledPackageLI(PackageSetting ps, 11107 boolean deleteCodeAndResources, int flags, 11108 int[] allUserHandles, boolean[] perUserInstalled, 11109 PackageRemovedInfo outInfo, boolean writeSettings) { 11110 if (outInfo != null) { 11111 outInfo.uid = ps.appId; 11112 } 11113 11114 // Delete package data from internal structures and also remove data if flag is set 11115 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11116 11117 // Delete application code and resources 11118 if (deleteCodeAndResources && (outInfo != null)) { 11119 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11120 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11121 getAppDexInstructionSets(ps)); 11122 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11123 } 11124 return true; 11125 } 11126 11127 @Override 11128 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11129 int userId) { 11130 mContext.enforceCallingOrSelfPermission( 11131 android.Manifest.permission.DELETE_PACKAGES, null); 11132 synchronized (mPackages) { 11133 PackageSetting ps = mSettings.mPackages.get(packageName); 11134 if (ps == null) { 11135 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11136 return false; 11137 } 11138 if (!ps.getInstalled(userId)) { 11139 // Can't block uninstall for an app that is not installed or enabled. 11140 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11141 return false; 11142 } 11143 ps.setBlockUninstall(blockUninstall, userId); 11144 mSettings.writePackageRestrictionsLPr(userId); 11145 } 11146 return true; 11147 } 11148 11149 @Override 11150 public boolean getBlockUninstallForUser(String packageName, int userId) { 11151 synchronized (mPackages) { 11152 PackageSetting ps = mSettings.mPackages.get(packageName); 11153 if (ps == null) { 11154 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11155 return false; 11156 } 11157 return ps.getBlockUninstall(userId); 11158 } 11159 } 11160 11161 /* 11162 * This method handles package deletion in general 11163 */ 11164 private boolean deletePackageLI(String packageName, UserHandle user, 11165 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11166 int flags, PackageRemovedInfo outInfo, 11167 boolean writeSettings) { 11168 if (packageName == null) { 11169 Slog.w(TAG, "Attempt to delete null packageName."); 11170 return false; 11171 } 11172 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11173 PackageSetting ps; 11174 boolean dataOnly = false; 11175 int removeUser = -1; 11176 int appId = -1; 11177 synchronized (mPackages) { 11178 ps = mSettings.mPackages.get(packageName); 11179 if (ps == null) { 11180 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11181 return false; 11182 } 11183 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11184 && user.getIdentifier() != UserHandle.USER_ALL) { 11185 // The caller is asking that the package only be deleted for a single 11186 // user. To do this, we just mark its uninstalled state and delete 11187 // its data. If this is a system app, we only allow this to happen if 11188 // they have set the special DELETE_SYSTEM_APP which requests different 11189 // semantics than normal for uninstalling system apps. 11190 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11191 ps.setUserState(user.getIdentifier(), 11192 COMPONENT_ENABLED_STATE_DEFAULT, 11193 false, //installed 11194 true, //stopped 11195 true, //notLaunched 11196 false, //hidden 11197 null, null, null, 11198 false // blockUninstall 11199 ); 11200 if (!isSystemApp(ps)) { 11201 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11202 // Other user still have this package installed, so all 11203 // we need to do is clear this user's data and save that 11204 // it is uninstalled. 11205 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11206 removeUser = user.getIdentifier(); 11207 appId = ps.appId; 11208 mSettings.writePackageRestrictionsLPr(removeUser); 11209 } else { 11210 // We need to set it back to 'installed' so the uninstall 11211 // broadcasts will be sent correctly. 11212 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11213 ps.setInstalled(true, user.getIdentifier()); 11214 } 11215 } else { 11216 // This is a system app, so we assume that the 11217 // other users still have this package installed, so all 11218 // we need to do is clear this user's data and save that 11219 // it is uninstalled. 11220 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11221 removeUser = user.getIdentifier(); 11222 appId = ps.appId; 11223 mSettings.writePackageRestrictionsLPr(removeUser); 11224 } 11225 } 11226 } 11227 11228 if (removeUser >= 0) { 11229 // From above, we determined that we are deleting this only 11230 // for a single user. Continue the work here. 11231 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11232 if (outInfo != null) { 11233 outInfo.removedPackage = packageName; 11234 outInfo.removedAppId = appId; 11235 outInfo.removedUsers = new int[] {removeUser}; 11236 } 11237 mInstaller.clearUserData(packageName, removeUser); 11238 removeKeystoreDataIfNeeded(removeUser, appId); 11239 schedulePackageCleaning(packageName, removeUser, false); 11240 return true; 11241 } 11242 11243 if (dataOnly) { 11244 // Delete application data first 11245 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11246 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11247 return true; 11248 } 11249 11250 boolean ret = false; 11251 if (isSystemApp(ps)) { 11252 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11253 // When an updated system application is deleted we delete the existing resources as well and 11254 // fall back to existing code in system partition 11255 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11256 flags, outInfo, writeSettings); 11257 } else { 11258 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11259 // Kill application pre-emptively especially for apps on sd. 11260 killApplication(packageName, ps.appId, "uninstall pkg"); 11261 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11262 allUserHandles, perUserInstalled, 11263 outInfo, writeSettings); 11264 } 11265 11266 return ret; 11267 } 11268 11269 private final class ClearStorageConnection implements ServiceConnection { 11270 IMediaContainerService mContainerService; 11271 11272 @Override 11273 public void onServiceConnected(ComponentName name, IBinder service) { 11274 synchronized (this) { 11275 mContainerService = IMediaContainerService.Stub.asInterface(service); 11276 notifyAll(); 11277 } 11278 } 11279 11280 @Override 11281 public void onServiceDisconnected(ComponentName name) { 11282 } 11283 } 11284 11285 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11286 final boolean mounted; 11287 if (Environment.isExternalStorageEmulated()) { 11288 mounted = true; 11289 } else { 11290 final String status = Environment.getExternalStorageState(); 11291 11292 mounted = status.equals(Environment.MEDIA_MOUNTED) 11293 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11294 } 11295 11296 if (!mounted) { 11297 return; 11298 } 11299 11300 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11301 int[] users; 11302 if (userId == UserHandle.USER_ALL) { 11303 users = sUserManager.getUserIds(); 11304 } else { 11305 users = new int[] { userId }; 11306 } 11307 final ClearStorageConnection conn = new ClearStorageConnection(); 11308 if (mContext.bindServiceAsUser( 11309 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11310 try { 11311 for (int curUser : users) { 11312 long timeout = SystemClock.uptimeMillis() + 5000; 11313 synchronized (conn) { 11314 long now = SystemClock.uptimeMillis(); 11315 while (conn.mContainerService == null && now < timeout) { 11316 try { 11317 conn.wait(timeout - now); 11318 } catch (InterruptedException e) { 11319 } 11320 } 11321 } 11322 if (conn.mContainerService == null) { 11323 return; 11324 } 11325 11326 final UserEnvironment userEnv = new UserEnvironment(curUser); 11327 clearDirectory(conn.mContainerService, 11328 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11329 if (allData) { 11330 clearDirectory(conn.mContainerService, 11331 userEnv.buildExternalStorageAppDataDirs(packageName)); 11332 clearDirectory(conn.mContainerService, 11333 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11334 } 11335 } 11336 } finally { 11337 mContext.unbindService(conn); 11338 } 11339 } 11340 } 11341 11342 @Override 11343 public void clearApplicationUserData(final String packageName, 11344 final IPackageDataObserver observer, final int userId) { 11345 mContext.enforceCallingOrSelfPermission( 11346 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11347 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11348 // Queue up an async operation since the package deletion may take a little while. 11349 mHandler.post(new Runnable() { 11350 public void run() { 11351 mHandler.removeCallbacks(this); 11352 final boolean succeeded; 11353 synchronized (mInstallLock) { 11354 succeeded = clearApplicationUserDataLI(packageName, userId); 11355 } 11356 clearExternalStorageDataSync(packageName, userId, true); 11357 if (succeeded) { 11358 // invoke DeviceStorageMonitor's update method to clear any notifications 11359 DeviceStorageMonitorInternal 11360 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11361 if (dsm != null) { 11362 dsm.checkMemory(); 11363 } 11364 } 11365 if(observer != null) { 11366 try { 11367 observer.onRemoveCompleted(packageName, succeeded); 11368 } catch (RemoteException e) { 11369 Log.i(TAG, "Observer no longer exists."); 11370 } 11371 } //end if observer 11372 } //end run 11373 }); 11374 } 11375 11376 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11377 if (packageName == null) { 11378 Slog.w(TAG, "Attempt to delete null packageName."); 11379 return false; 11380 } 11381 11382 // Try finding details about the requested package 11383 PackageParser.Package pkg; 11384 synchronized (mPackages) { 11385 pkg = mPackages.get(packageName); 11386 if (pkg == null) { 11387 final PackageSetting ps = mSettings.mPackages.get(packageName); 11388 if (ps != null) { 11389 pkg = ps.pkg; 11390 } 11391 } 11392 } 11393 11394 if (pkg == null) { 11395 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11396 } 11397 11398 // Always delete data directories for package, even if we found no other 11399 // record of app. This helps users recover from UID mismatches without 11400 // resorting to a full data wipe. 11401 int retCode = mInstaller.clearUserData(packageName, userId); 11402 if (retCode < 0) { 11403 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 11404 return false; 11405 } 11406 11407 if (pkg == null) { 11408 return false; 11409 } 11410 11411 if (pkg != null && pkg.applicationInfo != null) { 11412 final int appId = pkg.applicationInfo.uid; 11413 removeKeystoreDataIfNeeded(userId, appId); 11414 } 11415 11416 // Create a native library symlink only if we have native libraries 11417 // and if the native libraries are 32 bit libraries. We do not provide 11418 // this symlink for 64 bit libraries. 11419 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11420 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11421 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11422 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11423 Slog.w(TAG, "Failed linking native library dir"); 11424 return false; 11425 } 11426 } 11427 11428 return true; 11429 } 11430 11431 /** 11432 * Remove entries from the keystore daemon. Will only remove it if the 11433 * {@code appId} is valid. 11434 */ 11435 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11436 if (appId < 0) { 11437 return; 11438 } 11439 11440 final KeyStore keyStore = KeyStore.getInstance(); 11441 if (keyStore != null) { 11442 if (userId == UserHandle.USER_ALL) { 11443 for (final int individual : sUserManager.getUserIds()) { 11444 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11445 } 11446 } else { 11447 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11448 } 11449 } else { 11450 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11451 } 11452 } 11453 11454 @Override 11455 public void deleteApplicationCacheFiles(final String packageName, 11456 final IPackageDataObserver observer) { 11457 mContext.enforceCallingOrSelfPermission( 11458 android.Manifest.permission.DELETE_CACHE_FILES, null); 11459 // Queue up an async operation since the package deletion may take a little while. 11460 final int userId = UserHandle.getCallingUserId(); 11461 mHandler.post(new Runnable() { 11462 public void run() { 11463 mHandler.removeCallbacks(this); 11464 final boolean succeded; 11465 synchronized (mInstallLock) { 11466 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11467 } 11468 clearExternalStorageDataSync(packageName, userId, false); 11469 if(observer != null) { 11470 try { 11471 observer.onRemoveCompleted(packageName, succeded); 11472 } catch (RemoteException e) { 11473 Log.i(TAG, "Observer no longer exists."); 11474 } 11475 } //end if observer 11476 } //end run 11477 }); 11478 } 11479 11480 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11481 if (packageName == null) { 11482 Slog.w(TAG, "Attempt to delete null packageName."); 11483 return false; 11484 } 11485 PackageParser.Package p; 11486 synchronized (mPackages) { 11487 p = mPackages.get(packageName); 11488 } 11489 if (p == null) { 11490 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11491 return false; 11492 } 11493 final ApplicationInfo applicationInfo = p.applicationInfo; 11494 if (applicationInfo == null) { 11495 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11496 return false; 11497 } 11498 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11499 if (retCode < 0) { 11500 Slog.w(TAG, "Couldn't remove cache files for package: " 11501 + packageName + " u" + userId); 11502 return false; 11503 } 11504 return true; 11505 } 11506 11507 @Override 11508 public void getPackageSizeInfo(final String packageName, int userHandle, 11509 final IPackageStatsObserver observer) { 11510 mContext.enforceCallingOrSelfPermission( 11511 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11512 if (packageName == null) { 11513 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11514 } 11515 11516 PackageStats stats = new PackageStats(packageName, userHandle); 11517 11518 /* 11519 * Queue up an async operation since the package measurement may take a 11520 * little while. 11521 */ 11522 Message msg = mHandler.obtainMessage(INIT_COPY); 11523 msg.obj = new MeasureParams(stats, observer); 11524 mHandler.sendMessage(msg); 11525 } 11526 11527 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11528 PackageStats pStats) { 11529 if (packageName == null) { 11530 Slog.w(TAG, "Attempt to get size of null packageName."); 11531 return false; 11532 } 11533 PackageParser.Package p; 11534 boolean dataOnly = false; 11535 String libDirRoot = null; 11536 String asecPath = null; 11537 PackageSetting ps = null; 11538 synchronized (mPackages) { 11539 p = mPackages.get(packageName); 11540 ps = mSettings.mPackages.get(packageName); 11541 if(p == null) { 11542 dataOnly = true; 11543 if((ps == null) || (ps.pkg == null)) { 11544 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11545 return false; 11546 } 11547 p = ps.pkg; 11548 } 11549 if (ps != null) { 11550 libDirRoot = ps.legacyNativeLibraryPathString; 11551 } 11552 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11553 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11554 if (secureContainerId != null) { 11555 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11556 } 11557 } 11558 } 11559 String publicSrcDir = null; 11560 if(!dataOnly) { 11561 final ApplicationInfo applicationInfo = p.applicationInfo; 11562 if (applicationInfo == null) { 11563 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11564 return false; 11565 } 11566 if (isForwardLocked(p)) { 11567 publicSrcDir = applicationInfo.getBaseResourcePath(); 11568 } 11569 } 11570 // TODO: extend to measure size of split APKs 11571 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11572 // not just the first level. 11573 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11574 // just the primary. 11575 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11576 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11577 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11578 if (res < 0) { 11579 return false; 11580 } 11581 11582 // Fix-up for forward-locked applications in ASEC containers. 11583 if (!isExternal(p)) { 11584 pStats.codeSize += pStats.externalCodeSize; 11585 pStats.externalCodeSize = 0L; 11586 } 11587 11588 return true; 11589 } 11590 11591 11592 @Override 11593 public void addPackageToPreferred(String packageName) { 11594 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11595 } 11596 11597 @Override 11598 public void removePackageFromPreferred(String packageName) { 11599 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11600 } 11601 11602 @Override 11603 public List<PackageInfo> getPreferredPackages(int flags) { 11604 return new ArrayList<PackageInfo>(); 11605 } 11606 11607 private int getUidTargetSdkVersionLockedLPr(int uid) { 11608 Object obj = mSettings.getUserIdLPr(uid); 11609 if (obj instanceof SharedUserSetting) { 11610 final SharedUserSetting sus = (SharedUserSetting) obj; 11611 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11612 final Iterator<PackageSetting> it = sus.packages.iterator(); 11613 while (it.hasNext()) { 11614 final PackageSetting ps = it.next(); 11615 if (ps.pkg != null) { 11616 int v = ps.pkg.applicationInfo.targetSdkVersion; 11617 if (v < vers) vers = v; 11618 } 11619 } 11620 return vers; 11621 } else if (obj instanceof PackageSetting) { 11622 final PackageSetting ps = (PackageSetting) obj; 11623 if (ps.pkg != null) { 11624 return ps.pkg.applicationInfo.targetSdkVersion; 11625 } 11626 } 11627 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11628 } 11629 11630 @Override 11631 public void addPreferredActivity(IntentFilter filter, int match, 11632 ComponentName[] set, ComponentName activity, int userId) { 11633 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11634 "Adding preferred"); 11635 } 11636 11637 private void addPreferredActivityInternal(IntentFilter filter, int match, 11638 ComponentName[] set, ComponentName activity, boolean always, int userId, 11639 String opname) { 11640 // writer 11641 int callingUid = Binder.getCallingUid(); 11642 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 11643 if (filter.countActions() == 0) { 11644 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11645 return; 11646 } 11647 synchronized (mPackages) { 11648 if (mContext.checkCallingOrSelfPermission( 11649 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11650 != PackageManager.PERMISSION_GRANTED) { 11651 if (getUidTargetSdkVersionLockedLPr(callingUid) 11652 < Build.VERSION_CODES.FROYO) { 11653 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11654 + callingUid); 11655 return; 11656 } 11657 mContext.enforceCallingOrSelfPermission( 11658 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11659 } 11660 11661 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11662 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11663 + userId + ":"); 11664 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11665 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11666 scheduleWritePackageRestrictionsLocked(userId); 11667 } 11668 } 11669 11670 @Override 11671 public void replacePreferredActivity(IntentFilter filter, int match, 11672 ComponentName[] set, ComponentName activity, int userId) { 11673 if (filter.countActions() != 1) { 11674 throw new IllegalArgumentException( 11675 "replacePreferredActivity expects filter to have only 1 action."); 11676 } 11677 if (filter.countDataAuthorities() != 0 11678 || filter.countDataPaths() != 0 11679 || filter.countDataSchemes() > 1 11680 || filter.countDataTypes() != 0) { 11681 throw new IllegalArgumentException( 11682 "replacePreferredActivity expects filter to have no data authorities, " + 11683 "paths, or types; and at most one scheme."); 11684 } 11685 11686 final int callingUid = Binder.getCallingUid(); 11687 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 11688 synchronized (mPackages) { 11689 if (mContext.checkCallingOrSelfPermission( 11690 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11691 != PackageManager.PERMISSION_GRANTED) { 11692 if (getUidTargetSdkVersionLockedLPr(callingUid) 11693 < Build.VERSION_CODES.FROYO) { 11694 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11695 + Binder.getCallingUid()); 11696 return; 11697 } 11698 mContext.enforceCallingOrSelfPermission( 11699 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11700 } 11701 11702 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11703 if (pir != null) { 11704 // Get all of the existing entries that exactly match this filter. 11705 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11706 if (existing != null && existing.size() == 1) { 11707 PreferredActivity cur = existing.get(0); 11708 if (DEBUG_PREFERRED) { 11709 Slog.i(TAG, "Checking replace of preferred:"); 11710 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11711 if (!cur.mPref.mAlways) { 11712 Slog.i(TAG, " -- CUR; not mAlways!"); 11713 } else { 11714 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11715 Slog.i(TAG, " -- CUR: mSet=" 11716 + Arrays.toString(cur.mPref.mSetComponents)); 11717 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11718 Slog.i(TAG, " -- NEW: mMatch=" 11719 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11720 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11721 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11722 } 11723 } 11724 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11725 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11726 && cur.mPref.sameSet(set)) { 11727 // Setting the preferred activity to what it happens to be already 11728 if (DEBUG_PREFERRED) { 11729 Slog.i(TAG, "Replacing with same preferred activity " 11730 + cur.mPref.mShortComponent + " for user " 11731 + userId + ":"); 11732 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11733 } 11734 return; 11735 } 11736 } 11737 11738 if (existing != null) { 11739 if (DEBUG_PREFERRED) { 11740 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11741 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11742 } 11743 for (int i = 0; i < existing.size(); i++) { 11744 PreferredActivity pa = existing.get(i); 11745 if (DEBUG_PREFERRED) { 11746 Slog.i(TAG, "Removing existing preferred activity " 11747 + pa.mPref.mComponent + ":"); 11748 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11749 } 11750 pir.removeFilter(pa); 11751 } 11752 } 11753 } 11754 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11755 "Replacing preferred"); 11756 } 11757 } 11758 11759 @Override 11760 public void clearPackagePreferredActivities(String packageName) { 11761 final int uid = Binder.getCallingUid(); 11762 // writer 11763 synchronized (mPackages) { 11764 PackageParser.Package pkg = mPackages.get(packageName); 11765 if (pkg == null || pkg.applicationInfo.uid != uid) { 11766 if (mContext.checkCallingOrSelfPermission( 11767 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11768 != PackageManager.PERMISSION_GRANTED) { 11769 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11770 < Build.VERSION_CODES.FROYO) { 11771 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11772 + Binder.getCallingUid()); 11773 return; 11774 } 11775 mContext.enforceCallingOrSelfPermission( 11776 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11777 } 11778 } 11779 11780 int user = UserHandle.getCallingUserId(); 11781 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11782 scheduleWritePackageRestrictionsLocked(user); 11783 } 11784 } 11785 } 11786 11787 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11788 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11789 ArrayList<PreferredActivity> removed = null; 11790 boolean changed = false; 11791 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11792 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11793 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11794 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11795 continue; 11796 } 11797 Iterator<PreferredActivity> it = pir.filterIterator(); 11798 while (it.hasNext()) { 11799 PreferredActivity pa = it.next(); 11800 // Mark entry for removal only if it matches the package name 11801 // and the entry is of type "always". 11802 if (packageName == null || 11803 (pa.mPref.mComponent.getPackageName().equals(packageName) 11804 && pa.mPref.mAlways)) { 11805 if (removed == null) { 11806 removed = new ArrayList<PreferredActivity>(); 11807 } 11808 removed.add(pa); 11809 } 11810 } 11811 if (removed != null) { 11812 for (int j=0; j<removed.size(); j++) { 11813 PreferredActivity pa = removed.get(j); 11814 pir.removeFilter(pa); 11815 } 11816 changed = true; 11817 } 11818 } 11819 return changed; 11820 } 11821 11822 @Override 11823 public void resetPreferredActivities(int userId) { 11824 /* TODO: Actually use userId. Why is it being passed in? */ 11825 mContext.enforceCallingOrSelfPermission( 11826 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11827 // writer 11828 synchronized (mPackages) { 11829 int user = UserHandle.getCallingUserId(); 11830 clearPackagePreferredActivitiesLPw(null, user); 11831 mSettings.readDefaultPreferredAppsLPw(this, user); 11832 scheduleWritePackageRestrictionsLocked(user); 11833 } 11834 } 11835 11836 @Override 11837 public int getPreferredActivities(List<IntentFilter> outFilters, 11838 List<ComponentName> outActivities, String packageName) { 11839 11840 int num = 0; 11841 final int userId = UserHandle.getCallingUserId(); 11842 // reader 11843 synchronized (mPackages) { 11844 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11845 if (pir != null) { 11846 final Iterator<PreferredActivity> it = pir.filterIterator(); 11847 while (it.hasNext()) { 11848 final PreferredActivity pa = it.next(); 11849 if (packageName == null 11850 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11851 && pa.mPref.mAlways)) { 11852 if (outFilters != null) { 11853 outFilters.add(new IntentFilter(pa)); 11854 } 11855 if (outActivities != null) { 11856 outActivities.add(pa.mPref.mComponent); 11857 } 11858 } 11859 } 11860 } 11861 } 11862 11863 return num; 11864 } 11865 11866 @Override 11867 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11868 int userId) { 11869 int callingUid = Binder.getCallingUid(); 11870 if (callingUid != Process.SYSTEM_UID) { 11871 throw new SecurityException( 11872 "addPersistentPreferredActivity can only be run by the system"); 11873 } 11874 if (filter.countActions() == 0) { 11875 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11876 return; 11877 } 11878 synchronized (mPackages) { 11879 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11880 " :"); 11881 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11882 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11883 new PersistentPreferredActivity(filter, activity)); 11884 scheduleWritePackageRestrictionsLocked(userId); 11885 } 11886 } 11887 11888 @Override 11889 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11890 int callingUid = Binder.getCallingUid(); 11891 if (callingUid != Process.SYSTEM_UID) { 11892 throw new SecurityException( 11893 "clearPackagePersistentPreferredActivities can only be run by the system"); 11894 } 11895 ArrayList<PersistentPreferredActivity> removed = null; 11896 boolean changed = false; 11897 synchronized (mPackages) { 11898 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11899 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11900 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11901 .valueAt(i); 11902 if (userId != thisUserId) { 11903 continue; 11904 } 11905 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11906 while (it.hasNext()) { 11907 PersistentPreferredActivity ppa = it.next(); 11908 // Mark entry for removal only if it matches the package name. 11909 if (ppa.mComponent.getPackageName().equals(packageName)) { 11910 if (removed == null) { 11911 removed = new ArrayList<PersistentPreferredActivity>(); 11912 } 11913 removed.add(ppa); 11914 } 11915 } 11916 if (removed != null) { 11917 for (int j=0; j<removed.size(); j++) { 11918 PersistentPreferredActivity ppa = removed.get(j); 11919 ppir.removeFilter(ppa); 11920 } 11921 changed = true; 11922 } 11923 } 11924 11925 if (changed) { 11926 scheduleWritePackageRestrictionsLocked(userId); 11927 } 11928 } 11929 } 11930 11931 @Override 11932 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11933 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11934 mContext.enforceCallingOrSelfPermission( 11935 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11936 int callingUid = Binder.getCallingUid(); 11937 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11938 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11939 if (intentFilter.countActions() == 0) { 11940 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11941 return; 11942 } 11943 synchronized (mPackages) { 11944 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 11945 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11946 CrossProfileIntentResolver resolver = 11947 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11948 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 11949 // We have all those whose filter is equal. Now checking if the rest is equal as well. 11950 if (existing != null) { 11951 int size = existing.size(); 11952 for (int i = 0; i < size; i++) { 11953 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 11954 return; 11955 } 11956 } 11957 } 11958 resolver.addFilter(newFilter); 11959 scheduleWritePackageRestrictionsLocked(sourceUserId); 11960 } 11961 } 11962 11963 @Override 11964 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11965 int ownerUserId) { 11966 mContext.enforceCallingOrSelfPermission( 11967 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11968 int callingUid = Binder.getCallingUid(); 11969 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11970 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11971 int callingUserId = UserHandle.getUserId(callingUid); 11972 synchronized (mPackages) { 11973 CrossProfileIntentResolver resolver = 11974 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11975 ArraySet<CrossProfileIntentFilter> set = 11976 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 11977 for (CrossProfileIntentFilter filter : set) { 11978 if (filter.getOwnerPackage().equals(ownerPackage) 11979 && filter.getOwnerUserId() == callingUserId) { 11980 resolver.removeFilter(filter); 11981 } 11982 } 11983 scheduleWritePackageRestrictionsLocked(sourceUserId); 11984 } 11985 } 11986 11987 // Enforcing that callingUid is owning pkg on userId 11988 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11989 // The system owns everything. 11990 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11991 return; 11992 } 11993 int callingUserId = UserHandle.getUserId(callingUid); 11994 if (callingUserId != userId) { 11995 throw new SecurityException("calling uid " + callingUid 11996 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11997 + callingUserId); 11998 } 11999 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 12000 if (pi == null) { 12001 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 12002 + callingUserId); 12003 } 12004 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 12005 throw new SecurityException("Calling uid " + callingUid 12006 + " does not own package " + pkg); 12007 } 12008 } 12009 12010 @Override 12011 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 12012 Intent intent = new Intent(Intent.ACTION_MAIN); 12013 intent.addCategory(Intent.CATEGORY_HOME); 12014 12015 final int callingUserId = UserHandle.getCallingUserId(); 12016 List<ResolveInfo> list = queryIntentActivities(intent, null, 12017 PackageManager.GET_META_DATA, callingUserId); 12018 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 12019 true, false, false, callingUserId); 12020 12021 allHomeCandidates.clear(); 12022 if (list != null) { 12023 for (ResolveInfo ri : list) { 12024 allHomeCandidates.add(ri); 12025 } 12026 } 12027 return (preferred == null || preferred.activityInfo == null) 12028 ? null 12029 : new ComponentName(preferred.activityInfo.packageName, 12030 preferred.activityInfo.name); 12031 } 12032 12033 @Override 12034 public void setApplicationEnabledSetting(String appPackageName, 12035 int newState, int flags, int userId, String callingPackage) { 12036 if (!sUserManager.exists(userId)) return; 12037 if (callingPackage == null) { 12038 callingPackage = Integer.toString(Binder.getCallingUid()); 12039 } 12040 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 12041 } 12042 12043 @Override 12044 public void setComponentEnabledSetting(ComponentName componentName, 12045 int newState, int flags, int userId) { 12046 if (!sUserManager.exists(userId)) return; 12047 setEnabledSetting(componentName.getPackageName(), 12048 componentName.getClassName(), newState, flags, userId, null); 12049 } 12050 12051 private void setEnabledSetting(final String packageName, String className, int newState, 12052 final int flags, int userId, String callingPackage) { 12053 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 12054 || newState == COMPONENT_ENABLED_STATE_ENABLED 12055 || newState == COMPONENT_ENABLED_STATE_DISABLED 12056 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 12057 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 12058 throw new IllegalArgumentException("Invalid new component state: " 12059 + newState); 12060 } 12061 PackageSetting pkgSetting; 12062 final int uid = Binder.getCallingUid(); 12063 final int permission = mContext.checkCallingOrSelfPermission( 12064 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12065 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 12066 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12067 boolean sendNow = false; 12068 boolean isApp = (className == null); 12069 String componentName = isApp ? packageName : className; 12070 int packageUid = -1; 12071 ArrayList<String> components; 12072 12073 // writer 12074 synchronized (mPackages) { 12075 pkgSetting = mSettings.mPackages.get(packageName); 12076 if (pkgSetting == null) { 12077 if (className == null) { 12078 throw new IllegalArgumentException( 12079 "Unknown package: " + packageName); 12080 } 12081 throw new IllegalArgumentException( 12082 "Unknown component: " + packageName 12083 + "/" + className); 12084 } 12085 // Allow root and verify that userId is not being specified by a different user 12086 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 12087 throw new SecurityException( 12088 "Permission Denial: attempt to change component state from pid=" 12089 + Binder.getCallingPid() 12090 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 12091 } 12092 if (className == null) { 12093 // We're dealing with an application/package level state change 12094 if (pkgSetting.getEnabled(userId) == newState) { 12095 // Nothing to do 12096 return; 12097 } 12098 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 12099 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 12100 // Don't care about who enables an app. 12101 callingPackage = null; 12102 } 12103 pkgSetting.setEnabled(newState, userId, callingPackage); 12104 // pkgSetting.pkg.mSetEnabled = newState; 12105 } else { 12106 // We're dealing with a component level state change 12107 // First, verify that this is a valid class name. 12108 PackageParser.Package pkg = pkgSetting.pkg; 12109 if (pkg == null || !pkg.hasComponentClassName(className)) { 12110 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 12111 throw new IllegalArgumentException("Component class " + className 12112 + " does not exist in " + packageName); 12113 } else { 12114 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 12115 + className + " does not exist in " + packageName); 12116 } 12117 } 12118 switch (newState) { 12119 case COMPONENT_ENABLED_STATE_ENABLED: 12120 if (!pkgSetting.enableComponentLPw(className, userId)) { 12121 return; 12122 } 12123 break; 12124 case COMPONENT_ENABLED_STATE_DISABLED: 12125 if (!pkgSetting.disableComponentLPw(className, userId)) { 12126 return; 12127 } 12128 break; 12129 case COMPONENT_ENABLED_STATE_DEFAULT: 12130 if (!pkgSetting.restoreComponentLPw(className, userId)) { 12131 return; 12132 } 12133 break; 12134 default: 12135 Slog.e(TAG, "Invalid new component state: " + newState); 12136 return; 12137 } 12138 } 12139 mSettings.writePackageRestrictionsLPr(userId); 12140 components = mPendingBroadcasts.get(userId, packageName); 12141 final boolean newPackage = components == null; 12142 if (newPackage) { 12143 components = new ArrayList<String>(); 12144 } 12145 if (!components.contains(componentName)) { 12146 components.add(componentName); 12147 } 12148 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 12149 sendNow = true; 12150 // Purge entry from pending broadcast list if another one exists already 12151 // since we are sending one right away. 12152 mPendingBroadcasts.remove(userId, packageName); 12153 } else { 12154 if (newPackage) { 12155 mPendingBroadcasts.put(userId, packageName, components); 12156 } 12157 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12158 // Schedule a message 12159 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12160 } 12161 } 12162 } 12163 12164 long callingId = Binder.clearCallingIdentity(); 12165 try { 12166 if (sendNow) { 12167 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12168 sendPackageChangedBroadcast(packageName, 12169 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12170 } 12171 } finally { 12172 Binder.restoreCallingIdentity(callingId); 12173 } 12174 } 12175 12176 private void sendPackageChangedBroadcast(String packageName, 12177 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12178 if (DEBUG_INSTALL) 12179 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12180 + componentNames); 12181 Bundle extras = new Bundle(4); 12182 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12183 String nameList[] = new String[componentNames.size()]; 12184 componentNames.toArray(nameList); 12185 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12186 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12187 extras.putInt(Intent.EXTRA_UID, packageUid); 12188 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12189 new int[] {UserHandle.getUserId(packageUid)}); 12190 } 12191 12192 @Override 12193 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12194 if (!sUserManager.exists(userId)) return; 12195 final int uid = Binder.getCallingUid(); 12196 final int permission = mContext.checkCallingOrSelfPermission( 12197 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12198 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12199 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 12200 // writer 12201 synchronized (mPackages) { 12202 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12203 uid, userId)) { 12204 scheduleWritePackageRestrictionsLocked(userId); 12205 } 12206 } 12207 } 12208 12209 @Override 12210 public String getInstallerPackageName(String packageName) { 12211 // reader 12212 synchronized (mPackages) { 12213 return mSettings.getInstallerPackageNameLPr(packageName); 12214 } 12215 } 12216 12217 @Override 12218 public int getApplicationEnabledSetting(String packageName, int userId) { 12219 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12220 int uid = Binder.getCallingUid(); 12221 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 12222 // reader 12223 synchronized (mPackages) { 12224 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12225 } 12226 } 12227 12228 @Override 12229 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12230 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12231 int uid = Binder.getCallingUid(); 12232 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 12233 // reader 12234 synchronized (mPackages) { 12235 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12236 } 12237 } 12238 12239 @Override 12240 public void enterSafeMode() { 12241 enforceSystemOrRoot("Only the system can request entering safe mode"); 12242 12243 if (!mSystemReady) { 12244 mSafeMode = true; 12245 } 12246 } 12247 12248 @Override 12249 public void systemReady() { 12250 mSystemReady = true; 12251 12252 // Read the compatibilty setting when the system is ready. 12253 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12254 mContext.getContentResolver(), 12255 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12256 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12257 if (DEBUG_SETTINGS) { 12258 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12259 } 12260 12261 synchronized (mPackages) { 12262 // Verify that all of the preferred activity components actually 12263 // exist. It is possible for applications to be updated and at 12264 // that point remove a previously declared activity component that 12265 // had been set as a preferred activity. We try to clean this up 12266 // the next time we encounter that preferred activity, but it is 12267 // possible for the user flow to never be able to return to that 12268 // situation so here we do a sanity check to make sure we haven't 12269 // left any junk around. 12270 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12271 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12272 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12273 removed.clear(); 12274 for (PreferredActivity pa : pir.filterSet()) { 12275 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12276 removed.add(pa); 12277 } 12278 } 12279 if (removed.size() > 0) { 12280 for (int r=0; r<removed.size(); r++) { 12281 PreferredActivity pa = removed.get(r); 12282 Slog.w(TAG, "Removing dangling preferred activity: " 12283 + pa.mPref.mComponent); 12284 pir.removeFilter(pa); 12285 } 12286 mSettings.writePackageRestrictionsLPr( 12287 mSettings.mPreferredActivities.keyAt(i)); 12288 } 12289 } 12290 } 12291 sUserManager.systemReady(); 12292 12293 // Kick off any messages waiting for system ready 12294 if (mPostSystemReadyMessages != null) { 12295 for (Message msg : mPostSystemReadyMessages) { 12296 msg.sendToTarget(); 12297 } 12298 mPostSystemReadyMessages = null; 12299 } 12300 } 12301 12302 @Override 12303 public boolean isSafeMode() { 12304 return mSafeMode; 12305 } 12306 12307 @Override 12308 public boolean hasSystemUidErrors() { 12309 return mHasSystemUidErrors; 12310 } 12311 12312 static String arrayToString(int[] array) { 12313 StringBuffer buf = new StringBuffer(128); 12314 buf.append('['); 12315 if (array != null) { 12316 for (int i=0; i<array.length; i++) { 12317 if (i > 0) buf.append(", "); 12318 buf.append(array[i]); 12319 } 12320 } 12321 buf.append(']'); 12322 return buf.toString(); 12323 } 12324 12325 static class DumpState { 12326 public static final int DUMP_LIBS = 1 << 0; 12327 public static final int DUMP_FEATURES = 1 << 1; 12328 public static final int DUMP_RESOLVERS = 1 << 2; 12329 public static final int DUMP_PERMISSIONS = 1 << 3; 12330 public static final int DUMP_PACKAGES = 1 << 4; 12331 public static final int DUMP_SHARED_USERS = 1 << 5; 12332 public static final int DUMP_MESSAGES = 1 << 6; 12333 public static final int DUMP_PROVIDERS = 1 << 7; 12334 public static final int DUMP_VERIFIERS = 1 << 8; 12335 public static final int DUMP_PREFERRED = 1 << 9; 12336 public static final int DUMP_PREFERRED_XML = 1 << 10; 12337 public static final int DUMP_KEYSETS = 1 << 11; 12338 public static final int DUMP_VERSION = 1 << 12; 12339 public static final int DUMP_INSTALLS = 1 << 13; 12340 12341 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12342 12343 private int mTypes; 12344 12345 private int mOptions; 12346 12347 private boolean mTitlePrinted; 12348 12349 private SharedUserSetting mSharedUser; 12350 12351 public boolean isDumping(int type) { 12352 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12353 return true; 12354 } 12355 12356 return (mTypes & type) != 0; 12357 } 12358 12359 public void setDump(int type) { 12360 mTypes |= type; 12361 } 12362 12363 public boolean isOptionEnabled(int option) { 12364 return (mOptions & option) != 0; 12365 } 12366 12367 public void setOptionEnabled(int option) { 12368 mOptions |= option; 12369 } 12370 12371 public boolean onTitlePrinted() { 12372 final boolean printed = mTitlePrinted; 12373 mTitlePrinted = true; 12374 return printed; 12375 } 12376 12377 public boolean getTitlePrinted() { 12378 return mTitlePrinted; 12379 } 12380 12381 public void setTitlePrinted(boolean enabled) { 12382 mTitlePrinted = enabled; 12383 } 12384 12385 public SharedUserSetting getSharedUser() { 12386 return mSharedUser; 12387 } 12388 12389 public void setSharedUser(SharedUserSetting user) { 12390 mSharedUser = user; 12391 } 12392 } 12393 12394 @Override 12395 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12396 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12397 != PackageManager.PERMISSION_GRANTED) { 12398 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12399 + Binder.getCallingPid() 12400 + ", uid=" + Binder.getCallingUid() 12401 + " without permission " 12402 + android.Manifest.permission.DUMP); 12403 return; 12404 } 12405 12406 DumpState dumpState = new DumpState(); 12407 boolean fullPreferred = false; 12408 boolean checkin = false; 12409 12410 String packageName = null; 12411 12412 int opti = 0; 12413 while (opti < args.length) { 12414 String opt = args[opti]; 12415 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12416 break; 12417 } 12418 opti++; 12419 12420 if ("-a".equals(opt)) { 12421 // Right now we only know how to print all. 12422 } else if ("-h".equals(opt)) { 12423 pw.println("Package manager dump options:"); 12424 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12425 pw.println(" --checkin: dump for a checkin"); 12426 pw.println(" -f: print details of intent filters"); 12427 pw.println(" -h: print this help"); 12428 pw.println(" cmd may be one of:"); 12429 pw.println(" l[ibraries]: list known shared libraries"); 12430 pw.println(" f[ibraries]: list device features"); 12431 pw.println(" k[eysets]: print known keysets"); 12432 pw.println(" r[esolvers]: dump intent resolvers"); 12433 pw.println(" perm[issions]: dump permissions"); 12434 pw.println(" pref[erred]: print preferred package settings"); 12435 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12436 pw.println(" prov[iders]: dump content providers"); 12437 pw.println(" p[ackages]: dump installed packages"); 12438 pw.println(" s[hared-users]: dump shared user IDs"); 12439 pw.println(" m[essages]: print collected runtime messages"); 12440 pw.println(" v[erifiers]: print package verifier info"); 12441 pw.println(" version: print database version info"); 12442 pw.println(" write: write current settings now"); 12443 pw.println(" <package.name>: info about given package"); 12444 pw.println(" installs: details about install sessions"); 12445 return; 12446 } else if ("--checkin".equals(opt)) { 12447 checkin = true; 12448 } else if ("-f".equals(opt)) { 12449 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12450 } else { 12451 pw.println("Unknown argument: " + opt + "; use -h for help"); 12452 } 12453 } 12454 12455 // Is the caller requesting to dump a particular piece of data? 12456 if (opti < args.length) { 12457 String cmd = args[opti]; 12458 opti++; 12459 // Is this a package name? 12460 if ("android".equals(cmd) || cmd.contains(".")) { 12461 packageName = cmd; 12462 // When dumping a single package, we always dump all of its 12463 // filter information since the amount of data will be reasonable. 12464 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12465 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12466 dumpState.setDump(DumpState.DUMP_LIBS); 12467 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12468 dumpState.setDump(DumpState.DUMP_FEATURES); 12469 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12470 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12471 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12472 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12473 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12474 dumpState.setDump(DumpState.DUMP_PREFERRED); 12475 } else if ("preferred-xml".equals(cmd)) { 12476 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12477 if (opti < args.length && "--full".equals(args[opti])) { 12478 fullPreferred = true; 12479 opti++; 12480 } 12481 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12482 dumpState.setDump(DumpState.DUMP_PACKAGES); 12483 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12484 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12485 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12486 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12487 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12488 dumpState.setDump(DumpState.DUMP_MESSAGES); 12489 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12490 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12491 } else if ("version".equals(cmd)) { 12492 dumpState.setDump(DumpState.DUMP_VERSION); 12493 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12494 dumpState.setDump(DumpState.DUMP_KEYSETS); 12495 } else if ("installs".equals(cmd)) { 12496 dumpState.setDump(DumpState.DUMP_INSTALLS); 12497 } else if ("write".equals(cmd)) { 12498 synchronized (mPackages) { 12499 mSettings.writeLPr(); 12500 pw.println("Settings written."); 12501 return; 12502 } 12503 } 12504 } 12505 12506 if (checkin) { 12507 pw.println("vers,1"); 12508 } 12509 12510 // reader 12511 synchronized (mPackages) { 12512 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12513 if (!checkin) { 12514 if (dumpState.onTitlePrinted()) 12515 pw.println(); 12516 pw.println("Database versions:"); 12517 pw.print(" SDK Version:"); 12518 pw.print(" internal="); 12519 pw.print(mSettings.mInternalSdkPlatform); 12520 pw.print(" external="); 12521 pw.println(mSettings.mExternalSdkPlatform); 12522 pw.print(" DB Version:"); 12523 pw.print(" internal="); 12524 pw.print(mSettings.mInternalDatabaseVersion); 12525 pw.print(" external="); 12526 pw.println(mSettings.mExternalDatabaseVersion); 12527 } 12528 } 12529 12530 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12531 if (!checkin) { 12532 if (dumpState.onTitlePrinted()) 12533 pw.println(); 12534 pw.println("Verifiers:"); 12535 pw.print(" Required: "); 12536 pw.print(mRequiredVerifierPackage); 12537 pw.print(" (uid="); 12538 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12539 pw.println(")"); 12540 } else if (mRequiredVerifierPackage != null) { 12541 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12542 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12543 } 12544 } 12545 12546 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12547 boolean printedHeader = false; 12548 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12549 while (it.hasNext()) { 12550 String name = it.next(); 12551 SharedLibraryEntry ent = mSharedLibraries.get(name); 12552 if (!checkin) { 12553 if (!printedHeader) { 12554 if (dumpState.onTitlePrinted()) 12555 pw.println(); 12556 pw.println("Libraries:"); 12557 printedHeader = true; 12558 } 12559 pw.print(" "); 12560 } else { 12561 pw.print("lib,"); 12562 } 12563 pw.print(name); 12564 if (!checkin) { 12565 pw.print(" -> "); 12566 } 12567 if (ent.path != null) { 12568 if (!checkin) { 12569 pw.print("(jar) "); 12570 pw.print(ent.path); 12571 } else { 12572 pw.print(",jar,"); 12573 pw.print(ent.path); 12574 } 12575 } else { 12576 if (!checkin) { 12577 pw.print("(apk) "); 12578 pw.print(ent.apk); 12579 } else { 12580 pw.print(",apk,"); 12581 pw.print(ent.apk); 12582 } 12583 } 12584 pw.println(); 12585 } 12586 } 12587 12588 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12589 if (dumpState.onTitlePrinted()) 12590 pw.println(); 12591 if (!checkin) { 12592 pw.println("Features:"); 12593 } 12594 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12595 while (it.hasNext()) { 12596 String name = it.next(); 12597 if (!checkin) { 12598 pw.print(" "); 12599 } else { 12600 pw.print("feat,"); 12601 } 12602 pw.println(name); 12603 } 12604 } 12605 12606 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12607 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12608 : "Activity Resolver Table:", " ", packageName, 12609 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12610 dumpState.setTitlePrinted(true); 12611 } 12612 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12613 : "Receiver Resolver Table:", " ", packageName, 12614 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12615 dumpState.setTitlePrinted(true); 12616 } 12617 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12618 : "Service Resolver Table:", " ", packageName, 12619 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12620 dumpState.setTitlePrinted(true); 12621 } 12622 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12623 : "Provider Resolver Table:", " ", packageName, 12624 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12625 dumpState.setTitlePrinted(true); 12626 } 12627 } 12628 12629 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12630 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12631 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12632 int user = mSettings.mPreferredActivities.keyAt(i); 12633 if (pir.dump(pw, 12634 dumpState.getTitlePrinted() 12635 ? "\nPreferred Activities User " + user + ":" 12636 : "Preferred Activities User " + user + ":", " ", 12637 packageName, true, false)) { 12638 dumpState.setTitlePrinted(true); 12639 } 12640 } 12641 } 12642 12643 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12644 pw.flush(); 12645 FileOutputStream fout = new FileOutputStream(fd); 12646 BufferedOutputStream str = new BufferedOutputStream(fout); 12647 XmlSerializer serializer = new FastXmlSerializer(); 12648 try { 12649 serializer.setOutput(str, "utf-8"); 12650 serializer.startDocument(null, true); 12651 serializer.setFeature( 12652 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12653 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12654 serializer.endDocument(); 12655 serializer.flush(); 12656 } catch (IllegalArgumentException e) { 12657 pw.println("Failed writing: " + e); 12658 } catch (IllegalStateException e) { 12659 pw.println("Failed writing: " + e); 12660 } catch (IOException e) { 12661 pw.println("Failed writing: " + e); 12662 } 12663 } 12664 12665 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12666 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12667 if (packageName == null) { 12668 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12669 if (iperm == 0) { 12670 if (dumpState.onTitlePrinted()) 12671 pw.println(); 12672 pw.println("AppOp Permissions:"); 12673 } 12674 pw.print(" AppOp Permission "); 12675 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12676 pw.println(":"); 12677 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12678 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12679 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12680 } 12681 } 12682 } 12683 } 12684 12685 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12686 boolean printedSomething = false; 12687 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12688 if (packageName != null && !packageName.equals(p.info.packageName)) { 12689 continue; 12690 } 12691 if (!printedSomething) { 12692 if (dumpState.onTitlePrinted()) 12693 pw.println(); 12694 pw.println("Registered ContentProviders:"); 12695 printedSomething = true; 12696 } 12697 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12698 pw.print(" "); pw.println(p.toString()); 12699 } 12700 printedSomething = false; 12701 for (Map.Entry<String, PackageParser.Provider> entry : 12702 mProvidersByAuthority.entrySet()) { 12703 PackageParser.Provider p = entry.getValue(); 12704 if (packageName != null && !packageName.equals(p.info.packageName)) { 12705 continue; 12706 } 12707 if (!printedSomething) { 12708 if (dumpState.onTitlePrinted()) 12709 pw.println(); 12710 pw.println("ContentProvider Authorities:"); 12711 printedSomething = true; 12712 } 12713 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12714 pw.print(" "); pw.println(p.toString()); 12715 if (p.info != null && p.info.applicationInfo != null) { 12716 final String appInfo = p.info.applicationInfo.toString(); 12717 pw.print(" applicationInfo="); pw.println(appInfo); 12718 } 12719 } 12720 } 12721 12722 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12723 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12724 } 12725 12726 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12727 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12728 } 12729 12730 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12731 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 12732 } 12733 12734 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 12735 // XXX should handle packageName != null by dumping only install data that 12736 // the given package is involved with. 12737 if (dumpState.onTitlePrinted()) pw.println(); 12738 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12739 } 12740 12741 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12742 if (dumpState.onTitlePrinted()) pw.println(); 12743 mSettings.dumpReadMessagesLPr(pw, dumpState); 12744 12745 pw.println(); 12746 pw.println("Package warning messages:"); 12747 final File fname = getSettingsProblemFile(); 12748 FileInputStream in = null; 12749 try { 12750 in = new FileInputStream(fname); 12751 final int avail = in.available(); 12752 final byte[] data = new byte[avail]; 12753 in.read(data); 12754 pw.print(new String(data)); 12755 } catch (FileNotFoundException e) { 12756 } catch (IOException e) { 12757 } finally { 12758 if (in != null) { 12759 try { 12760 in.close(); 12761 } catch (IOException e) { 12762 } 12763 } 12764 } 12765 } 12766 12767 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 12768 BufferedReader in = null; 12769 String line = null; 12770 try { 12771 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12772 while ((line = in.readLine()) != null) { 12773 pw.print("msg,"); 12774 pw.println(line); 12775 } 12776 } catch (IOException ignored) { 12777 } finally { 12778 IoUtils.closeQuietly(in); 12779 } 12780 } 12781 } 12782 } 12783 12784 // ------- apps on sdcard specific code ------- 12785 static final boolean DEBUG_SD_INSTALL = false; 12786 12787 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12788 12789 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12790 12791 private boolean mMediaMounted = false; 12792 12793 static String getEncryptKey() { 12794 try { 12795 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12796 SD_ENCRYPTION_KEYSTORE_NAME); 12797 if (sdEncKey == null) { 12798 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12799 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12800 if (sdEncKey == null) { 12801 Slog.e(TAG, "Failed to create encryption keys"); 12802 return null; 12803 } 12804 } 12805 return sdEncKey; 12806 } catch (NoSuchAlgorithmException nsae) { 12807 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12808 return null; 12809 } catch (IOException ioe) { 12810 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12811 return null; 12812 } 12813 } 12814 12815 /* 12816 * Update media status on PackageManager. 12817 */ 12818 @Override 12819 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12820 int callingUid = Binder.getCallingUid(); 12821 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12822 throw new SecurityException("Media status can only be updated by the system"); 12823 } 12824 // reader; this apparently protects mMediaMounted, but should probably 12825 // be a different lock in that case. 12826 synchronized (mPackages) { 12827 Log.i(TAG, "Updating external media status from " 12828 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12829 + (mediaStatus ? "mounted" : "unmounted")); 12830 if (DEBUG_SD_INSTALL) 12831 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12832 + ", mMediaMounted=" + mMediaMounted); 12833 if (mediaStatus == mMediaMounted) { 12834 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12835 : 0, -1); 12836 mHandler.sendMessage(msg); 12837 return; 12838 } 12839 mMediaMounted = mediaStatus; 12840 } 12841 // Queue up an async operation since the package installation may take a 12842 // little while. 12843 mHandler.post(new Runnable() { 12844 public void run() { 12845 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12846 } 12847 }); 12848 } 12849 12850 /** 12851 * Called by MountService when the initial ASECs to scan are available. 12852 * Should block until all the ASEC containers are finished being scanned. 12853 */ 12854 public void scanAvailableAsecs() { 12855 updateExternalMediaStatusInner(true, false, false); 12856 if (mShouldRestoreconData) { 12857 SELinuxMMAC.setRestoreconDone(); 12858 mShouldRestoreconData = false; 12859 } 12860 } 12861 12862 /* 12863 * Collect information of applications on external media, map them against 12864 * existing containers and update information based on current mount status. 12865 * Please note that we always have to report status if reportStatus has been 12866 * set to true especially when unloading packages. 12867 */ 12868 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12869 boolean externalStorage) { 12870 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12871 int[] uidArr = EmptyArray.INT; 12872 12873 final String[] list = PackageHelper.getSecureContainerList(); 12874 if (ArrayUtils.isEmpty(list)) { 12875 Log.i(TAG, "No secure containers found"); 12876 } else { 12877 // Process list of secure containers and categorize them 12878 // as active or stale based on their package internal state. 12879 12880 // reader 12881 synchronized (mPackages) { 12882 for (String cid : list) { 12883 // Leave stages untouched for now; installer service owns them 12884 if (PackageInstallerService.isStageName(cid)) continue; 12885 12886 if (DEBUG_SD_INSTALL) 12887 Log.i(TAG, "Processing container " + cid); 12888 String pkgName = getAsecPackageName(cid); 12889 if (pkgName == null) { 12890 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12891 continue; 12892 } 12893 if (DEBUG_SD_INSTALL) 12894 Log.i(TAG, "Looking for pkg : " + pkgName); 12895 12896 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12897 if (ps == null) { 12898 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12899 continue; 12900 } 12901 12902 /* 12903 * Skip packages that are not external if we're unmounting 12904 * external storage. 12905 */ 12906 if (externalStorage && !isMounted && !isExternal(ps)) { 12907 continue; 12908 } 12909 12910 final AsecInstallArgs args = new AsecInstallArgs(cid, 12911 getAppDexInstructionSets(ps), isForwardLocked(ps)); 12912 // The package status is changed only if the code path 12913 // matches between settings and the container id. 12914 if (ps.codePathString != null 12915 && ps.codePathString.startsWith(args.getCodePath())) { 12916 if (DEBUG_SD_INSTALL) { 12917 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12918 + " at code path: " + ps.codePathString); 12919 } 12920 12921 // We do have a valid package installed on sdcard 12922 processCids.put(args, ps.codePathString); 12923 final int uid = ps.appId; 12924 if (uid != -1) { 12925 uidArr = ArrayUtils.appendInt(uidArr, uid); 12926 } 12927 } else { 12928 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12929 + ps.codePathString); 12930 } 12931 } 12932 } 12933 12934 Arrays.sort(uidArr); 12935 } 12936 12937 // Process packages with valid entries. 12938 if (isMounted) { 12939 if (DEBUG_SD_INSTALL) 12940 Log.i(TAG, "Loading packages"); 12941 loadMediaPackages(processCids, uidArr); 12942 startCleaningPackages(); 12943 mInstallerService.onSecureContainersAvailable(); 12944 } else { 12945 if (DEBUG_SD_INSTALL) 12946 Log.i(TAG, "Unloading packages"); 12947 unloadMediaPackages(processCids, uidArr, reportStatus); 12948 } 12949 } 12950 12951 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12952 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12953 int size = pkgList.size(); 12954 if (size > 0) { 12955 // Send broadcasts here 12956 Bundle extras = new Bundle(); 12957 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12958 .toArray(new String[size])); 12959 if (uidArr != null) { 12960 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12961 } 12962 if (replacing) { 12963 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12964 } 12965 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12966 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12967 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12968 } 12969 } 12970 12971 /* 12972 * Look at potentially valid container ids from processCids If package 12973 * information doesn't match the one on record or package scanning fails, 12974 * the cid is added to list of removeCids. We currently don't delete stale 12975 * containers. 12976 */ 12977 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12978 ArrayList<String> pkgList = new ArrayList<String>(); 12979 Set<AsecInstallArgs> keys = processCids.keySet(); 12980 12981 for (AsecInstallArgs args : keys) { 12982 String codePath = processCids.get(args); 12983 if (DEBUG_SD_INSTALL) 12984 Log.i(TAG, "Loading container : " + args.cid); 12985 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12986 try { 12987 // Make sure there are no container errors first. 12988 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12989 Slog.e(TAG, "Failed to mount cid : " + args.cid 12990 + " when installing from sdcard"); 12991 continue; 12992 } 12993 // Check code path here. 12994 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12995 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12996 + " does not match one in settings " + codePath); 12997 continue; 12998 } 12999 // Parse package 13000 int parseFlags = mDefParseFlags; 13001 if (args.isExternal()) { 13002 parseFlags |= PackageParser.PARSE_ON_SDCARD; 13003 } 13004 if (args.isFwdLocked()) { 13005 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 13006 } 13007 13008 synchronized (mInstallLock) { 13009 PackageParser.Package pkg = null; 13010 try { 13011 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 13012 } catch (PackageManagerException e) { 13013 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 13014 } 13015 // Scan the package 13016 if (pkg != null) { 13017 /* 13018 * TODO why is the lock being held? doPostInstall is 13019 * called in other places without the lock. This needs 13020 * to be straightened out. 13021 */ 13022 // writer 13023 synchronized (mPackages) { 13024 retCode = PackageManager.INSTALL_SUCCEEDED; 13025 pkgList.add(pkg.packageName); 13026 // Post process args 13027 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 13028 pkg.applicationInfo.uid); 13029 } 13030 } else { 13031 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 13032 } 13033 } 13034 13035 } finally { 13036 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 13037 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 13038 } 13039 } 13040 } 13041 // writer 13042 synchronized (mPackages) { 13043 // If the platform SDK has changed since the last time we booted, 13044 // we need to re-grant app permission to catch any new ones that 13045 // appear. This is really a hack, and means that apps can in some 13046 // cases get permissions that the user didn't initially explicitly 13047 // allow... it would be nice to have some better way to handle 13048 // this situation. 13049 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 13050 if (regrantPermissions) 13051 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 13052 + mSdkVersion + "; regranting permissions for external storage"); 13053 mSettings.mExternalSdkPlatform = mSdkVersion; 13054 13055 // Make sure group IDs have been assigned, and any permission 13056 // changes in other apps are accounted for 13057 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 13058 | (regrantPermissions 13059 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 13060 : 0)); 13061 13062 mSettings.updateExternalDatabaseVersion(); 13063 13064 // can downgrade to reader 13065 // Persist settings 13066 mSettings.writeLPr(); 13067 } 13068 // Send a broadcast to let everyone know we are done processing 13069 if (pkgList.size() > 0) { 13070 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13071 } 13072 } 13073 13074 /* 13075 * Utility method to unload a list of specified containers 13076 */ 13077 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 13078 // Just unmount all valid containers. 13079 for (AsecInstallArgs arg : cidArgs) { 13080 synchronized (mInstallLock) { 13081 arg.doPostDeleteLI(false); 13082 } 13083 } 13084 } 13085 13086 /* 13087 * Unload packages mounted on external media. This involves deleting package 13088 * data from internal structures, sending broadcasts about diabled packages, 13089 * gc'ing to free up references, unmounting all secure containers 13090 * corresponding to packages on external media, and posting a 13091 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 13092 * that we always have to post this message if status has been requested no 13093 * matter what. 13094 */ 13095 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 13096 final boolean reportStatus) { 13097 if (DEBUG_SD_INSTALL) 13098 Log.i(TAG, "unloading media packages"); 13099 ArrayList<String> pkgList = new ArrayList<String>(); 13100 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 13101 final Set<AsecInstallArgs> keys = processCids.keySet(); 13102 for (AsecInstallArgs args : keys) { 13103 String pkgName = args.getPackageName(); 13104 if (DEBUG_SD_INSTALL) 13105 Log.i(TAG, "Trying to unload pkg : " + pkgName); 13106 // Delete package internally 13107 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 13108 synchronized (mInstallLock) { 13109 boolean res = deletePackageLI(pkgName, null, false, null, null, 13110 PackageManager.DELETE_KEEP_DATA, outInfo, false); 13111 if (res) { 13112 pkgList.add(pkgName); 13113 } else { 13114 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 13115 failedList.add(args); 13116 } 13117 } 13118 } 13119 13120 // reader 13121 synchronized (mPackages) { 13122 // We didn't update the settings after removing each package; 13123 // write them now for all packages. 13124 mSettings.writeLPr(); 13125 } 13126 13127 // We have to absolutely send UPDATED_MEDIA_STATUS only 13128 // after confirming that all the receivers processed the ordered 13129 // broadcast when packages get disabled, force a gc to clean things up. 13130 // and unload all the containers. 13131 if (pkgList.size() > 0) { 13132 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 13133 new IIntentReceiver.Stub() { 13134 public void performReceive(Intent intent, int resultCode, String data, 13135 Bundle extras, boolean ordered, boolean sticky, 13136 int sendingUser) throws RemoteException { 13137 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 13138 reportStatus ? 1 : 0, 1, keys); 13139 mHandler.sendMessage(msg); 13140 } 13141 }); 13142 } else { 13143 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 13144 keys); 13145 mHandler.sendMessage(msg); 13146 } 13147 } 13148 13149 /** Binder call */ 13150 @Override 13151 public void movePackage(final String packageName, final IPackageMoveObserver observer, 13152 final int flags) { 13153 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 13154 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 13155 int returnCode = PackageManager.MOVE_SUCCEEDED; 13156 int currInstallFlags = 0; 13157 int newInstallFlags = 0; 13158 13159 File codeFile = null; 13160 String installerPackageName = null; 13161 String packageAbiOverride = null; 13162 13163 // reader 13164 synchronized (mPackages) { 13165 final PackageParser.Package pkg = mPackages.get(packageName); 13166 final PackageSetting ps = mSettings.mPackages.get(packageName); 13167 if (pkg == null || ps == null) { 13168 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13169 } else { 13170 // Disable moving fwd locked apps and system packages 13171 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 13172 Slog.w(TAG, "Cannot move system application"); 13173 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13174 } else if (pkg.mOperationPending) { 13175 Slog.w(TAG, "Attempt to move package which has pending operations"); 13176 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13177 } else { 13178 // Find install location first 13179 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13180 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13181 Slog.w(TAG, "Ambigous flags specified for move location."); 13182 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13183 } else { 13184 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13185 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13186 currInstallFlags = isExternal(pkg) 13187 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13188 13189 if (newInstallFlags == currInstallFlags) { 13190 Slog.w(TAG, "No move required. Trying to move to same location"); 13191 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13192 } else { 13193 if (isForwardLocked(pkg)) { 13194 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13195 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13196 } 13197 } 13198 } 13199 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13200 pkg.mOperationPending = true; 13201 } 13202 } 13203 13204 codeFile = new File(pkg.codePath); 13205 installerPackageName = ps.installerPackageName; 13206 packageAbiOverride = ps.cpuAbiOverrideString; 13207 } 13208 } 13209 13210 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13211 try { 13212 observer.packageMoved(packageName, returnCode); 13213 } catch (RemoteException ignored) { 13214 } 13215 return; 13216 } 13217 13218 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 13219 @Override 13220 public void onUserActionRequired(Intent intent) throws RemoteException { 13221 throw new IllegalStateException(); 13222 } 13223 13224 @Override 13225 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 13226 Bundle extras) throws RemoteException { 13227 Slog.d(TAG, "Install result for move: " 13228 + PackageManager.installStatusToString(returnCode, msg)); 13229 13230 // We usually have a new package now after the install, but if 13231 // we failed we need to clear the pending flag on the original 13232 // package object. 13233 synchronized (mPackages) { 13234 final PackageParser.Package pkg = mPackages.get(packageName); 13235 if (pkg != null) { 13236 pkg.mOperationPending = false; 13237 } 13238 } 13239 13240 final int status = PackageManager.installStatusToPublicStatus(returnCode); 13241 switch (status) { 13242 case PackageInstaller.STATUS_SUCCESS: 13243 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 13244 break; 13245 case PackageInstaller.STATUS_FAILURE_STORAGE: 13246 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 13247 break; 13248 default: 13249 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 13250 break; 13251 } 13252 } 13253 }; 13254 13255 // Treat a move like reinstalling an existing app, which ensures that we 13256 // process everythign uniformly, like unpacking native libraries. 13257 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 13258 13259 final Message msg = mHandler.obtainMessage(INIT_COPY); 13260 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 13261 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 13262 installerPackageName, null, user, packageAbiOverride); 13263 mHandler.sendMessage(msg); 13264 } 13265 13266 @Override 13267 public boolean setInstallLocation(int loc) { 13268 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13269 null); 13270 if (getInstallLocation() == loc) { 13271 return true; 13272 } 13273 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13274 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13275 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13276 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13277 return true; 13278 } 13279 return false; 13280 } 13281 13282 @Override 13283 public int getInstallLocation() { 13284 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13285 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13286 PackageHelper.APP_INSTALL_AUTO); 13287 } 13288 13289 /** Called by UserManagerService */ 13290 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 13291 mDirtyUsers.remove(userHandle); 13292 mSettings.removeUserLPw(userHandle); 13293 mPendingBroadcasts.remove(userHandle); 13294 if (mInstaller != null) { 13295 // Technically, we shouldn't be doing this with the package lock 13296 // held. However, this is very rare, and there is already so much 13297 // other disk I/O going on, that we'll let it slide for now. 13298 mInstaller.removeUserDataDirs(userHandle); 13299 } 13300 mUserNeedsBadging.delete(userHandle); 13301 removeUnusedPackagesLILPw(userManager, userHandle); 13302 } 13303 13304 /** 13305 * We're removing userHandle and would like to remove any downloaded packages 13306 * that are no longer in use by any other user. 13307 * @param userHandle the user being removed 13308 */ 13309 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 13310 final boolean DEBUG_CLEAN_APKS = false; 13311 int [] users = userManager.getUserIdsLPr(); 13312 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 13313 while (psit.hasNext()) { 13314 PackageSetting ps = psit.next(); 13315 if (ps.pkg == null) { 13316 continue; 13317 } 13318 final String packageName = ps.pkg.packageName; 13319 // Skip over if system app 13320 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13321 continue; 13322 } 13323 if (DEBUG_CLEAN_APKS) { 13324 Slog.i(TAG, "Checking package " + packageName); 13325 } 13326 boolean keep = false; 13327 for (int i = 0; i < users.length; i++) { 13328 if (users[i] != userHandle && ps.getInstalled(users[i])) { 13329 keep = true; 13330 if (DEBUG_CLEAN_APKS) { 13331 Slog.i(TAG, " Keeping package " + packageName + " for user " 13332 + users[i]); 13333 } 13334 break; 13335 } 13336 } 13337 if (!keep) { 13338 if (DEBUG_CLEAN_APKS) { 13339 Slog.i(TAG, " Removing package " + packageName); 13340 } 13341 mHandler.post(new Runnable() { 13342 public void run() { 13343 deletePackageX(packageName, userHandle, 0); 13344 } //end run 13345 }); 13346 } 13347 } 13348 } 13349 13350 /** Called by UserManagerService */ 13351 void createNewUserLILPw(int userHandle, File path) { 13352 if (mInstaller != null) { 13353 mInstaller.createUserConfig(userHandle); 13354 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13355 } 13356 } 13357 13358 @Override 13359 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13360 mContext.enforceCallingOrSelfPermission( 13361 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13362 "Only package verification agents can read the verifier device identity"); 13363 13364 synchronized (mPackages) { 13365 return mSettings.getVerifierDeviceIdentityLPw(); 13366 } 13367 } 13368 13369 @Override 13370 public void setPermissionEnforced(String permission, boolean enforced) { 13371 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13372 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13373 synchronized (mPackages) { 13374 if (mSettings.mReadExternalStorageEnforced == null 13375 || mSettings.mReadExternalStorageEnforced != enforced) { 13376 mSettings.mReadExternalStorageEnforced = enforced; 13377 mSettings.writeLPr(); 13378 } 13379 } 13380 // kill any non-foreground processes so we restart them and 13381 // grant/revoke the GID. 13382 final IActivityManager am = ActivityManagerNative.getDefault(); 13383 if (am != null) { 13384 final long token = Binder.clearCallingIdentity(); 13385 try { 13386 am.killProcessesBelowForeground("setPermissionEnforcement"); 13387 } catch (RemoteException e) { 13388 } finally { 13389 Binder.restoreCallingIdentity(token); 13390 } 13391 } 13392 } else { 13393 throw new IllegalArgumentException("No selective enforcement for " + permission); 13394 } 13395 } 13396 13397 @Override 13398 @Deprecated 13399 public boolean isPermissionEnforced(String permission) { 13400 return true; 13401 } 13402 13403 @Override 13404 public boolean isStorageLow() { 13405 final long token = Binder.clearCallingIdentity(); 13406 try { 13407 final DeviceStorageMonitorInternal 13408 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13409 if (dsm != null) { 13410 return dsm.isMemoryLow(); 13411 } else { 13412 return false; 13413 } 13414 } finally { 13415 Binder.restoreCallingIdentity(token); 13416 } 13417 } 13418 13419 @Override 13420 public IPackageInstaller getPackageInstaller() { 13421 return mInstallerService; 13422 } 13423 13424 private boolean userNeedsBadging(int userId) { 13425 int index = mUserNeedsBadging.indexOfKey(userId); 13426 if (index < 0) { 13427 final UserInfo userInfo; 13428 final long token = Binder.clearCallingIdentity(); 13429 try { 13430 userInfo = sUserManager.getUserInfo(userId); 13431 } finally { 13432 Binder.restoreCallingIdentity(token); 13433 } 13434 final boolean b; 13435 if (userInfo != null && userInfo.isManagedProfile()) { 13436 b = true; 13437 } else { 13438 b = false; 13439 } 13440 mUserNeedsBadging.put(userId, b); 13441 return b; 13442 } 13443 return mUserNeedsBadging.valueAt(index); 13444 } 13445 13446 @Override 13447 public KeySet getKeySetByAlias(String packageName, String alias) { 13448 if (packageName == null || alias == null) { 13449 return null; 13450 } 13451 synchronized(mPackages) { 13452 final PackageParser.Package pkg = mPackages.get(packageName); 13453 if (pkg == null) { 13454 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13455 throw new IllegalArgumentException("Unknown package: " + packageName); 13456 } 13457 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13458 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13459 } 13460 } 13461 13462 @Override 13463 public KeySet getSigningKeySet(String packageName) { 13464 if (packageName == null) { 13465 return null; 13466 } 13467 synchronized(mPackages) { 13468 final PackageParser.Package pkg = mPackages.get(packageName); 13469 if (pkg == null) { 13470 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13471 throw new IllegalArgumentException("Unknown package: " + packageName); 13472 } 13473 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13474 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13475 throw new SecurityException("May not access signing KeySet of other apps."); 13476 } 13477 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13478 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13479 } 13480 } 13481 13482 @Override 13483 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13484 if (packageName == null || ks == null) { 13485 return false; 13486 } 13487 synchronized(mPackages) { 13488 final PackageParser.Package pkg = mPackages.get(packageName); 13489 if (pkg == null) { 13490 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13491 throw new IllegalArgumentException("Unknown package: " + packageName); 13492 } 13493 IBinder ksh = ks.getToken(); 13494 if (ksh instanceof KeySetHandle) { 13495 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13496 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13497 } 13498 return false; 13499 } 13500 } 13501 13502 @Override 13503 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13504 if (packageName == null || ks == null) { 13505 return false; 13506 } 13507 synchronized(mPackages) { 13508 final PackageParser.Package pkg = mPackages.get(packageName); 13509 if (pkg == null) { 13510 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13511 throw new IllegalArgumentException("Unknown package: " + packageName); 13512 } 13513 IBinder ksh = ks.getToken(); 13514 if (ksh instanceof KeySetHandle) { 13515 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13516 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13517 } 13518 return false; 13519 } 13520 } 13521 13522 public void getUsageStatsIfNoPackageUsageInfo() { 13523 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 13524 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 13525 if (usm == null) { 13526 throw new IllegalStateException("UsageStatsManager must be initialized"); 13527 } 13528 long now = System.currentTimeMillis(); 13529 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 13530 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 13531 String packageName = entry.getKey(); 13532 PackageParser.Package pkg = mPackages.get(packageName); 13533 if (pkg == null) { 13534 continue; 13535 } 13536 UsageStats usage = entry.getValue(); 13537 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 13538 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 13539 } 13540 } 13541 } 13542} 13543